diff options
author | Quentin Le Menez | 2018-01-09 10:09:46 +0000 |
---|---|---|
committer | Quentin Le Menez | 2018-01-09 13:18:15 +0000 |
commit | d98116b5b376f18b6cf626ba4158a35fe9a4a64e (patch) | |
tree | 4458c9c5ada0a216b385813a56ea9a9b8c7b6509 /plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram | |
parent | 453e99bc2dcbd5fabad100f9d0d5f682013c3b19 (diff) | |
download | org.eclipse.papyrus-d98116b5b376f18b6cf626ba4158a35fe9a4a64e.tar.gz org.eclipse.papyrus-d98116b5b376f18b6cf626ba4158a35fe9a4a64e.tar.xz org.eclipse.papyrus-d98116b5b376f18b6cf626ba4158a35fe9a4a64e.zip |
Bug 515367 - [releng] Uniformization of the end of lines to Unix standard
- Format the EOL of all the files matched by: grep -rIUs . | xargs -Ifile dos2unix -k 'file'
Change-Id: I5c41d540a9a67b50de9b912ab35e16cc9a912961
Signed-off-by: Quentin Le Menez <quentin.lemenez@cea.fr>
Diffstat (limited to 'plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram')
182 files changed, 24352 insertions, 24352 deletions
diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/ActivityDiagramCreationCondition.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/ActivityDiagramCreationCondition.java index ce932a50b1e..7d2cb70fbc7 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/ActivityDiagramCreationCondition.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/ActivityDiagramCreationCondition.java @@ -1,29 +1,29 @@ -/*****************************************************************************
- * Copyright (c) 2009 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
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.papyrus.infra.ui.extension.commands.PerspectiveContextDependence;
-
-/**
- * ActivityDiagramCreationCondition class allows to check if an Activity diagram can be added to the
- * selected element.
- */
-public class ActivityDiagramCreationCondition extends PerspectiveContextDependence {
-
- /**
- * @return whether the diagram can be created.
- */
- @Override
- public boolean create(EObject selectedElement) {
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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 + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.papyrus.infra.ui.extension.commands.PerspectiveContextDependence; + +/** + * ActivityDiagramCreationCondition class allows to check if an Activity diagram can be added to the + * selected element. + */ +public class ActivityDiagramCreationCondition extends PerspectiveContextDependence { + + /** + * @return whether the diagram can be created. + */ + @Override + public boolean create(EObject selectedElement) { + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/ActivityDiagramEditorFactory.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/ActivityDiagramEditorFactory.java index 2c394673346..1ae8f097832 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/ActivityDiagramEditorFactory.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/ActivityDiagramEditorFactory.java @@ -1,30 +1,30 @@ -/*****************************************************************************
- * Copyright (c) 2009 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity;
-
-import org.eclipse.papyrus.infra.gmfdiag.common.GmfEditorFactory;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityDiagramEditPart;
-
-/**
- * The editor factory to launch the activity diagram.
- */
-public class ActivityDiagramEditorFactory extends GmfEditorFactory {
-
- /**
- * Instantiates a new activity diagram editor factory.
- */
- public ActivityDiagramEditorFactory() {
- super(UmlActivityDiagramForMultiEditor.class, ActivityDiagramEditPart.MODEL_ID);
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity; + +import org.eclipse.papyrus.infra.gmfdiag.common.GmfEditorFactory; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityDiagramEditPart; + +/** + * The editor factory to launch the activity diagram. + */ +public class ActivityDiagramEditorFactory extends GmfEditorFactory { + + /** + * Instantiates a new activity diagram editor factory. + */ + public ActivityDiagramEditorFactory() { + super(UmlActivityDiagramForMultiEditor.class, ActivityDiagramEditPart.MODEL_ID); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/AbstractContainerNodeDescriptor.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/AbstractContainerNodeDescriptor.java index 88b9f6c941e..38574ab2f27 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/AbstractContainerNodeDescriptor.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/AbstractContainerNodeDescriptor.java @@ -1,171 +1,171 @@ -/*****************************************************************************
- * Copyright (c) 2011 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-
-/**
- * This abstract class describes the required methods to register to the org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension
- * point.
- * These methods allow to recover necessary information on the container node for a given type.
- *
- * @author adaussy
- */
-public abstract class AbstractContainerNodeDescriptor implements IContainerNodeDescriptor {
-
- /**
- * Get the eclass of the model eobject represented by the node
- *
- * @return model object eclass
- */
- @Override
- public abstract EClass getContainerEClass();
-
- @Override
- public List<EClass> getPossibleGraphicalChildren() {
- List<EReference> refs = this.getChildrenReferences();
- List<EClass> result = new ArrayList<EClass>(refs.size());
- for (EReference ref : refs) {
- result.add(ref.getEReferenceType());
- }
- return result;
- }
-
- /**
- * Get the list of references linking the container to children element.
- * Note that these may not be direct containment relations in case the element is only a graphical container.
- *
- * @return the references to contained elements
- */
- @Override
- public abstract List<EReference> getChildrenReferences();
-
- /**
- * Get the list of references linking the child to its parent element.
- * Note that these may not be direct containment relations in case the element is only a graphical container.
- *
- * @return the references to contained elements
- */
- @Override
- public abstract List<EReference> getParentReferences();
-
- /**
- * Get the list of references linking the child to its parent element.
- * Note that these may not be direct containment relations in case the element is only a graphical container.
- *
- * @return the references to contained elements
- */
- @Override
- public abstract Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences();
-
- /**
- * Get the edit part which is registered to the group framework (compartment) from a view of the corresponding node.
- *
- * @return the compartment edit part which is registered to the group framework
- */
- @Override
- public abstract IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart);
-
- /**
- * Give you the right be a graphical parent of child.
- *
- * @param childType
- * EClass of the child you want to test
- * @return
- */
- @Override
- public boolean canIBeGraphicalParentOf(EClass childType) {
- for (EReference reference : this.getChildrenReferences()) {
- if (reference.getEReferenceType().isSuperTypeOf(childType)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Give you the right to be a model parent of child
- *
- * @param childType
- * EClass of the child you want to test
- * @return
- */
- @Override
- public boolean canIBeModelParentOf(EClass childType) {
- for (EReference reference : this.getChildrenReferences()) {
- if (reference.getEReferenceType().isSuperTypeOf(childType) && reference.isContainment()) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Give the reference object which can reference the child.
- *
- * @param childType
- * EClass of the child you want to test
- * @return null if no reference is found
- */
- @Override
- public List<EReference> getReferenceFor(EClass childType) {
- List<EReference> result = new ArrayList<EReference>();
- for (EReference reference : this.getChildrenReferences()) {
- if (reference.getEReferenceType().isSuperTypeOf(childType) && !reference.isContainment()) {
- result.add(reference);
- }
- }
- return result;
- }
-
- /**
- * Give the reference object which can contain the child.
- *
- * @param childType
- * EClass of the child you want to test
- * @return null if no reference is found
- */
- @Override
- public EReference getContainmentReferenceFor(EClass childType) {
- EReference usedReference = null;
- List<EReference> result = new ArrayList<EReference>();
- for (EReference reference : this.getChildrenReferences()) {
- if (reference.getEReferenceType().isSuperTypeOf(childType) && reference.isContainment() && !reference.isDerived()) {
- result.add(reference);
- }
- }
- // Select the best containment relation
- for (EReference ref : result) {
- if (usedReference == null || ref.getEReferenceType().getEAllSuperTypes().contains(usedReference.getEReferenceType())) {
- // the ref feature is more precise than the previously selected one. Use it instead.
- usedReference = ref;
- }
- }
- return usedReference;
- }
-
- @Override
- public int compareTo(IContainerNodeDescriptor o) {
- Integer thisInt = new Integer(getGroupPriority());
- Integer otherInt = new Integer(o.getGroupPriority());
- return thisInt.compareTo(otherInt);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; + +/** + * This abstract class describes the required methods to register to the org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension + * point. + * These methods allow to recover necessary information on the container node for a given type. + * + * @author adaussy + */ +public abstract class AbstractContainerNodeDescriptor implements IContainerNodeDescriptor { + + /** + * Get the eclass of the model eobject represented by the node + * + * @return model object eclass + */ + @Override + public abstract EClass getContainerEClass(); + + @Override + public List<EClass> getPossibleGraphicalChildren() { + List<EReference> refs = this.getChildrenReferences(); + List<EClass> result = new ArrayList<EClass>(refs.size()); + for (EReference ref : refs) { + result.add(ref.getEReferenceType()); + } + return result; + } + + /** + * Get the list of references linking the container to children element. + * Note that these may not be direct containment relations in case the element is only a graphical container. + * + * @return the references to contained elements + */ + @Override + public abstract List<EReference> getChildrenReferences(); + + /** + * Get the list of references linking the child to its parent element. + * Note that these may not be direct containment relations in case the element is only a graphical container. + * + * @return the references to contained elements + */ + @Override + public abstract List<EReference> getParentReferences(); + + /** + * Get the list of references linking the child to its parent element. + * Note that these may not be direct containment relations in case the element is only a graphical container. + * + * @return the references to contained elements + */ + @Override + public abstract Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences(); + + /** + * Get the edit part which is registered to the group framework (compartment) from a view of the corresponding node. + * + * @return the compartment edit part which is registered to the group framework + */ + @Override + public abstract IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart); + + /** + * Give you the right be a graphical parent of child. + * + * @param childType + * EClass of the child you want to test + * @return + */ + @Override + public boolean canIBeGraphicalParentOf(EClass childType) { + for (EReference reference : this.getChildrenReferences()) { + if (reference.getEReferenceType().isSuperTypeOf(childType)) { + return true; + } + } + return false; + } + + /** + * Give you the right to be a model parent of child + * + * @param childType + * EClass of the child you want to test + * @return + */ + @Override + public boolean canIBeModelParentOf(EClass childType) { + for (EReference reference : this.getChildrenReferences()) { + if (reference.getEReferenceType().isSuperTypeOf(childType) && reference.isContainment()) { + return true; + } + } + return false; + } + + /** + * Give the reference object which can reference the child. + * + * @param childType + * EClass of the child you want to test + * @return null if no reference is found + */ + @Override + public List<EReference> getReferenceFor(EClass childType) { + List<EReference> result = new ArrayList<EReference>(); + for (EReference reference : this.getChildrenReferences()) { + if (reference.getEReferenceType().isSuperTypeOf(childType) && !reference.isContainment()) { + result.add(reference); + } + } + return result; + } + + /** + * Give the reference object which can contain the child. + * + * @param childType + * EClass of the child you want to test + * @return null if no reference is found + */ + @Override + public EReference getContainmentReferenceFor(EClass childType) { + EReference usedReference = null; + List<EReference> result = new ArrayList<EReference>(); + for (EReference reference : this.getChildrenReferences()) { + if (reference.getEReferenceType().isSuperTypeOf(childType) && reference.isContainment() && !reference.isDerived()) { + result.add(reference); + } + } + // Select the best containment relation + for (EReference ref : result) { + if (usedReference == null || ref.getEReferenceType().getEAllSuperTypes().contains(usedReference.getEReferenceType())) { + // the ref feature is more precise than the previously selected one. Use it instead. + usedReference = ref; + } + } + return usedReference; + } + + @Override + public int compareTo(IContainerNodeDescriptor o) { + Integer thisInt = new Integer(getGroupPriority()); + Integer otherInt = new Integer(o.getGroupPriority()); + return thisInt.compareTo(otherInt); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ContainerNodeDescriptorRegistry.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ContainerNodeDescriptorRegistry.java index f428924eaba..6981f99b2b0 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ContainerNodeDescriptorRegistry.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ContainerNodeDescriptorRegistry.java @@ -1,97 +1,97 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ActivityContainment;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ActivityNodeContainment;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ActivityPartitionContainment;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ConditionalNodeContainment;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ExpansionRegionContainment;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.InterruptibleActivityRegionContainment;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.LoopNodeContainment;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.SequenceNodeContainment;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.StructuredActivityNodeContainment;
-import org.eclipse.uml2.uml.UMLPackage;
-
-import com.google.common.collect.Lists;
-
-/**
- * Registry of all node and group descriptor
- */
-public final class ContainerNodeDescriptorRegistry {
-
- /**
- * Constructor
- */
- private ContainerNodeDescriptorRegistry() {
- }
-
- /**
- * Registry of all descriptor
- */
- private static Map<EClass, IContainerNodeDescriptor> registry;
- /**
- * Initialize
- * (May be in the future using extension point
- */
- static {
- registry = new HashMap<EClass, IContainerNodeDescriptor>();
- registry.put(UMLPackage.Literals.ACTIVITY_PARTITION, new ActivityPartitionContainment());
- registry.put(UMLPackage.Literals.STRUCTURED_ACTIVITY_NODE, new StructuredActivityNodeContainment());
- registry.put(UMLPackage.Literals.CONDITIONAL_NODE, new ConditionalNodeContainment());
- registry.put(UMLPackage.Literals.EXPANSION_REGION, new ExpansionRegionContainment());
- registry.put(UMLPackage.Literals.INTERRUPTIBLE_ACTIVITY_REGION, new InterruptibleActivityRegionContainment());
- registry.put(UMLPackage.Literals.LOOP_NODE, new LoopNodeContainment());
- registry.put(UMLPackage.Literals.SEQUENCE_NODE, new SequenceNodeContainment());
- registry.put(UMLPackage.Literals.ACTIVITY_NODE, new ActivityNodeContainment());
- registry.put(UMLPackage.Literals.ACTIVITY, new ActivityContainment());
- }
-
- /**
- * SingletonHolder is loaded on the first execution of Singleton.getInstance()
- * or the first access to SingletonHolder.INSTANCE, not before.
- */
- private static class SingletonHolder {
-
- public static final ContainerNodeDescriptorRegistry instance = new ContainerNodeDescriptorRegistry();
- }
-
- public IContainerNodeDescriptor getContainerNodeDescriptor(EClass eclass) {
- try {
- IContainerNodeDescriptor result = registry.get(eclass);
- if (result == null) {
- ArrayList<EClass> superTypes = Lists.newArrayList(eclass.getEAllSuperTypes());
- for (EClass aux : Lists.reverse(superTypes)) {
- result = registry.get(aux);
- if (result != null) {
- return result;
- }
- }
- }
- return result;
- } catch (Exception e) {
- throw new RuntimeException("wrong use of the ContainerNodeDescriptorRegistry");
- }
- }
-
- public static ContainerNodeDescriptorRegistry getInstance() {
- return SingletonHolder.instance;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ActivityContainment; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ActivityNodeContainment; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ActivityPartitionContainment; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ConditionalNodeContainment; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.ExpansionRegionContainment; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.InterruptibleActivityRegionContainment; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.LoopNodeContainment; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.SequenceNodeContainment; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment.StructuredActivityNodeContainment; +import org.eclipse.uml2.uml.UMLPackage; + +import com.google.common.collect.Lists; + +/** + * Registry of all node and group descriptor + */ +public final class ContainerNodeDescriptorRegistry { + + /** + * Constructor + */ + private ContainerNodeDescriptorRegistry() { + } + + /** + * Registry of all descriptor + */ + private static Map<EClass, IContainerNodeDescriptor> registry; + /** + * Initialize + * (May be in the future using extension point + */ + static { + registry = new HashMap<EClass, IContainerNodeDescriptor>(); + registry.put(UMLPackage.Literals.ACTIVITY_PARTITION, new ActivityPartitionContainment()); + registry.put(UMLPackage.Literals.STRUCTURED_ACTIVITY_NODE, new StructuredActivityNodeContainment()); + registry.put(UMLPackage.Literals.CONDITIONAL_NODE, new ConditionalNodeContainment()); + registry.put(UMLPackage.Literals.EXPANSION_REGION, new ExpansionRegionContainment()); + registry.put(UMLPackage.Literals.INTERRUPTIBLE_ACTIVITY_REGION, new InterruptibleActivityRegionContainment()); + registry.put(UMLPackage.Literals.LOOP_NODE, new LoopNodeContainment()); + registry.put(UMLPackage.Literals.SEQUENCE_NODE, new SequenceNodeContainment()); + registry.put(UMLPackage.Literals.ACTIVITY_NODE, new ActivityNodeContainment()); + registry.put(UMLPackage.Literals.ACTIVITY, new ActivityContainment()); + } + + /** + * SingletonHolder is loaded on the first execution of Singleton.getInstance() + * or the first access to SingletonHolder.INSTANCE, not before. + */ + private static class SingletonHolder { + + public static final ContainerNodeDescriptorRegistry instance = new ContainerNodeDescriptorRegistry(); + } + + public IContainerNodeDescriptor getContainerNodeDescriptor(EClass eclass) { + try { + IContainerNodeDescriptor result = registry.get(eclass); + if (result == null) { + ArrayList<EClass> superTypes = Lists.newArrayList(eclass.getEAllSuperTypes()); + for (EClass aux : Lists.reverse(superTypes)) { + result = registry.get(aux); + if (result != null) { + return result; + } + } + } + return result; + } catch (Exception e) { + throw new RuntimeException("wrong use of the ContainerNodeDescriptorRegistry"); + } + } + + public static ContainerNodeDescriptorRegistry getInstance() { + return SingletonHolder.instance; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/GroupEditPolicyProvider.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/GroupEditPolicyProvider.java index 685db64bb36..75d673fb555 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/GroupEditPolicyProvider.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/GroupEditPolicyProvider.java @@ -1,138 +1,138 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gmf.runtime.common.core.service.IOperation;
-import org.eclipse.gmf.runtime.common.core.service.IProviderChangeListener;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
-import org.eclipse.gmf.runtime.diagram.ui.services.editpolicy.CreateEditPoliciesOperation;
-import org.eclipse.gmf.runtime.diagram.ui.services.editpolicy.IEditPolicyProvider;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.ActivityContentCompartmentCreationEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.InterruptibleActivityRegionContentCompartmentCreationEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.ActivityGroupEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.ActivityNodeEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.GroupNotifyingInCreationEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityActivityContentCompartmentEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityDiagramEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionActivityPartitionContentCompartmentEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLVisualIDRegistry;
-import org.eclipse.uml2.uml.ActivityGroup;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Provider for all edit policies related to the group framework
- */
-public class GroupEditPolicyProvider implements IEditPolicyProvider {
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.gmf.runtime.common.core.service.IProvider#addProviderChangeListener(org.eclipse.gmf.runtime.common.core.service.IProviderChangeListener
- * )
- */
- @Override
- public void addProviderChangeListener(IProviderChangeListener listener) {
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.common.core.service.IProvider#removeProviderChangeListener(org.eclipse.gmf.runtime.common.core.service.
- * IProviderChangeListener)
- */
- @Override
- public void removeProviderChangeListener(IProviderChangeListener listener) {
- }
-
- /**
- *
- * {@inheritDoc}
- */
- @Override
- public void createEditPolicies(EditPart editPart) {
- /*
- * Installation of notiying edit polocy
- */
- if (editPart instanceof ActivityEditPart) {
- editPart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY, new ActivityGroupEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY)));
- }
- if (editPart instanceof IGraphicalEditPart && editPart.getParent() instanceof IGraphicalEditPart) {
- IGraphicalEditPart graphEditpart = (IGraphicalEditPart) editPart;
- // is top edit part of the element
- IGraphicalEditPart parentEditPart = (IGraphicalEditPart) editPart.getParent();
- EObject resolveSemanticElement = graphEditpart.resolveSemanticElement();
- if (resolveSemanticElement != null && !resolveSemanticElement.equals(parentEditPart.resolveSemanticElement())) {
- if (resolveSemanticElement instanceof ActivityNode) {
- graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY, new ActivityNodeEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY_NODE)));
- }
- if (resolveSemanticElement instanceof ActivityGroup) {
- graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY, new ActivityGroupEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(resolveSemanticElement.eClass())));
- }
- /*
- * Installation of policy to handle graphicac
- */
- switch (UMLVisualIDRegistry.getVisualID(graphEditpart.getNotationView())) {
- case ActivityPartitionActivityPartitionContentCompartmentEditPart.VISUAL_ID:
- graphEditpart.installEditPolicy(EditPolicyRoles.CREATION_ROLE,
- new ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY_PARTITION)));
- graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY,
- new GroupNotifyingInCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(resolveSemanticElement.eClass())));
- break;
- case InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart.VISUAL_ID:
- graphEditpart.installEditPolicy(EditPolicyRoles.CREATION_ROLE,
- new InterruptibleActivityRegionContentCompartmentCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.INTERRUPTIBLE_ACTIVITY_REGION)));
- graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY,
- new GroupNotifyingInCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(resolveSemanticElement.eClass())));
- break;
- case ActivityActivityContentCompartmentEditPart.VISUAL_ID:
- graphEditpart.installEditPolicy(EditPolicyRoles.CREATION_ROLE, new ActivityContentCompartmentCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY)));
- graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY,
- new GroupNotifyingInCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(resolveSemanticElement.eClass())));
- break;
- default:
- break;
- }
- }
-
- }
- }
-
- /**
- *
- * {@inheritDoc}
- */
- @Override
- public boolean provides(IOperation operation) {
- CreateEditPoliciesOperation epOperation = (CreateEditPoliciesOperation) operation;
- if (!(epOperation.getEditPart() instanceof GraphicalEditPart)) {
- return false;
- }
- GraphicalEditPart gep = (GraphicalEditPart) epOperation.getEditPart();
- String diagramType = gep.getNotationView().getDiagram().getType();
- if (ActivityDiagramEditPart.MODEL_ID.equals(diagramType)) {
- return true;
- }
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.EditPart; +import org.eclipse.gmf.runtime.common.core.service.IOperation; +import org.eclipse.gmf.runtime.common.core.service.IProviderChangeListener; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles; +import org.eclipse.gmf.runtime.diagram.ui.services.editpolicy.CreateEditPoliciesOperation; +import org.eclipse.gmf.runtime.diagram.ui.services.editpolicy.IEditPolicyProvider; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.ActivityContentCompartmentCreationEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.InterruptibleActivityRegionContentCompartmentCreationEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.ActivityGroupEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.ActivityNodeEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.GroupNotifyingInCreationEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityActivityContentCompartmentEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityDiagramEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionActivityPartitionContentCompartmentEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLVisualIDRegistry; +import org.eclipse.uml2.uml.ActivityGroup; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Provider for all edit policies related to the group framework + */ +public class GroupEditPolicyProvider implements IEditPolicyProvider { + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.gmf.runtime.common.core.service.IProvider#addProviderChangeListener(org.eclipse.gmf.runtime.common.core.service.IProviderChangeListener + * ) + */ + @Override + public void addProviderChangeListener(IProviderChangeListener listener) { + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.common.core.service.IProvider#removeProviderChangeListener(org.eclipse.gmf.runtime.common.core.service. + * IProviderChangeListener) + */ + @Override + public void removeProviderChangeListener(IProviderChangeListener listener) { + } + + /** + * + * {@inheritDoc} + */ + @Override + public void createEditPolicies(EditPart editPart) { + /* + * Installation of notiying edit polocy + */ + if (editPart instanceof ActivityEditPart) { + editPart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY, new ActivityGroupEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY))); + } + if (editPart instanceof IGraphicalEditPart && editPart.getParent() instanceof IGraphicalEditPart) { + IGraphicalEditPart graphEditpart = (IGraphicalEditPart) editPart; + // is top edit part of the element + IGraphicalEditPart parentEditPart = (IGraphicalEditPart) editPart.getParent(); + EObject resolveSemanticElement = graphEditpart.resolveSemanticElement(); + if (resolveSemanticElement != null && !resolveSemanticElement.equals(parentEditPart.resolveSemanticElement())) { + if (resolveSemanticElement instanceof ActivityNode) { + graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY, new ActivityNodeEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY_NODE))); + } + if (resolveSemanticElement instanceof ActivityGroup) { + graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY, new ActivityGroupEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(resolveSemanticElement.eClass()))); + } + /* + * Installation of policy to handle graphicac + */ + switch (UMLVisualIDRegistry.getVisualID(graphEditpart.getNotationView())) { + case ActivityPartitionActivityPartitionContentCompartmentEditPart.VISUAL_ID: + graphEditpart.installEditPolicy(EditPolicyRoles.CREATION_ROLE, + new ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY_PARTITION))); + graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY, + new GroupNotifyingInCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(resolveSemanticElement.eClass()))); + break; + case InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart.VISUAL_ID: + graphEditpart.installEditPolicy(EditPolicyRoles.CREATION_ROLE, + new InterruptibleActivityRegionContentCompartmentCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.INTERRUPTIBLE_ACTIVITY_REGION))); + graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY, + new GroupNotifyingInCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(resolveSemanticElement.eClass()))); + break; + case ActivityActivityContentCompartmentEditPart.VISUAL_ID: + graphEditpart.installEditPolicy(EditPolicyRoles.CREATION_ROLE, new ActivityContentCompartmentCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY))); + graphEditpart.installEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY, + new GroupNotifyingInCreationEditPolicy(ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(resolveSemanticElement.eClass()))); + break; + default: + break; + } + } + + } + } + + /** + * + * {@inheritDoc} + */ + @Override + public boolean provides(IOperation operation) { + CreateEditPoliciesOperation epOperation = (CreateEditPoliciesOperation) operation; + if (!(epOperation.getEditPart() instanceof GraphicalEditPart)) { + return false; + } + GraphicalEditPart gep = (GraphicalEditPart) epOperation.getEditPart(); + String diagramType = gep.getNotationView().getDiagram().getType(); + if (ActivityDiagramEditPart.MODEL_ID.equals(diagramType)) { + return true; + } + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/GroupRequestAdvisor.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/GroupRequestAdvisor.java index 91bbd30b6a9..9c4825926a5 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/GroupRequestAdvisor.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/GroupRequestAdvisor.java @@ -1,1055 +1,1055 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import javax.naming.InitialContext;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-import org.eclipse.emf.workspace.WorkspaceEditingDomainFactory;
-import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
-import org.eclipse.gef.EditPolicy;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.RequestConstants;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gef.requests.GroupRequest;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.commands.SetBoundsCommand;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest;
-import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
-import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
-import org.eclipse.gmf.runtime.emf.type.core.commands.MoveElementsCommand;
-import org.eclipse.gmf.runtime.emf.type.core.requests.MoveRequest;
-import org.eclipse.gmf.runtime.notation.Diagram;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.infra.core.log.LogHelper;
-import org.eclipse.papyrus.infra.emf.gmf.command.GMFtoEMFCommandWrapper;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.ICompositeCreator;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.INotification;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.NotificationRunnable;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.Type;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.IContext;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.GroupNotifyingOnMoveEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.AncestorFilter;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.DescendantsFilter;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.DescendantsFilterIGroupNotifier;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.SameContainerFilter;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.IGroupRequest;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.SetDeferredRequest;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ui.IntegrateViewToConfigureComposite;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.DebugUtils;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils;
-import org.eclipse.papyrus.uml.diagram.activity.commands.DeferredSetValueCommand;
-import org.eclipse.papyrus.uml.diagram.activity.commands.RunNotificationCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.part.ActivityGroup.IGroupCompartmentEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.common.commands.RemoveValueCommand;
-import org.eclipse.papyrus.uml.diagram.common.commands.RemoveValueRequest;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.uml2.uml.ActivityGroup;
-import org.eclipse.uml2.uml.Element;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Sets;
-
-public class GroupRequestAdvisor implements IGroupRequestAdvisor {
-
- /**
- * Exception message
- */
- private static final String UNABLE_TO_GET_THE_INTIAL_TARGET_REQUEST_BOUNDS = "Unable to get the intial target request bounds";////$NON-NLS-1$
-
- /**
- * Debug message
- */
- private static final String CHILDREN_REFERENCES_ARE = " ---- Children references are : ---- ";
-
- /**
- * Debug message
- */
- private static final String ALL_PARENT_REFERENCES_ARE = " ---- All parent references are : ---- ";
-
- /**
- * Runnable to run command to change parent of selected element
- *
- * @author arthur daussy
- *
- */
- private final class ChangeGraphicalParentRunnable implements NotificationRunnable {
-
- /**
- * New graphical host
- */
- private final IGraphicalEditPart host;
-
- /**
- * Initial request
- */
- private final IGroupRequest request;
-
- /**
- * List of all modified view
- * Used to compute list of modfied files
- */
- private List<View> viewTomodify;
-
- /**
- * Constructor
- *
- * @param host
- * New graphical host
- * @param request
- * Initial request
- */
- private ChangeGraphicalParentRunnable(IGraphicalEditPart host, IGroupRequest request) {
- this.host = host;
- this.request = request;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.ui.toolbox.notification.NotificationRunnable#run(org.eclipse.papyrus.ui.toolbox.notification.builders.IContext)
- */
- @Override
- public void run(IContext context) {
- IntegrateViewToConfigureComposite composite = (IntegrateViewToConfigureComposite) context.get(IContext.COMPOSITE_CREATED);
- final INotification notif = (INotification) context.get(IContext.NOTIFICATION_OBJECT);
- CompositeTransactionalCommand ccMovingElement = new CompositeTransactionalCommand(request.getHostRequest().getEditingDomain(), "Move graphical elements into a new host");////$NON-NLS-1$
- /*
- * Use to calculate impacted file
- */
- viewTomodify = Lists.newArrayList();
- IGraphicalEditPart hostEditPart = request.getHostRequest();
- viewTomodify.add(host.getNotationView());
- for (IGroupNotifier notifier : composite.getSelectedNotifier()) {
- IGraphicalEditPart notifierEditPart = notifier.getHostEditPart();
- IGraphicalEditPart hostCompartmentEditPart = request.getNodeDescpitor().getCompartmentPartFromView(hostEditPart);
- /*
- * debugging label
- */
- if (DebugUtils.isDebugging()) {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("Move ");
- stringBuilder.append(Utils.getCorrectLabel(notifierEditPart));
- stringBuilder.append(" to ");
- stringBuilder.append(Utils.getCorrectLabel(hostEditPart));
- DebugUtils.getLog().info(stringBuilder.toString());
- }
- if (notifierEditPart != null) {
- EObject semanticElementToDrop = notifierEditPart.resolveSemanticElement();
- if (semanticElementToDrop != null && hostCompartmentEditPart != null) {
- /*
- * Request to change graphical parent
- */
- ChangeBoundsRequest chdBoundsRequest = new ChangeBoundsRequest(RequestConstants.REQ_ADD);
- chdBoundsRequest.setEditParts(notifierEditPart);
- viewTomodify.add(notifierEditPart.getNotationView());
- Command dropcommand = hostCompartmentEditPart.getCommand(chdBoundsRequest);
- if (dropcommand != null) {
- ccMovingElement.compose(new CommandProxy(dropcommand));
- }
- } else {
- // log error
- }
- } else {
- // log error
- }
- }
- /*
- * Execute resulting command
- */
- if (ccMovingElement != null && !ccMovingElement.isEmpty()) {
- host.getEditingDomain().getCommandStack().execute(new GMFtoEMFCommandWrapper(ccMovingElement));
- }
- notif.delete();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.ui.toolbox.notification.NotificationRunnable#getLabel()
- */
- @Override
- public String getLabel() {
- return "OK";
- }
-
- /**
- * @return the list of all EObject modifed
- */
- public List getModifiedObject() {
- return viewTomodify == null ? Collections.emptyList() : viewTomodify;
- }
- }
-
- /**
- * SingletonHolder is loaded on the first execution of Singleton.getInstance()
- * or the first access to SingletonHolder.INSTANCE, not before.
- */
- private static class SingletonHolder {
-
- public static final GroupRequestAdvisor instance = new GroupRequestAdvisor();
- }
-
- /**
- * Get the instance of {@link GroupRequestAdvisor}
- *
- * @return
- */
- public static GroupRequestAdvisor getInstance() {
- return SingletonHolder.instance;
- }
-
- /**
- * Store all the listener
- */
- private Multimap<EObject, IGroupNotifier> listenners;
-
- /**
- * Logger
- */
- private static LogHelper log = new LogHelper(UMLDiagramEditorPlugin.getInstance());
-
- /***
- * Private constructor
- */
- private GroupRequestAdvisor() {
- listenners = ArrayListMultimap.create();
- }
-
- /**
- * Add a {@link IGroupNotifier}
- *
- * @param editpolicy
- */
- @Override
- public void addListenner(EObject eObject, IGroupNotifier editpolicy) {
- getListenerRegistry().put(eObject, editpolicy);
- }
-
- /**
- * Remove a {@link IGroupNotifier}
- *
- * @param editpolicy
- */
- @Override
- public void removeListenner(IGroupNotifier editpolicy) {
- if (editpolicy == null) {
- return;
- }
- Iterator<Entry<EObject, IGroupNotifier>> iterator = getListenerRegistry().entries().iterator();
- while (iterator.hasNext()) {
- Entry<EObject, IGroupNotifier> entry = iterator.next();
- if (editpolicy.equals(entry.getValue())) {
- iterator.remove();
- }
- }
- }
-
- @Override
- public ICommand notifyGroupFramework(IGroupRequest request) {
- if (DebugUtils.isDebugging()) {
- log.debug("***********************BEGIN : Group Request Advisor***********************************");
- }
- /******************
- * Handling parent
- ******************/
- CompositeCommand cc = new CompositeCommand("Global command from GroupRequestAdvisor");
- Request initialRequest = request.getInitialRequest();
- if (initialRequest instanceof ChangeBoundsRequest) {
- handleMove(request, cc);
- } else if (initialRequest instanceof GroupRequest && RequestConstants.REQ_DELETE.equals(initialRequest.getType())) {
- handleDelete(request, cc);
- }
- if (cc != null && !cc.isEmpty()) {
- return cc;
- }
- return null;
- }
-
- protected void handleDelete(IGroupRequest request, CompositeCommand cc) {
- // request.getNodeDescpitor().getChildrenReferences()
- }
-
- /**
- * Handle move
- *
- * @param request
- * @param cc
- */
- protected void handleMove(IGroupRequest request, CompositeCommand cc) {
- /*
- * All parent
- */
- fillRequestWithAllPossibleParent(request);
- fillRequestWithAllPossibleChildren(request);
- Object elementAdapter = request.getTargetElement().getAdapter(EObject.class);
- if (elementAdapter instanceof EObject) {
- /*
- * Handle children
- */
- handleSemanticChildren(request, cc, (EObject) elementAdapter);
- /*
- * Semantic of all the parent
- */
- handleSemanticParents(request, cc, elementAdapter);
- }
- if (DebugUtils.isDebugging()) {
- log.debug("***********************END : Group Request Advisor***********************************");
- }
- // /*
- // * For all new child send request
- // * For all GrChild create new request from old one and use dispatcher
- // */
- // if(cc != null && !cc.isEmpty()) {
- // return cc;
- // }
- // return null;
- }
-
- /**
- * Handle all the children of the group (graphical and non graphical children)
- *
- * @param request
- * @param cc
- * @param targetElement
- */
- protected void handleSemanticChildren(final IGroupRequest request, CompositeCommand cc, EObject targetElement) {
- List<EObject> graphicalChildren = Lists.newArrayList();
- /*
- * There is graphical childrne only when the node is moving
- */
- if (request.getInitialRequest() instanceof ChangeBoundsRequest) {
- graphicalChildren = handleGraphicalChildren(request, cc);
- }
- /*
- * Unset
- */
- for (Entry<EReference, EObject> oldChildrenEntry : Utils.getOldChildren(request).entries()) {
- Multimap<EReference, EObject> allActualChildren = request.getChildrenEReferenceMap();
- EReference ref = oldChildrenEntry.getKey();
- if (ref != null) {
- if (!allActualChildren.containsEntry(oldChildrenEntry.getValue(), ref)) {
- EReference eOpposite = ref.getEOpposite();
- if (!graphicalChildren.contains(oldChildrenEntry.getValue())) {
- if (eOpposite != null && !eOpposite.isContainment() && !ref.isContainment()) {
- RemoveValueRequest rmVa = new RemoveValueRequest(targetElement, ref, Collections.singletonList(oldChildrenEntry.getValue()));
- RemoveValueCommand rmCmd = new RemoveValueCommand(rmVa);
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("From handling parent : Remove ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(ref));
- stringBuilder.append(" from ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(targetElement));
- stringBuilder.append(" value ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(oldChildrenEntry.getValue()));//
- rmCmd.setLabel(stringBuilder.toString());
- if (rmCmd != null) {
- cc.compose(rmCmd);
- }
- }
- }
- }
- }
- }
- /*
- * Set semantic
- */
- Set<EObject> newChildren = Sets.newHashSet();
- for (Entry<EReference, EObject> entry : request.getChildrenEReferenceMap().entries()) {
- EReference ref = entry.getKey();
- if (ref != null) {
- EReference eOpposite = ref.getEOpposite();
- if (!graphicalChildren.contains(entry.getValue())) {
- newChildren.add(entry.getValue());
- if (eOpposite != null && !eOpposite.isContainment()) {
- SetDeferredRequest setRq = new SetDeferredRequest(request.getHostRequest().getEditingDomain(), request.getTargetElement(), ref, entry.getValue());
- DeferredSetValueCommand setCmd = new DeferredSetValueCommand(setRq);
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("From handling parent : Set deferred");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(entry.getValue()));
- stringBuilder.append(" from ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(ref));
- stringBuilder.append(" value ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(entry.getValue()));//
- setCmd.setLabel(stringBuilder.toString());
- if (setCmd != null) {
- cc.compose(setCmd);
- }
- }
- }
- }
- if (!newChildren.isEmpty()) {
- handleChangeParentNotificationCommand(request, cc, newChildren);
- }
- }
- }
-
- /**
- * Create a notification to user to ask him is he want to add its new children as graphical child of its parent group
- *
- * @param request
- * {@link InitialContext} {@link IGroupRequest}
- * @param cc
- * {@link CompositeCommand} to compose new commands
- * @param newChildren
- * List of all new children
- */
- protected void handleChangeParentNotificationCommand(final IGroupRequest request, CompositeCommand cc, Set<EObject> newChildren) {
- /*
- * Create dialog to suggest user to move views
- */
- final IGraphicalEditPart host = request.getHostRequest();
- /*
- * Get editpart of all children
- */
- Iterable<IGroupNotifier> listOfChidren = Iterables.transform(newChildren, new Function<EObject, IGroupNotifier>() {
-
- @Override
- public IGroupNotifier apply(EObject arg0) {
- Collection<IGroupNotifier> notifiers = getListenerRegistry().get(arg0);
- for (IGroupNotifier notifier : notifiers) {
- IGraphicalEditPart notifierEditPart = notifier.getHostEditPart();
- if (notifierEditPart != null) {
- if (EcoreUtil.isAncestor(host.getNotationView().getDiagram(), notifierEditPart.getNotationView())) {
- return notifier;
- }
- }
- }
- return null;
- }
- });
- final Iterable<IGroupNotifier> listOfFilteredChidren = Iterables.filter(listOfChidren, Predicates.notNull());
- List<IGroupNotifier> automaticChildren = Lists.newArrayList();
- List<IGroupNotifier> nonAutomaticChildren = Lists.newArrayList();
- /*
- * Dispatch children
- */
- dispatchChildren(request, host, listOfFilteredChidren, automaticChildren, nonAutomaticChildren);
- IGraphicalEditPart hostEditPart = request.getHostRequest();
- /*
- * Command to change graphical parent for element when we can guess graphical parent
- */
- for (IGroupNotifier notifier : automaticChildren) {
- IGraphicalEditPart notifierEditPart = notifier.getHostEditPart();
- IGraphicalEditPart hostCompartmentEditPart = request.getNodeDescpitor().getCompartmentPartFromView(hostEditPart);
- Request initialRequest = request.getInitialRequest();
- Rectangle hostBounds = null;
- if (initialRequest instanceof ChangeBoundsRequest) {
- hostBounds = Utils.getAbslotueRequestBounds((ChangeBoundsRequest) initialRequest, hostCompartmentEditPart);
- } else {
- hostBounds = Utils.getAbsoluteBounds(hostCompartmentEditPart);
- }
- Rectangle childBounds = Utils.getAbsoluteBounds(notifierEditPart);
- MoveElementsCommand mvCmd = new MoveElementsCommand(new MoveRequest(hostCompartmentEditPart.getNotationView(), notifierEditPart.getNotationView()));
- /*
- * Integrate view into new compartment
- */
- if (mvCmd != null && mvCmd.canExecute()) {
- cc.compose(mvCmd);
- }
- /*
- * Set view to the new location
- */
- SetBoundsCommand setBoundCommand = new SetBoundsCommand(WorkspaceEditingDomainFactory.INSTANCE.getEditingDomain(host.getNotationView().eResource().getResourceSet()), "test", new EObjectAdapter(notifierEditPart.getNotationView()),
- childBounds.translate(hostBounds.getLocation().negate()));
- if (setBoundCommand != null && setBoundCommand.canExecute()) {
- cc.compose(setBoundCommand);
- }
- }
- /*
- * Create notification for element where we can NOT guess the graphical parent
- */
- if (!nonAutomaticChildren.isEmpty()) {
- /*
- * create runnable to run the command
- */
- ChangeGraphicalParentRunnable changeGraphicalParentRunnable = new ChangeGraphicalParentRunnable(host, request);
- final NotificationBuilder notification = createChangeGraphicalParentNotification(nonAutomaticChildren, changeGraphicalParentRunnable, hostEditPart);
- RunNotificationCommand runNotifCmd = new RunNotificationCommand(request.getHostRequest().getEditingDomain(), "Notification command", getWorkspaceFiles(changeGraphicalParentRunnable.getModifiedObject()), notification);////$NON-NLS-1$
- cc.compose(runNotifCmd);
- }
- }
-
- /**
- * Dispatch all children in two category.
- * listOfFilteredChidren will contained all element to automatically add as graphical children
- * nonAutomaticChildren will contained all element to ask the user what to do with
- *
- * @param request
- * @param host
- * @param listOfFilteredChidren
- * @param automaticChildren
- * @param nonAutomaticChildren
- */
- private void dispatchChildren(final IGroupRequest request, final IGraphicalEditPart host, final Iterable<IGroupNotifier> listOfFilteredChidren, List<IGroupNotifier> automaticChildren, List<IGroupNotifier> nonAutomaticChildren) {
- for (IGroupNotifier notifier : listOfFilteredChidren) {
- IGraphicalEditPart parentEditPart = getGraphicalParent(notifier.getHostEditPart());
- if (parentEditPart != null) {
- EObject eObject = parentEditPart.resolveSemanticElement();
- if (eObject instanceof ActivityGroup) {
- ActivityGroup group = (ActivityGroup) eObject;
- Collection<IGroupNotifier> groupNotifiers = listenners.get(group);
- if (!groupNotifiers.isEmpty()) {
- IGroupNotifier myGroupNotifier = groupNotifiers.iterator().next();
- /*
- * Is the old container (an activity group) continaing the current moving element
- */
- boolean isNewContainerVisuallyIncludeInOldContainer = myGroupNotifier.includes(Utils.getAbslotueRequestBounds((ChangeBoundsRequest) request.getInitialRequest(), host));
- /*
- * Can the old container (an activity group) be a model a the current moving element
- */
- boolean canTheOldContainerBeAModelParentOfTheNewContainer = myGroupNotifier.getHostGroupDescriptor().canIBeModelParentOf(host.resolveSemanticElement().eClass());
- /*
- *
- */
- boolean canTheNewContainerBeModelParentOfTheOldContianer = request.getNodeDescpitor().canIBeModelParentOf(host.resolveSemanticElement().eClass());
- /*
- * Is the current moving element containing the old container
- */
- IGroupNotifier currentElementNotifier = getIGroupNotifier(host);
- boolean isOldContainerVisuallyIncludeInNewContainer = currentElementNotifier.includes(Utils.getAbsoluteBounds(myGroupNotifier.getHostEditPart()));
- if (canTheOldContainerBeAModelParentOfTheNewContainer && isNewContainerVisuallyIncludeInOldContainer) {
- /*
- * Is going to be a new child of the old container
- */
- automaticChildren.add(notifier);
- } else if (canTheNewContainerBeModelParentOfTheOldContianer && isOldContainerVisuallyIncludeInNewContainer) {
- /*
- * Is going to be a new container for the old container
- */
- } else {
- /*
- * There is no containing relation between the groups
- */
- if (currentElementNotifier.getHostGroupDescriptor().getContainmentReferenceFor(notifier.getHostEditPart().resolveSemanticElement().eClass()) == null) {
- nonAutomaticChildren.add(notifier);
- } else {
- // If containment link automatically add it to new group
- automaticChildren.add(notifier);
- }
- }
- } else {
- /*
- * No notifier where found
- */
- nonAutomaticChildren.add(notifier);
- }
- } else {
- /*
- * If there is no container (which is group)
- */
- if (!parentEditPart.equals(host)) {
- automaticChildren.add(notifier);
- }
- }
- } else {
- DebugUtils.getLog().error("Unable to retreive graphical parent of " + Utils.getCorrectLabel(notifier), null);
- }
- }
- }
-
- /**
- * Get the IGroupNotifier of the {@link IGraphicalEditPart} passed in argument
- *
- * @param host
- * @return
- */
- private IGroupNotifier getIGroupNotifier(final IGraphicalEditPart host) {
- EditPolicy editPolicy = host.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY);
- if (editPolicy instanceof IGroupNotifier) {
- return (IGroupNotifier) editPolicy;
- } else {
- editPolicy = host.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY);
- if (editPolicy instanceof IGroupNotifier) {
- return (IGroupNotifier) editPolicy;
- }
- }
- throw new RuntimeException("Unable to retreive the IGroupNofier of the current group");////$NON-NLS-1$
- }
-
- /**
- * Get the edit which represent the parent (semantically) of the edit part child passed in argument
- *
- * @param child
- * @return
- */
- private IGraphicalEditPart getGraphicalParent(IGraphicalEditPart child) {
- IGraphicalEditPart result = child;
- EObject childElement = child.resolveSemanticElement();
- if (child != null) {
- while (childElement == result.resolveSemanticElement()) {
- try {
- result = (IGraphicalEditPart) result.getParent();
- } catch (ClassCastException e) {
- return result;
- }
- }
- }
- return result;
- }
-
- /**
- * Create a notification to ask user if he want to change the graphical parent of some elements
- *
- * @param listOfFilteredChidren
- * @param changeGraphicalParentRunnable
- * @return
- */
- private NotificationBuilder createChangeGraphicalParentNotification(final Iterable<IGroupNotifier> listOfFilteredChidren, ChangeGraphicalParentRunnable changeGraphicalParentRunnable, final IGraphicalEditPart host) {
- return new NotificationBuilder().setType(Type.INFO).setAsynchronous(true).setTemporary(true).setDelay(3000).setTitle("Papyrus graphical modification").setComposite(new ICompositeCreator() {
-
- @Override
- public Composite createComposite(Composite parent, FormToolkit toolkit) {
- return new IntegrateViewToConfigureComposite(parent, SWT.NONE, Lists.newArrayList(Lists.newArrayList(listOfFilteredChidren)), "New elements are visually contained in the current group (" + Utils.getCorrectLabel(host)
- + ").\n Please select the elements you want to integrate into this group figure.");
- }
- }).addAction(changeGraphicalParentRunnable);
- }
-
- /**
- * Handle graphical children
- *
- * @param request
- * {@link IGroupRequest}
- * @param cc
- * {@link CompositeCommand} to compose new commands
- * @return The list of all graphical children already handled
- */
- protected List<EObject> handleGraphicalChildren(IGroupRequest request, CompositeCommand cc) {
- /*
- * List of all the graphical children
- */
- List<EObject> graphicalChildren = new ArrayList<EObject>();
- /*
- * Handle graphical children
- */
- // Get graphical children
- Object targetEditPart = request.getTargetElement().getAdapter(IGraphicalEditPart.class);
- IGraphicalEditPart compartementEditPart = null;
- if (targetEditPart instanceof IGroupCompartmentEditPart) {
- compartementEditPart = ((IGraphicalEditPart) targetEditPart);
- } else if (targetEditPart instanceof IGraphicalEditPart) {
- IContainerNodeDescriptor nodeDescpitor = request.getNodeDescpitor();
- if (nodeDescpitor != null) {
- compartementEditPart = nodeDescpitor.getCompartmentPartFromView((IGraphicalEditPart) targetEditPart);
- }
- }
- if (compartementEditPart != null) {
- /*
- * Transform an IGraphicalEditPart to the related GroupNotifyingEditPolicy
- */
- @SuppressWarnings("unchecked")
- Iterable<GroupNotifyingOnMoveEditPolicy> policies = Iterables.transform(compartementEditPart.getChildren(), new Function<IGraphicalEditPart, GroupNotifyingOnMoveEditPolicy>() {
-
- @Override
- public GroupNotifyingOnMoveEditPolicy apply(IGraphicalEditPart from) {
- EditPolicy editPolicy = from.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY);
- if (editPolicy instanceof GroupNotifyingOnMoveEditPolicy) {
- return (GroupNotifyingOnMoveEditPolicy) editPolicy;
- }
- return null;
- }
- });
- for (final GroupNotifyingOnMoveEditPolicy p : policies) {
- if (p != null) {
- if (DebugUtils.isDebugging()) {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("+++ Work for child ");
- stringBuilder.append(Utils.getCorrectLabel(p.getEObject()));
- stringBuilder.append(" +++");
- DebugUtils.getLog().debug(stringBuilder.toString());
- }
- Request initialRequest = request.getInitialRequest();
- Request auxChReq = null;
- if (initialRequest instanceof ChangeBoundsRequest) {
- auxChReq = Utils.getChangeBoundsRequestCopy((ChangeBoundsRequest) initialRequest, p.getHostEditPart());
- } else {
- auxChReq = initialRequest;
- }
- /*
- * Save graphical parent
- */
- // auxChReq.getExtendedData().put(GROUP_FRAMEWORK_GRAPHICAL_PARENT, compartementEditPart.resolveSemanticElement());
- graphicalChildren.add(p.getEObject());
- Command childCommand = p.getCommand(auxChReq);
- if (childCommand != null && childCommand.canExecute()) {
- cc.compose(new CommandProxy(childCommand));
- }
- }
- }
- }
- return graphicalChildren;
- }
-
- /**
- * Set and Unset semantic relation with parents
- *
- * @param request
- * {@link IGroupRequest}
- * @param cc
- * {@link CompositeCommand} to compose command
- * @param elementAdapter
- */
- protected void handleSemanticParents(IGroupRequest request, CompositeCommand cc, Object elementAdapter) {
- EObject targetElement = (EObject) elementAdapter;
- Multimap<EReference, EObject> allActualParent = request.getParentEReferenceMap();
- for (Entry<EReference, EObject> entry : Utils.getOldParents(request).entries()) {
- EReference ref = entry.getKey();
- if (ref != null) {
- if (!allActualParent.containsEntry(ref, entry.getValue())) {
- EReference eOpposite = ref.getEOpposite();
- if (eOpposite != null && !eOpposite.isContainment() && !eOpposite.isDerived()) {
- RemoveValueRequest rmVa = new RemoveValueRequest(targetElement, ref, Collections.singletonList(entry.getValue()));
- RemoveValueCommand rmCmd = new RemoveValueCommand(rmVa);
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("From handling parent : Remove ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(entry.getValue()));
- stringBuilder.append(" from ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(targetElement));
- stringBuilder.append(" value ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(entry.getValue()));//
- rmCmd.setLabel(stringBuilder.toString());
- if (rmCmd != null) {
- cc.compose(rmCmd);
- }
- }
- // }
- }
- }
- }
- /*
- * Set semantic
- * If the EObject has not been already handle as graphical children
- */
- for (Entry<EReference, EObject> entry : request.getParentEReferenceMap().entries()) {
- EReference ref = entry.getKey();
- if (ref != null) {
- EReference eOpposite = ref.getEOpposite();
- if (eOpposite != null && !eOpposite.isContainment() && !ref.isContainment()) {
- SetDeferredRequest setRq = new SetDeferredRequest(request.getHostRequest().getEditingDomain(), request.getTargetElement(), ref, entry.getValue());
- DeferredSetValueCommand setCmd = new DeferredSetValueCommand(setRq);
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("From handling parent : Set deferred ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(ref));
- stringBuilder.append(" from ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(request.getTargetElement()));
- stringBuilder.append(" value ");////$NON-NLS-1$
- stringBuilder.append(Utils.getCorrectLabel(entry.getValue()));//
- setCmd.setLabel(stringBuilder.toString());
- if (setCmd != null) {
- cc.compose(setCmd);
- }
- }
- }
- }
- }
-
- /**
- * Return a list of all IGroupRequestListenner which can be children of the target of the request
- *
- * @param request
- * @return
- */
- protected Multimap<EReference, IGroupNotifier> fillRequestWithAllPossibleChildren(IGroupRequest request) {
- final Multimap<EReference, IGroupNotifier> result = fillReqestWithReferendedElement(request, false, false);
- /**
- * TODO filter graphical parent which currently moving
- * I1 in ActPart1
- * ActPart1 move into ActPart2
- * I1 should only reference ActPart1
- */
- /*
- * Debug
- */
- DebugUtils.displayMultipmapDebug(CHILDREN_REFERENCES_ARE, request.getChildrenEReferenceMap());
- return result;
- }
-
- public EObject getPossibleModelParent(IGroupRequest request) {
- Multimap<EReference, IGroupNotifier> parentsMap = fillReqestWithReferendedElement(request, true, true);
- List<IGroupNotifier> parents = Lists.newArrayList(parentsMap.values());
- Collections.sort(parents);
- if (!parents.isEmpty()) {
- return parents.get(0).getEObject();
- }
- return request.getHostRequest().resolveSemanticElement();
- }
-
- /**
- * Return only current displayed listener
- *
- * @author adaussy
- *
- */
- private static class ActiveListener implements Predicate<IGroupNotifier> {
-
- private Diagram currentDiagramDisplayed;
-
- public ActiveListener(Diagram currentDiagramDisplayed) {
- super();
- this.currentDiagramDisplayed = currentDiagramDisplayed;
- Assert.isNotNull(currentDiagramDisplayed);
- }
-
- @Override
- public boolean apply(IGroupNotifier input) {
- IGraphicalEditPart host = input.getHostEditPart();
- if (host != null) {
- View primaryView = host.getPrimaryView();
- if (primaryView != null) {
- return currentDiagramDisplayed.equals(primaryView.getDiagram());
- }
- }
- return false;
- }
- }
-
- /**
- * Get all the element in references which are included or include (depending of the parameter include)
- *
- * @param request
- * {@link IGroupRequest}
- * @param newBounds
- * New bounds of the elements
- * @param references
- * All references to take into account
- * @param eReferenceMapToFillInRequest
- * Map in the request to fill
- * @param result
- * {@link Map} which link a {@link EReference} to a {@link IGroupNotifier}
- * @param containementOnly
- * true if we are looking for containing references only
- */
- protected void getReferenceElements(IGroupRequest request, final Rectangle newBounds, final List<EReference> references, Multimap<EReference, Element> eReferenceMapToFillInRequest, Multimap<EReference, IGroupNotifier> result, boolean include,
- boolean containementOnly, Map<EStructuralFeature, EStructuralFeature> parentOpositeFeature) {
- Iterable<IGroupNotifier> activeListeners = Iterables.filter(getListenerRegistry().values(), new ActiveListener(getCurrentlyDisplayedDiagram(request)));
- for (IGroupNotifier input : activeListeners) {
- EObject inputEObject = input.getEObject();
- if (inputEObject == null || !(inputEObject instanceof Element)) {
- continue;
- }
- Object adapter = request.getTargetElement().getAdapter(EObject.class);
- // EObject targetElement = null;
- // if(adapter instanceof EObject) {
- // targetElement = (EObject)adapter;
- // }
- if (inputEObject.equals(adapter)) {
- continue;
- }
- EReference refenceFounded = null;
- for (EReference ref : references) {
- EClass refType = ref.getEReferenceType();
- EClass eoBjectType = inputEObject.eClass();
- if (refType.isSuperTypeOf(eoBjectType)) {
- refenceFounded = ref;
- break;
- }
- }
- if (refenceFounded != null) {
- if ((include && input.includes(newBounds)) || (!include && input.isIncludedIn(newBounds))) {
- if (containementOnly && parentOpositeFeature.get(refenceFounded) instanceof EReference && !((EReference) parentOpositeFeature.get(refenceFounded)).isContainment()) {
- continue;
- }
- eReferenceMapToFillInRequest.put(refenceFounded, (Element) inputEObject);
- result.put(refenceFounded, input);
- }
- }
- }
- }
-
- /**
- * Return the currently displayed diagram
- *
- * @param request
- * @return
- */
- protected Diagram getCurrentlyDisplayedDiagram(IGroupRequest request) {
- IGraphicalEditPart graph = request.getHostRequest();
- if (graph != null) {
- Object m = graph.getModel();
- if (m instanceof View) {
- View v = (View) m;
- return v.getDiagram();
- }
- }
- throw new RuntimeException("Unable to get the current diagram displayed");////$NON-NLS-1$
- }
-
- /**
- * Return the list of all {@link IGroupNotifier} which can be parent of the target of the request
- *
- * @param request
- * @return
- */
- protected Multimap<EReference, IGroupNotifier> fillRequestWithAllPossibleParent(IGroupRequest request) {
- final Multimap<EReference, IGroupNotifier> result = fillReqestWithReferendedElement(request, true, false);
- /*
- * Debug
- */
- DebugUtils.displayMultipmapDebug(ALL_PARENT_REFERENCES_ARE, request.getParentEReferenceMap());
- return result;
- }
-
- protected Multimap<EReference, IGroupNotifier> fillReqestWithReferendedElement(IGroupRequest request, boolean lookingForParent, boolean onlyContainment) {
- final Rectangle newBounds = getInitalTargetRequestNewBounds(request);
- final Multimap<EReference, IGroupNotifier> result = ArrayListMultimap.create();
- if (request.getNodeDescpitor() == null) {
- return result;
- }
- List<EReference> references = null;
- if (lookingForParent) {
- references = request.getNodeDescpitor().getParentReferences();
- } else {
- references = request.getNodeDescpitor().getChildrenReferences();
- }
- final Multimap<EReference, IGroupNotifier> auxResult = ArrayListMultimap.create();
- final Multimap<EReference, Element> eReferenceLookedForMap = ArrayListMultimap.create();
- getReferenceElements(request, newBounds, references, eReferenceLookedForMap, auxResult, lookingForParent, onlyContainment, lookingForParent ? request.getNodeDescpitor().getParentEOppositeReferences() : null);
- /*
- * Filter ancestors
- */
- for (EReference ref : eReferenceLookedForMap.keySet()) {
- /*
- * Filter descendant
- * Example :
- * 1 - ActPart1 include in Act1 then Act1 disappear
- * 2 - ActPart1 include in ActPart2 then ActPart1 disappear
- */
- Object adapter = request.getTargetElement().getAdapter(EObject.class);
- if (adapter instanceof Element) {
- Element element = (Element) adapter;
- Predicate<Element> composedPredicate = Predicates.and(new SameContainerFilter(element), lookingForParent ? new DescendantsFilter(eReferenceLookedForMap.values()) : new AncestorFilter(eReferenceLookedForMap.values()));
- Collection<Element> filteredCollection = Collections2.filter(eReferenceLookedForMap.get(ref), composedPredicate);
- if (lookingForParent) {
- request.getParentEReferenceMap().putAll(ref, filteredCollection);
- } else {
- request.getChildrenEReferenceMap().putAll(ref, filteredCollection);
- }
- }
- }
- for (EReference ref : auxResult.keySet()) {
- /*
- * Filter descendant
- * Example :
- * 1 - ActPart1 include in Act1 then Act1 disappear
- * 2 - ActPart1 include in ActPart2 then ActPart1 disappear
- */
- Iterable<IGroupNotifier> resultCollection = Iterables.filter(auxResult.get(ref), new DescendantsFilterIGroupNotifier(auxResult.values()));
- result.putAll(ref, resultCollection);
- }
- return result;
- }
-
- /**
- * Get the absolute bounds of the target of the request
- *
- * @param request
- * @return
- */
- public static Rectangle getInitalTargetRequestNewBounds(final IGroupRequest request) {
- Request initialRequest = request.getInitialRequest();
- if (initialRequest instanceof ChangeBoundsRequest) {
- return Utils.getAbslotueRequestBounds((ChangeBoundsRequest) initialRequest, request.getHostRequest());
- } else if (initialRequest instanceof CreateViewRequest) {
- return Utils.getAbslotueRequestBounds((CreateViewRequest) initialRequest);
- }
- throw new RuntimeException(UNABLE_TO_GET_THE_INTIAL_TARGET_REQUEST_BOUNDS);
- }
-
- /**
- * Convenience method to get a list of workspaces files associated with <code>eObject</code>.
- *
- * @param eObject
- * the model object, may be <code>null</code>
- * @return the list of {@link IFile}s
- */
- protected static List getWorkspaceFiles(EObject eObject) {
- List result = new ArrayList();
- if (eObject != null) {
- Resource resource = eObject.eResource();
- if (resource != null) {
- IFile file = WorkspaceSynchronizer.getFile(resource);
- if (file != null) {
- result.add(file);
- }
- }
- }
- return result;
- }
-
- /**
- * Convenience method to get a list of workspaces files associated with {@link EObject}s in <code>eObject</code>.
- *
- * @param eObjects
- * the list of model object
- * @return the list of {@link IFile}s
- */
- protected static List getWorkspaceFiles(List eObjects) {
- List result = new ArrayList();
- for (Iterator i = eObjects.iterator(); i.hasNext();) {
- Object next = i.next();
- if (next instanceof EObject) {
- Resource resource = ((EObject) next).eResource();
- if (resource != null) {
- IFile file = WorkspaceSynchronizer.getFile(resource);
- if (file != null) {
- result.add(file);
- }
- }
- }
- }
- return result;
- }
-
- /**
- * @return the listenners
- */
- @Override
- public Multimap<EObject, IGroupNotifier> getListenerRegistry() {
- return listenners;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import javax.naming.InitialContext; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.Assert; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.emf.workspace.WorkspaceEditingDomainFactory; +import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; +import org.eclipse.gef.EditPolicy; +import org.eclipse.gef.Request; +import org.eclipse.gef.RequestConstants; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gef.requests.GroupRequest; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.commands.SetBoundsCommand; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest; +import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand; +import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter; +import org.eclipse.gmf.runtime.emf.type.core.commands.MoveElementsCommand; +import org.eclipse.gmf.runtime.emf.type.core.requests.MoveRequest; +import org.eclipse.gmf.runtime.notation.Diagram; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.infra.core.log.LogHelper; +import org.eclipse.papyrus.infra.emf.gmf.command.GMFtoEMFCommandWrapper; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.ICompositeCreator; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.INotification; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.NotificationRunnable; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.Type; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.IContext; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.GroupNotifyingOnMoveEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.AncestorFilter; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.DescendantsFilter; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.DescendantsFilterIGroupNotifier; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.SameContainerFilter; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.IGroupRequest; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.SetDeferredRequest; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ui.IntegrateViewToConfigureComposite; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.DebugUtils; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils; +import org.eclipse.papyrus.uml.diagram.activity.commands.DeferredSetValueCommand; +import org.eclipse.papyrus.uml.diagram.activity.commands.RunNotificationCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.part.ActivityGroup.IGroupCompartmentEditPart; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.common.commands.RemoveValueCommand; +import org.eclipse.papyrus.uml.diagram.common.commands.RemoveValueRequest; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.uml2.uml.ActivityGroup; +import org.eclipse.uml2.uml.Element; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Collections2; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Multimap; +import com.google.common.collect.Sets; + +public class GroupRequestAdvisor implements IGroupRequestAdvisor { + + /** + * Exception message + */ + private static final String UNABLE_TO_GET_THE_INTIAL_TARGET_REQUEST_BOUNDS = "Unable to get the intial target request bounds";////$NON-NLS-1$ + + /** + * Debug message + */ + private static final String CHILDREN_REFERENCES_ARE = " ---- Children references are : ---- "; + + /** + * Debug message + */ + private static final String ALL_PARENT_REFERENCES_ARE = " ---- All parent references are : ---- "; + + /** + * Runnable to run command to change parent of selected element + * + * @author arthur daussy + * + */ + private final class ChangeGraphicalParentRunnable implements NotificationRunnable { + + /** + * New graphical host + */ + private final IGraphicalEditPart host; + + /** + * Initial request + */ + private final IGroupRequest request; + + /** + * List of all modified view + * Used to compute list of modfied files + */ + private List<View> viewTomodify; + + /** + * Constructor + * + * @param host + * New graphical host + * @param request + * Initial request + */ + private ChangeGraphicalParentRunnable(IGraphicalEditPart host, IGroupRequest request) { + this.host = host; + this.request = request; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.ui.toolbox.notification.NotificationRunnable#run(org.eclipse.papyrus.ui.toolbox.notification.builders.IContext) + */ + @Override + public void run(IContext context) { + IntegrateViewToConfigureComposite composite = (IntegrateViewToConfigureComposite) context.get(IContext.COMPOSITE_CREATED); + final INotification notif = (INotification) context.get(IContext.NOTIFICATION_OBJECT); + CompositeTransactionalCommand ccMovingElement = new CompositeTransactionalCommand(request.getHostRequest().getEditingDomain(), "Move graphical elements into a new host");////$NON-NLS-1$ + /* + * Use to calculate impacted file + */ + viewTomodify = Lists.newArrayList(); + IGraphicalEditPart hostEditPart = request.getHostRequest(); + viewTomodify.add(host.getNotationView()); + for (IGroupNotifier notifier : composite.getSelectedNotifier()) { + IGraphicalEditPart notifierEditPart = notifier.getHostEditPart(); + IGraphicalEditPart hostCompartmentEditPart = request.getNodeDescpitor().getCompartmentPartFromView(hostEditPart); + /* + * debugging label + */ + if (DebugUtils.isDebugging()) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("Move "); + stringBuilder.append(Utils.getCorrectLabel(notifierEditPart)); + stringBuilder.append(" to "); + stringBuilder.append(Utils.getCorrectLabel(hostEditPart)); + DebugUtils.getLog().info(stringBuilder.toString()); + } + if (notifierEditPart != null) { + EObject semanticElementToDrop = notifierEditPart.resolveSemanticElement(); + if (semanticElementToDrop != null && hostCompartmentEditPart != null) { + /* + * Request to change graphical parent + */ + ChangeBoundsRequest chdBoundsRequest = new ChangeBoundsRequest(RequestConstants.REQ_ADD); + chdBoundsRequest.setEditParts(notifierEditPart); + viewTomodify.add(notifierEditPart.getNotationView()); + Command dropcommand = hostCompartmentEditPart.getCommand(chdBoundsRequest); + if (dropcommand != null) { + ccMovingElement.compose(new CommandProxy(dropcommand)); + } + } else { + // log error + } + } else { + // log error + } + } + /* + * Execute resulting command + */ + if (ccMovingElement != null && !ccMovingElement.isEmpty()) { + host.getEditingDomain().getCommandStack().execute(new GMFtoEMFCommandWrapper(ccMovingElement)); + } + notif.delete(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.ui.toolbox.notification.NotificationRunnable#getLabel() + */ + @Override + public String getLabel() { + return "OK"; + } + + /** + * @return the list of all EObject modifed + */ + public List getModifiedObject() { + return viewTomodify == null ? Collections.emptyList() : viewTomodify; + } + } + + /** + * SingletonHolder is loaded on the first execution of Singleton.getInstance() + * or the first access to SingletonHolder.INSTANCE, not before. + */ + private static class SingletonHolder { + + public static final GroupRequestAdvisor instance = new GroupRequestAdvisor(); + } + + /** + * Get the instance of {@link GroupRequestAdvisor} + * + * @return + */ + public static GroupRequestAdvisor getInstance() { + return SingletonHolder.instance; + } + + /** + * Store all the listener + */ + private Multimap<EObject, IGroupNotifier> listenners; + + /** + * Logger + */ + private static LogHelper log = new LogHelper(UMLDiagramEditorPlugin.getInstance()); + + /*** + * Private constructor + */ + private GroupRequestAdvisor() { + listenners = ArrayListMultimap.create(); + } + + /** + * Add a {@link IGroupNotifier} + * + * @param editpolicy + */ + @Override + public void addListenner(EObject eObject, IGroupNotifier editpolicy) { + getListenerRegistry().put(eObject, editpolicy); + } + + /** + * Remove a {@link IGroupNotifier} + * + * @param editpolicy + */ + @Override + public void removeListenner(IGroupNotifier editpolicy) { + if (editpolicy == null) { + return; + } + Iterator<Entry<EObject, IGroupNotifier>> iterator = getListenerRegistry().entries().iterator(); + while (iterator.hasNext()) { + Entry<EObject, IGroupNotifier> entry = iterator.next(); + if (editpolicy.equals(entry.getValue())) { + iterator.remove(); + } + } + } + + @Override + public ICommand notifyGroupFramework(IGroupRequest request) { + if (DebugUtils.isDebugging()) { + log.debug("***********************BEGIN : Group Request Advisor***********************************"); + } + /****************** + * Handling parent + ******************/ + CompositeCommand cc = new CompositeCommand("Global command from GroupRequestAdvisor"); + Request initialRequest = request.getInitialRequest(); + if (initialRequest instanceof ChangeBoundsRequest) { + handleMove(request, cc); + } else if (initialRequest instanceof GroupRequest && RequestConstants.REQ_DELETE.equals(initialRequest.getType())) { + handleDelete(request, cc); + } + if (cc != null && !cc.isEmpty()) { + return cc; + } + return null; + } + + protected void handleDelete(IGroupRequest request, CompositeCommand cc) { + // request.getNodeDescpitor().getChildrenReferences() + } + + /** + * Handle move + * + * @param request + * @param cc + */ + protected void handleMove(IGroupRequest request, CompositeCommand cc) { + /* + * All parent + */ + fillRequestWithAllPossibleParent(request); + fillRequestWithAllPossibleChildren(request); + Object elementAdapter = request.getTargetElement().getAdapter(EObject.class); + if (elementAdapter instanceof EObject) { + /* + * Handle children + */ + handleSemanticChildren(request, cc, (EObject) elementAdapter); + /* + * Semantic of all the parent + */ + handleSemanticParents(request, cc, elementAdapter); + } + if (DebugUtils.isDebugging()) { + log.debug("***********************END : Group Request Advisor***********************************"); + } + // /* + // * For all new child send request + // * For all GrChild create new request from old one and use dispatcher + // */ + // if(cc != null && !cc.isEmpty()) { + // return cc; + // } + // return null; + } + + /** + * Handle all the children of the group (graphical and non graphical children) + * + * @param request + * @param cc + * @param targetElement + */ + protected void handleSemanticChildren(final IGroupRequest request, CompositeCommand cc, EObject targetElement) { + List<EObject> graphicalChildren = Lists.newArrayList(); + /* + * There is graphical childrne only when the node is moving + */ + if (request.getInitialRequest() instanceof ChangeBoundsRequest) { + graphicalChildren = handleGraphicalChildren(request, cc); + } + /* + * Unset + */ + for (Entry<EReference, EObject> oldChildrenEntry : Utils.getOldChildren(request).entries()) { + Multimap<EReference, EObject> allActualChildren = request.getChildrenEReferenceMap(); + EReference ref = oldChildrenEntry.getKey(); + if (ref != null) { + if (!allActualChildren.containsEntry(oldChildrenEntry.getValue(), ref)) { + EReference eOpposite = ref.getEOpposite(); + if (!graphicalChildren.contains(oldChildrenEntry.getValue())) { + if (eOpposite != null && !eOpposite.isContainment() && !ref.isContainment()) { + RemoveValueRequest rmVa = new RemoveValueRequest(targetElement, ref, Collections.singletonList(oldChildrenEntry.getValue())); + RemoveValueCommand rmCmd = new RemoveValueCommand(rmVa); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("From handling parent : Remove ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(ref)); + stringBuilder.append(" from ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(targetElement)); + stringBuilder.append(" value ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(oldChildrenEntry.getValue()));// + rmCmd.setLabel(stringBuilder.toString()); + if (rmCmd != null) { + cc.compose(rmCmd); + } + } + } + } + } + } + /* + * Set semantic + */ + Set<EObject> newChildren = Sets.newHashSet(); + for (Entry<EReference, EObject> entry : request.getChildrenEReferenceMap().entries()) { + EReference ref = entry.getKey(); + if (ref != null) { + EReference eOpposite = ref.getEOpposite(); + if (!graphicalChildren.contains(entry.getValue())) { + newChildren.add(entry.getValue()); + if (eOpposite != null && !eOpposite.isContainment()) { + SetDeferredRequest setRq = new SetDeferredRequest(request.getHostRequest().getEditingDomain(), request.getTargetElement(), ref, entry.getValue()); + DeferredSetValueCommand setCmd = new DeferredSetValueCommand(setRq); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("From handling parent : Set deferred");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(entry.getValue())); + stringBuilder.append(" from ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(ref)); + stringBuilder.append(" value ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(entry.getValue()));// + setCmd.setLabel(stringBuilder.toString()); + if (setCmd != null) { + cc.compose(setCmd); + } + } + } + } + if (!newChildren.isEmpty()) { + handleChangeParentNotificationCommand(request, cc, newChildren); + } + } + } + + /** + * Create a notification to user to ask him is he want to add its new children as graphical child of its parent group + * + * @param request + * {@link InitialContext} {@link IGroupRequest} + * @param cc + * {@link CompositeCommand} to compose new commands + * @param newChildren + * List of all new children + */ + protected void handleChangeParentNotificationCommand(final IGroupRequest request, CompositeCommand cc, Set<EObject> newChildren) { + /* + * Create dialog to suggest user to move views + */ + final IGraphicalEditPart host = request.getHostRequest(); + /* + * Get editpart of all children + */ + Iterable<IGroupNotifier> listOfChidren = Iterables.transform(newChildren, new Function<EObject, IGroupNotifier>() { + + @Override + public IGroupNotifier apply(EObject arg0) { + Collection<IGroupNotifier> notifiers = getListenerRegistry().get(arg0); + for (IGroupNotifier notifier : notifiers) { + IGraphicalEditPart notifierEditPart = notifier.getHostEditPart(); + if (notifierEditPart != null) { + if (EcoreUtil.isAncestor(host.getNotationView().getDiagram(), notifierEditPart.getNotationView())) { + return notifier; + } + } + } + return null; + } + }); + final Iterable<IGroupNotifier> listOfFilteredChidren = Iterables.filter(listOfChidren, Predicates.notNull()); + List<IGroupNotifier> automaticChildren = Lists.newArrayList(); + List<IGroupNotifier> nonAutomaticChildren = Lists.newArrayList(); + /* + * Dispatch children + */ + dispatchChildren(request, host, listOfFilteredChidren, automaticChildren, nonAutomaticChildren); + IGraphicalEditPart hostEditPart = request.getHostRequest(); + /* + * Command to change graphical parent for element when we can guess graphical parent + */ + for (IGroupNotifier notifier : automaticChildren) { + IGraphicalEditPart notifierEditPart = notifier.getHostEditPart(); + IGraphicalEditPart hostCompartmentEditPart = request.getNodeDescpitor().getCompartmentPartFromView(hostEditPart); + Request initialRequest = request.getInitialRequest(); + Rectangle hostBounds = null; + if (initialRequest instanceof ChangeBoundsRequest) { + hostBounds = Utils.getAbslotueRequestBounds((ChangeBoundsRequest) initialRequest, hostCompartmentEditPart); + } else { + hostBounds = Utils.getAbsoluteBounds(hostCompartmentEditPart); + } + Rectangle childBounds = Utils.getAbsoluteBounds(notifierEditPart); + MoveElementsCommand mvCmd = new MoveElementsCommand(new MoveRequest(hostCompartmentEditPart.getNotationView(), notifierEditPart.getNotationView())); + /* + * Integrate view into new compartment + */ + if (mvCmd != null && mvCmd.canExecute()) { + cc.compose(mvCmd); + } + /* + * Set view to the new location + */ + SetBoundsCommand setBoundCommand = new SetBoundsCommand(WorkspaceEditingDomainFactory.INSTANCE.getEditingDomain(host.getNotationView().eResource().getResourceSet()), "test", new EObjectAdapter(notifierEditPart.getNotationView()), + childBounds.translate(hostBounds.getLocation().negate())); + if (setBoundCommand != null && setBoundCommand.canExecute()) { + cc.compose(setBoundCommand); + } + } + /* + * Create notification for element where we can NOT guess the graphical parent + */ + if (!nonAutomaticChildren.isEmpty()) { + /* + * create runnable to run the command + */ + ChangeGraphicalParentRunnable changeGraphicalParentRunnable = new ChangeGraphicalParentRunnable(host, request); + final NotificationBuilder notification = createChangeGraphicalParentNotification(nonAutomaticChildren, changeGraphicalParentRunnable, hostEditPart); + RunNotificationCommand runNotifCmd = new RunNotificationCommand(request.getHostRequest().getEditingDomain(), "Notification command", getWorkspaceFiles(changeGraphicalParentRunnable.getModifiedObject()), notification);////$NON-NLS-1$ + cc.compose(runNotifCmd); + } + } + + /** + * Dispatch all children in two category. + * listOfFilteredChidren will contained all element to automatically add as graphical children + * nonAutomaticChildren will contained all element to ask the user what to do with + * + * @param request + * @param host + * @param listOfFilteredChidren + * @param automaticChildren + * @param nonAutomaticChildren + */ + private void dispatchChildren(final IGroupRequest request, final IGraphicalEditPart host, final Iterable<IGroupNotifier> listOfFilteredChidren, List<IGroupNotifier> automaticChildren, List<IGroupNotifier> nonAutomaticChildren) { + for (IGroupNotifier notifier : listOfFilteredChidren) { + IGraphicalEditPart parentEditPart = getGraphicalParent(notifier.getHostEditPart()); + if (parentEditPart != null) { + EObject eObject = parentEditPart.resolveSemanticElement(); + if (eObject instanceof ActivityGroup) { + ActivityGroup group = (ActivityGroup) eObject; + Collection<IGroupNotifier> groupNotifiers = listenners.get(group); + if (!groupNotifiers.isEmpty()) { + IGroupNotifier myGroupNotifier = groupNotifiers.iterator().next(); + /* + * Is the old container (an activity group) continaing the current moving element + */ + boolean isNewContainerVisuallyIncludeInOldContainer = myGroupNotifier.includes(Utils.getAbslotueRequestBounds((ChangeBoundsRequest) request.getInitialRequest(), host)); + /* + * Can the old container (an activity group) be a model a the current moving element + */ + boolean canTheOldContainerBeAModelParentOfTheNewContainer = myGroupNotifier.getHostGroupDescriptor().canIBeModelParentOf(host.resolveSemanticElement().eClass()); + /* + * + */ + boolean canTheNewContainerBeModelParentOfTheOldContianer = request.getNodeDescpitor().canIBeModelParentOf(host.resolveSemanticElement().eClass()); + /* + * Is the current moving element containing the old container + */ + IGroupNotifier currentElementNotifier = getIGroupNotifier(host); + boolean isOldContainerVisuallyIncludeInNewContainer = currentElementNotifier.includes(Utils.getAbsoluteBounds(myGroupNotifier.getHostEditPart())); + if (canTheOldContainerBeAModelParentOfTheNewContainer && isNewContainerVisuallyIncludeInOldContainer) { + /* + * Is going to be a new child of the old container + */ + automaticChildren.add(notifier); + } else if (canTheNewContainerBeModelParentOfTheOldContianer && isOldContainerVisuallyIncludeInNewContainer) { + /* + * Is going to be a new container for the old container + */ + } else { + /* + * There is no containing relation between the groups + */ + if (currentElementNotifier.getHostGroupDescriptor().getContainmentReferenceFor(notifier.getHostEditPart().resolveSemanticElement().eClass()) == null) { + nonAutomaticChildren.add(notifier); + } else { + // If containment link automatically add it to new group + automaticChildren.add(notifier); + } + } + } else { + /* + * No notifier where found + */ + nonAutomaticChildren.add(notifier); + } + } else { + /* + * If there is no container (which is group) + */ + if (!parentEditPart.equals(host)) { + automaticChildren.add(notifier); + } + } + } else { + DebugUtils.getLog().error("Unable to retreive graphical parent of " + Utils.getCorrectLabel(notifier), null); + } + } + } + + /** + * Get the IGroupNotifier of the {@link IGraphicalEditPart} passed in argument + * + * @param host + * @return + */ + private IGroupNotifier getIGroupNotifier(final IGraphicalEditPart host) { + EditPolicy editPolicy = host.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY); + if (editPolicy instanceof IGroupNotifier) { + return (IGroupNotifier) editPolicy; + } else { + editPolicy = host.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY); + if (editPolicy instanceof IGroupNotifier) { + return (IGroupNotifier) editPolicy; + } + } + throw new RuntimeException("Unable to retreive the IGroupNofier of the current group");////$NON-NLS-1$ + } + + /** + * Get the edit which represent the parent (semantically) of the edit part child passed in argument + * + * @param child + * @return + */ + private IGraphicalEditPart getGraphicalParent(IGraphicalEditPart child) { + IGraphicalEditPart result = child; + EObject childElement = child.resolveSemanticElement(); + if (child != null) { + while (childElement == result.resolveSemanticElement()) { + try { + result = (IGraphicalEditPart) result.getParent(); + } catch (ClassCastException e) { + return result; + } + } + } + return result; + } + + /** + * Create a notification to ask user if he want to change the graphical parent of some elements + * + * @param listOfFilteredChidren + * @param changeGraphicalParentRunnable + * @return + */ + private NotificationBuilder createChangeGraphicalParentNotification(final Iterable<IGroupNotifier> listOfFilteredChidren, ChangeGraphicalParentRunnable changeGraphicalParentRunnable, final IGraphicalEditPart host) { + return new NotificationBuilder().setType(Type.INFO).setAsynchronous(true).setTemporary(true).setDelay(3000).setTitle("Papyrus graphical modification").setComposite(new ICompositeCreator() { + + @Override + public Composite createComposite(Composite parent, FormToolkit toolkit) { + return new IntegrateViewToConfigureComposite(parent, SWT.NONE, Lists.newArrayList(Lists.newArrayList(listOfFilteredChidren)), "New elements are visually contained in the current group (" + Utils.getCorrectLabel(host) + + ").\n Please select the elements you want to integrate into this group figure."); + } + }).addAction(changeGraphicalParentRunnable); + } + + /** + * Handle graphical children + * + * @param request + * {@link IGroupRequest} + * @param cc + * {@link CompositeCommand} to compose new commands + * @return The list of all graphical children already handled + */ + protected List<EObject> handleGraphicalChildren(IGroupRequest request, CompositeCommand cc) { + /* + * List of all the graphical children + */ + List<EObject> graphicalChildren = new ArrayList<EObject>(); + /* + * Handle graphical children + */ + // Get graphical children + Object targetEditPart = request.getTargetElement().getAdapter(IGraphicalEditPart.class); + IGraphicalEditPart compartementEditPart = null; + if (targetEditPart instanceof IGroupCompartmentEditPart) { + compartementEditPart = ((IGraphicalEditPart) targetEditPart); + } else if (targetEditPart instanceof IGraphicalEditPart) { + IContainerNodeDescriptor nodeDescpitor = request.getNodeDescpitor(); + if (nodeDescpitor != null) { + compartementEditPart = nodeDescpitor.getCompartmentPartFromView((IGraphicalEditPart) targetEditPart); + } + } + if (compartementEditPart != null) { + /* + * Transform an IGraphicalEditPart to the related GroupNotifyingEditPolicy + */ + @SuppressWarnings("unchecked") + Iterable<GroupNotifyingOnMoveEditPolicy> policies = Iterables.transform(compartementEditPart.getChildren(), new Function<IGraphicalEditPart, GroupNotifyingOnMoveEditPolicy>() { + + @Override + public GroupNotifyingOnMoveEditPolicy apply(IGraphicalEditPart from) { + EditPolicy editPolicy = from.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY); + if (editPolicy instanceof GroupNotifyingOnMoveEditPolicy) { + return (GroupNotifyingOnMoveEditPolicy) editPolicy; + } + return null; + } + }); + for (final GroupNotifyingOnMoveEditPolicy p : policies) { + if (p != null) { + if (DebugUtils.isDebugging()) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("+++ Work for child "); + stringBuilder.append(Utils.getCorrectLabel(p.getEObject())); + stringBuilder.append(" +++"); + DebugUtils.getLog().debug(stringBuilder.toString()); + } + Request initialRequest = request.getInitialRequest(); + Request auxChReq = null; + if (initialRequest instanceof ChangeBoundsRequest) { + auxChReq = Utils.getChangeBoundsRequestCopy((ChangeBoundsRequest) initialRequest, p.getHostEditPart()); + } else { + auxChReq = initialRequest; + } + /* + * Save graphical parent + */ + // auxChReq.getExtendedData().put(GROUP_FRAMEWORK_GRAPHICAL_PARENT, compartementEditPart.resolveSemanticElement()); + graphicalChildren.add(p.getEObject()); + Command childCommand = p.getCommand(auxChReq); + if (childCommand != null && childCommand.canExecute()) { + cc.compose(new CommandProxy(childCommand)); + } + } + } + } + return graphicalChildren; + } + + /** + * Set and Unset semantic relation with parents + * + * @param request + * {@link IGroupRequest} + * @param cc + * {@link CompositeCommand} to compose command + * @param elementAdapter + */ + protected void handleSemanticParents(IGroupRequest request, CompositeCommand cc, Object elementAdapter) { + EObject targetElement = (EObject) elementAdapter; + Multimap<EReference, EObject> allActualParent = request.getParentEReferenceMap(); + for (Entry<EReference, EObject> entry : Utils.getOldParents(request).entries()) { + EReference ref = entry.getKey(); + if (ref != null) { + if (!allActualParent.containsEntry(ref, entry.getValue())) { + EReference eOpposite = ref.getEOpposite(); + if (eOpposite != null && !eOpposite.isContainment() && !eOpposite.isDerived()) { + RemoveValueRequest rmVa = new RemoveValueRequest(targetElement, ref, Collections.singletonList(entry.getValue())); + RemoveValueCommand rmCmd = new RemoveValueCommand(rmVa); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("From handling parent : Remove ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(entry.getValue())); + stringBuilder.append(" from ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(targetElement)); + stringBuilder.append(" value ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(entry.getValue()));// + rmCmd.setLabel(stringBuilder.toString()); + if (rmCmd != null) { + cc.compose(rmCmd); + } + } + // } + } + } + } + /* + * Set semantic + * If the EObject has not been already handle as graphical children + */ + for (Entry<EReference, EObject> entry : request.getParentEReferenceMap().entries()) { + EReference ref = entry.getKey(); + if (ref != null) { + EReference eOpposite = ref.getEOpposite(); + if (eOpposite != null && !eOpposite.isContainment() && !ref.isContainment()) { + SetDeferredRequest setRq = new SetDeferredRequest(request.getHostRequest().getEditingDomain(), request.getTargetElement(), ref, entry.getValue()); + DeferredSetValueCommand setCmd = new DeferredSetValueCommand(setRq); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("From handling parent : Set deferred ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(ref)); + stringBuilder.append(" from ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(request.getTargetElement())); + stringBuilder.append(" value ");////$NON-NLS-1$ + stringBuilder.append(Utils.getCorrectLabel(entry.getValue()));// + setCmd.setLabel(stringBuilder.toString()); + if (setCmd != null) { + cc.compose(setCmd); + } + } + } + } + } + + /** + * Return a list of all IGroupRequestListenner which can be children of the target of the request + * + * @param request + * @return + */ + protected Multimap<EReference, IGroupNotifier> fillRequestWithAllPossibleChildren(IGroupRequest request) { + final Multimap<EReference, IGroupNotifier> result = fillReqestWithReferendedElement(request, false, false); + /** + * TODO filter graphical parent which currently moving + * I1 in ActPart1 + * ActPart1 move into ActPart2 + * I1 should only reference ActPart1 + */ + /* + * Debug + */ + DebugUtils.displayMultipmapDebug(CHILDREN_REFERENCES_ARE, request.getChildrenEReferenceMap()); + return result; + } + + public EObject getPossibleModelParent(IGroupRequest request) { + Multimap<EReference, IGroupNotifier> parentsMap = fillReqestWithReferendedElement(request, true, true); + List<IGroupNotifier> parents = Lists.newArrayList(parentsMap.values()); + Collections.sort(parents); + if (!parents.isEmpty()) { + return parents.get(0).getEObject(); + } + return request.getHostRequest().resolveSemanticElement(); + } + + /** + * Return only current displayed listener + * + * @author adaussy + * + */ + private static class ActiveListener implements Predicate<IGroupNotifier> { + + private Diagram currentDiagramDisplayed; + + public ActiveListener(Diagram currentDiagramDisplayed) { + super(); + this.currentDiagramDisplayed = currentDiagramDisplayed; + Assert.isNotNull(currentDiagramDisplayed); + } + + @Override + public boolean apply(IGroupNotifier input) { + IGraphicalEditPart host = input.getHostEditPart(); + if (host != null) { + View primaryView = host.getPrimaryView(); + if (primaryView != null) { + return currentDiagramDisplayed.equals(primaryView.getDiagram()); + } + } + return false; + } + } + + /** + * Get all the element in references which are included or include (depending of the parameter include) + * + * @param request + * {@link IGroupRequest} + * @param newBounds + * New bounds of the elements + * @param references + * All references to take into account + * @param eReferenceMapToFillInRequest + * Map in the request to fill + * @param result + * {@link Map} which link a {@link EReference} to a {@link IGroupNotifier} + * @param containementOnly + * true if we are looking for containing references only + */ + protected void getReferenceElements(IGroupRequest request, final Rectangle newBounds, final List<EReference> references, Multimap<EReference, Element> eReferenceMapToFillInRequest, Multimap<EReference, IGroupNotifier> result, boolean include, + boolean containementOnly, Map<EStructuralFeature, EStructuralFeature> parentOpositeFeature) { + Iterable<IGroupNotifier> activeListeners = Iterables.filter(getListenerRegistry().values(), new ActiveListener(getCurrentlyDisplayedDiagram(request))); + for (IGroupNotifier input : activeListeners) { + EObject inputEObject = input.getEObject(); + if (inputEObject == null || !(inputEObject instanceof Element)) { + continue; + } + Object adapter = request.getTargetElement().getAdapter(EObject.class); + // EObject targetElement = null; + // if(adapter instanceof EObject) { + // targetElement = (EObject)adapter; + // } + if (inputEObject.equals(adapter)) { + continue; + } + EReference refenceFounded = null; + for (EReference ref : references) { + EClass refType = ref.getEReferenceType(); + EClass eoBjectType = inputEObject.eClass(); + if (refType.isSuperTypeOf(eoBjectType)) { + refenceFounded = ref; + break; + } + } + if (refenceFounded != null) { + if ((include && input.includes(newBounds)) || (!include && input.isIncludedIn(newBounds))) { + if (containementOnly && parentOpositeFeature.get(refenceFounded) instanceof EReference && !((EReference) parentOpositeFeature.get(refenceFounded)).isContainment()) { + continue; + } + eReferenceMapToFillInRequest.put(refenceFounded, (Element) inputEObject); + result.put(refenceFounded, input); + } + } + } + } + + /** + * Return the currently displayed diagram + * + * @param request + * @return + */ + protected Diagram getCurrentlyDisplayedDiagram(IGroupRequest request) { + IGraphicalEditPart graph = request.getHostRequest(); + if (graph != null) { + Object m = graph.getModel(); + if (m instanceof View) { + View v = (View) m; + return v.getDiagram(); + } + } + throw new RuntimeException("Unable to get the current diagram displayed");////$NON-NLS-1$ + } + + /** + * Return the list of all {@link IGroupNotifier} which can be parent of the target of the request + * + * @param request + * @return + */ + protected Multimap<EReference, IGroupNotifier> fillRequestWithAllPossibleParent(IGroupRequest request) { + final Multimap<EReference, IGroupNotifier> result = fillReqestWithReferendedElement(request, true, false); + /* + * Debug + */ + DebugUtils.displayMultipmapDebug(ALL_PARENT_REFERENCES_ARE, request.getParentEReferenceMap()); + return result; + } + + protected Multimap<EReference, IGroupNotifier> fillReqestWithReferendedElement(IGroupRequest request, boolean lookingForParent, boolean onlyContainment) { + final Rectangle newBounds = getInitalTargetRequestNewBounds(request); + final Multimap<EReference, IGroupNotifier> result = ArrayListMultimap.create(); + if (request.getNodeDescpitor() == null) { + return result; + } + List<EReference> references = null; + if (lookingForParent) { + references = request.getNodeDescpitor().getParentReferences(); + } else { + references = request.getNodeDescpitor().getChildrenReferences(); + } + final Multimap<EReference, IGroupNotifier> auxResult = ArrayListMultimap.create(); + final Multimap<EReference, Element> eReferenceLookedForMap = ArrayListMultimap.create(); + getReferenceElements(request, newBounds, references, eReferenceLookedForMap, auxResult, lookingForParent, onlyContainment, lookingForParent ? request.getNodeDescpitor().getParentEOppositeReferences() : null); + /* + * Filter ancestors + */ + for (EReference ref : eReferenceLookedForMap.keySet()) { + /* + * Filter descendant + * Example : + * 1 - ActPart1 include in Act1 then Act1 disappear + * 2 - ActPart1 include in ActPart2 then ActPart1 disappear + */ + Object adapter = request.getTargetElement().getAdapter(EObject.class); + if (adapter instanceof Element) { + Element element = (Element) adapter; + Predicate<Element> composedPredicate = Predicates.and(new SameContainerFilter(element), lookingForParent ? new DescendantsFilter(eReferenceLookedForMap.values()) : new AncestorFilter(eReferenceLookedForMap.values())); + Collection<Element> filteredCollection = Collections2.filter(eReferenceLookedForMap.get(ref), composedPredicate); + if (lookingForParent) { + request.getParentEReferenceMap().putAll(ref, filteredCollection); + } else { + request.getChildrenEReferenceMap().putAll(ref, filteredCollection); + } + } + } + for (EReference ref : auxResult.keySet()) { + /* + * Filter descendant + * Example : + * 1 - ActPart1 include in Act1 then Act1 disappear + * 2 - ActPart1 include in ActPart2 then ActPart1 disappear + */ + Iterable<IGroupNotifier> resultCollection = Iterables.filter(auxResult.get(ref), new DescendantsFilterIGroupNotifier(auxResult.values())); + result.putAll(ref, resultCollection); + } + return result; + } + + /** + * Get the absolute bounds of the target of the request + * + * @param request + * @return + */ + public static Rectangle getInitalTargetRequestNewBounds(final IGroupRequest request) { + Request initialRequest = request.getInitialRequest(); + if (initialRequest instanceof ChangeBoundsRequest) { + return Utils.getAbslotueRequestBounds((ChangeBoundsRequest) initialRequest, request.getHostRequest()); + } else if (initialRequest instanceof CreateViewRequest) { + return Utils.getAbslotueRequestBounds((CreateViewRequest) initialRequest); + } + throw new RuntimeException(UNABLE_TO_GET_THE_INTIAL_TARGET_REQUEST_BOUNDS); + } + + /** + * Convenience method to get a list of workspaces files associated with <code>eObject</code>. + * + * @param eObject + * the model object, may be <code>null</code> + * @return the list of {@link IFile}s + */ + protected static List getWorkspaceFiles(EObject eObject) { + List result = new ArrayList(); + if (eObject != null) { + Resource resource = eObject.eResource(); + if (resource != null) { + IFile file = WorkspaceSynchronizer.getFile(resource); + if (file != null) { + result.add(file); + } + } + } + return result; + } + + /** + * Convenience method to get a list of workspaces files associated with {@link EObject}s in <code>eObject</code>. + * + * @param eObjects + * the list of model object + * @return the list of {@link IFile}s + */ + protected static List getWorkspaceFiles(List eObjects) { + List result = new ArrayList(); + for (Iterator i = eObjects.iterator(); i.hasNext();) { + Object next = i.next(); + if (next instanceof EObject) { + Resource resource = ((EObject) next).eResource(); + if (resource != null) { + IFile file = WorkspaceSynchronizer.getFile(resource); + if (file != null) { + result.add(file); + } + } + } + } + return result; + } + + /** + * @return the listenners + */ + @Override + public Multimap<EObject, IGroupNotifier> getListenerRegistry() { + return listenners; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IContainerNodeDescriptor.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IContainerNodeDescriptor.java index 72f77c3f4ca..52adc476963 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IContainerNodeDescriptor.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IContainerNodeDescriptor.java @@ -1,95 +1,95 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup;
-
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-
-/**
- * Interface used to descripbe a node
- *
- * @author adaussy
- *
- */
-public interface IContainerNodeDescriptor extends Comparable<IContainerNodeDescriptor> {
-
- /**
- * Get the EReference used to contained a child of a specified eClass
- *
- * @param childType
- * @return
- */
- public EReference getContainmentReferenceFor(EClass childType);
-
- /**
- * Get all references that can used to reference an child of a specified eClass
- *
- * @param childType
- * @return
- */
- public List<EReference> getReferenceFor(EClass childType);
-
- /**
- * Can the node point by this node descriptor can be a an a parent of a child describe by the eClass childType
- *
- * @param childType
- * @return
- */
- public boolean canIBeModelParentOf(EClass childType);
-
- /**
- * Return true if the node can be a graphical parent of the child specified by its eClass
- *
- * @param childType
- * @return
- */
- public boolean canIBeGraphicalParentOf(EClass childType);
-
- /**
- * Get the corrent compartment form an edit part
- * (This is a limit the handle node can have only one compartment)
- *
- * @param editpart
- * @return
- */
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart);
-
- /**
- * Get all the references of the child
- *
- * @return
- */
- public List<EReference> getChildrenReferences();
-
- public List<EClass> getPossibleGraphicalChildren();
-
- public EClass getContainerEClass();
-
- public List<EReference> getParentReferences();
-
- public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences();
-
- /**
- * Return an int which define for a same child the priority of this parent to be its graphical father
- *
- * @return
- */
- public int getGroupPriority();
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup; + +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; + +/** + * Interface used to descripbe a node + * + * @author adaussy + * + */ +public interface IContainerNodeDescriptor extends Comparable<IContainerNodeDescriptor> { + + /** + * Get the EReference used to contained a child of a specified eClass + * + * @param childType + * @return + */ + public EReference getContainmentReferenceFor(EClass childType); + + /** + * Get all references that can used to reference an child of a specified eClass + * + * @param childType + * @return + */ + public List<EReference> getReferenceFor(EClass childType); + + /** + * Can the node point by this node descriptor can be a an a parent of a child describe by the eClass childType + * + * @param childType + * @return + */ + public boolean canIBeModelParentOf(EClass childType); + + /** + * Return true if the node can be a graphical parent of the child specified by its eClass + * + * @param childType + * @return + */ + public boolean canIBeGraphicalParentOf(EClass childType); + + /** + * Get the corrent compartment form an edit part + * (This is a limit the handle node can have only one compartment) + * + * @param editpart + * @return + */ + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart); + + /** + * Get all the references of the child + * + * @return + */ + public List<EReference> getChildrenReferences(); + + public List<EClass> getPossibleGraphicalChildren(); + + public EClass getContainerEClass(); + + public List<EReference> getParentReferences(); + + public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences(); + + /** + * Return an int which define for a same child the priority of this parent to be its graphical father + * + * @return + */ + public int getGroupPriority(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IGroupEditPolicies.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IGroupEditPolicies.java index 8a26e2822f9..08f407df115 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IGroupEditPolicies.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IGroupEditPolicies.java @@ -1,36 +1,36 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup;
-
-/**
- * @author arthur daussy
- */
-public interface IGroupEditPolicies {
-
- /**
- * Role for Edit Policy which notify event to the group framework
- */
- public static String GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY = "GroupFramework_NotifyingOnMoveEditPolicy";
-
- /**
- * Role for Edit Policy which notify event to the group framework
- */
- public static String GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY = "GroupFramework_NotifyingOnCreationEditPolicy";
-
- /**
- * Role for Edit Policy which handle group framework notification
- */
- public static String GROUP_FRAMEWORK_HANDLING_EDIT_POLICY = "GroupFramework_HandlingEditPolicy";
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup; + +/** + * @author arthur daussy + */ +public interface IGroupEditPolicies { + + /** + * Role for Edit Policy which notify event to the group framework + */ + public static String GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY = "GroupFramework_NotifyingOnMoveEditPolicy"; + + /** + * Role for Edit Policy which notify event to the group framework + */ + public static String GROUP_FRAMEWORK_NOTIFYING_ON_CREATION_EDIT_POLICY = "GroupFramework_NotifyingOnCreationEditPolicy"; + + /** + * Role for Edit Policy which handle group framework notification + */ + public static String GROUP_FRAMEWORK_HANDLING_EDIT_POLICY = "GroupFramework_HandlingEditPolicy"; +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IGroupRequestAdvisor.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IGroupRequestAdvisor.java index dad7dec3e65..e91648208e3 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IGroupRequestAdvisor.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/IGroupRequestAdvisor.java @@ -1,61 +1,61 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.IGroupRequest;
-
-import com.google.common.collect.Multimap;
-
-/**
- * Represent an advisor of Group Request. Should be able to handle group request
- *
- * @author arthur daussy
- *
- */
-public interface IGroupRequestAdvisor {
-
- /**
- * Remove the listener from the Group framework
- *
- * @param editpolicy
- */
- public void removeListenner(IGroupNotifier editpolicy);
-
- /**
- * Register into the group framework
- *
- * @param eObject
- * @param editpolicy
- */
- public void addListenner(EObject eObject, IGroupNotifier editpolicy);
-
- /**
- * Notify to the group framework a change (come from a Notifing Edit policy)
- *
- * @param request
- * @return
- */
- public ICommand notifyGroupFramework(IGroupRequest request);
-
- /**
- * Return all register edit policy
- *
- * @return
- */
- public Multimap<EObject, IGroupNotifier> getListenerRegistry();
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.IGroupRequest; + +import com.google.common.collect.Multimap; + +/** + * Represent an advisor of Group Request. Should be able to handle group request + * + * @author arthur daussy + * + */ +public interface IGroupRequestAdvisor { + + /** + * Remove the listener from the Group framework + * + * @param editpolicy + */ + public void removeListenner(IGroupNotifier editpolicy); + + /** + * Register into the group framework + * + * @param eObject + * @param editpolicy + */ + public void addListenner(EObject eObject, IGroupNotifier editpolicy); + + /** + * Notify to the group framework a change (come from a Notifing Edit policy) + * + * @param request + * @return + */ + public ICommand notifyGroupFramework(IGroupRequest request); + + /** + * Return all register edit policy + * + * @return + */ + public Multimap<EObject, IGroupNotifier> getListenerRegistry(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy.java index 15cc8bd1c40..8861ada17fc 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy.java @@ -1,34 +1,34 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy;
-
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-
-/**
- * Creation edit policy for Activiyt partition
- *
- * @author adaussy
- *
- */
-public class ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy extends GroupCreationEditPolicy {
-
- /**
- * Elements graphically shown inside partitions are semantically owned by the activity.
- * So default reparenting check (of different semantic containers) should be skipped for partition contents.
- */
- public ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy(IContainerNodeDescriptor groupDescriptor) {
- super(groupDescriptor);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy; + +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; + +/** + * Creation edit policy for Activiyt partition + * + * @author adaussy + * + */ +public class ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy extends GroupCreationEditPolicy { + + /** + * Elements graphically shown inside partitions are semantically owned by the activity. + * So default reparenting check (of different semantic containers) should be skipped for partition contents. + */ + public ActivityPartitionActivityPartitionContentCompartmentCreationEditPolicy(IContainerNodeDescriptor groupDescriptor) { + super(groupDescriptor); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/GroupCreationEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/GroupCreationEditPolicy.java index 4d6d1563899..9118eaeb20c 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/GroupCreationEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/GroupCreationEditPolicy.java @@ -1,314 +1,314 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy;
-
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.commands.UnexecutableCommand;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.diagram.core.edithelpers.CreateElementRequestAdapter;
-import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
-import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.commands.SemanticCreateCommand;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GroupEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.LabelEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy;
-import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramUIMessages;
-import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewAndElementRequest;
-import org.eclipse.gmf.runtime.diagram.ui.requests.EditCommandRequestWrapper;
-import org.eclipse.gmf.runtime.diagram.ui.requests.RefreshConnectionsRequest;
-import org.eclipse.gmf.runtime.emf.core.util.PackageUtil;
-import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ContainerNodeDescriptorRegistry;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.GroupRequestAdvisor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.AbstractGroupRequest;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.IGroupRequest;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils;
-
-public class GroupCreationEditPolicy extends CreationEditPolicy {
-
- /**
- * Node descriptor
- */
- private IContainerNodeDescriptor groupDescriptor;
-
- /**
- * @param groupDescriptor
- */
- public GroupCreationEditPolicy(IContainerNodeDescriptor groupDescriptor) {
- super();
- this.groupDescriptor = groupDescriptor;
- }
-
- /**
- * Return the {@link IContainerNodeDescriptor} of the group owning this edit policy
- *
- * @return
- */
- protected IContainerNodeDescriptor getGroupDescriptor() {
- return groupDescriptor;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy#getReparentCommand(org.eclipse.gef.requests.ChangeBoundsRequest)
- */
- @Override
- protected Command getReparentCommand(ChangeBoundsRequest request) {
- Iterator editParts = request.getEditParts().iterator();
- View container = (View) getHost().getAdapter(View.class);
- EObject context = container == null ? null : ViewUtil.resolveSemanticElement(container);
- CompositeCommand cc = new CompositeCommand(DiagramUIMessages.AddCommand_Label);
- while (editParts.hasNext()) {
- EditPart ep = (EditPart) editParts.next();
- if (ep instanceof LabelEditPart) {
- continue;
- }
- if (ep instanceof GroupEditPart) {
- cc.compose(getReparentGroupCommand((GroupEditPart) ep));
- }
- View view = (View) ep.getAdapter(View.class);
- if (view == null) {
- continue;
- }
- EObject semantic = ViewUtil.resolveSemanticElement(view);
- if (semantic == null) {
- cc.compose(getReparentViewCommand((IGraphicalEditPart) ep));
- } else if (context != null) {
- if (shouldReparentModel(semantic, context)) {
- cc.compose(getReparentCommand((IGraphicalEditPart) ep));
- } else if (shouldGraphicalyReparent(semantic, context)) {
- cc.compose(getReparentViewCommand((IGraphicalEditPart) ep));
- }
- }
- }
- return cc.isEmpty() ? null : new ICommandProxy(cc.reduce());
- }
-
- /**
- * Return true if the node is visually contained into the host
- *
- * @param ep
- * @return
- */
- protected boolean isVisuallyContained(IGraphicalEditPart ep, ChangeBoundsRequest request) {
- Rectangle hostBounds = Utils.getAbsoluteBounds((IGraphicalEditPart) getHost());
- Rectangle ndeBounds = Utils.getAbslotueRequestBounds(request, ep);
- return hostBounds.contains(ndeBounds);
- }
-
- /**
- * Return true if this element should be a model child of this element
- *
- * @param semantic
- * @param context
- * @return
- */
- protected boolean shouldReparentModel(EObject element, EObject newContext) {
- EReference feature = PackageUtil.findFeature(newContext.eClass(), element.eClass());
- return feature != null && feature.isContainment() && shouldReparent(element, newContext) && !isSameContainer(element, newContext);
- }
-
- /**
- * Return true if the element should be a graphical child to this element
- *
- * @param semantic
- * @param context
- * @return
- */
- protected boolean shouldGraphicalyReparent(EObject element, EObject newContext) {
- EReference feature = findFeatureWhichReference(newContext.eClass(), element.eClass());
- return feature != null && !feature.isContainment() && shouldReparent(element, newContext);
- }
-
- /**
- * Finds a feature that can contain an object of type eClass.
- *
- * @param container
- * The container <code>EClass</code>.
- * @param eClass
- * The contained <code>EClass</code>.
- * @return The found feature.
- */
- protected static EReference findFeatureWhichReference(EClass container, EClass eClass) {
- Iterator i = container.getEAllReferences().iterator();
- while (i.hasNext()) {
- EReference reference = (EReference) i.next();
- if (PackageUtil.canReference(container, reference, eClass)) {
- return reference;
- }
- }
- return null;
- }
-
- /**
- * Checks if a container <code>EClass</code> can reference another <code>EClass</code>.
- *
- * @param class1
- * The referencer <code>EClass</code>.
- * @param class2
- * The referenced <code>EClass</code>.
- * @return True if an object can contain other objects of a given type.
- */
- protected static boolean canReference(EClass class1, EClass class2) {
- Iterator i = class1.getEAllReferences().iterator();
- while (i.hasNext()) {
- EReference reference = (EReference) i.next();
- if (!reference.isContainment()) {
- EClass eType = (EClass) reference.getEType();
- if ((eType.equals(class2)) || (eType.isSuperTypeOf(class2))) {
- return true;
- }
- }
- }
- return false;
- }
-
- @Override
- protected boolean shouldReparent(EObject element, EObject newContext) {
- return !(element == null || element == newContext || isContainedIn(element, newContext));
- }
-
- /**
- * Return true if the the container of the element if the newContext
- *
- * @param element
- * @param newContext
- * @return
- */
- protected boolean isSameContainer(EObject element, EObject newContext) {
- return element.eContainer() == newContext;
- }
-
- /*
- * This method checks to see element's containment tree already includes
- * itself. This is necessary to prevent cyclic graphs in the model that
- * cause StackOverflowExceptions.
- */
- private boolean isContainedIn(EObject element, EObject newContext) {
- EObject container = newContext.eContainer();
- while (container != null) {
- if (container.equals(element)) {
- return true;
- }
- container = container.eContainer();
- }
- return false;
- }
-
- @Override
- public EditPart getTargetEditPart(Request request) {
- if (request instanceof ChangeBoundsRequest) {
- ChangeBoundsRequest chRequest = (ChangeBoundsRequest) request;
- List editParts = chRequest.getEditParts();
- if (editParts != null) {
- for (Object p : editParts) {
- if (p instanceof IGraphicalEditPart) {
- IGraphicalEditPart graphEditPart = (IGraphicalEditPart) p;
- if (isVisuallyContained(graphEditPart, chRequest)) {
- return getHost();
- }
- return ((IGraphicalEditPart) getHost()).getTopGraphicEditPart().getParent();
- }
- }
- }
- }
- return super.getTargetEditPart(request);
- }
-
- @Override
- protected Command getCreateElementAndViewCommand(CreateViewAndElementRequest request) {
- // get the element descriptor
- CreateElementRequestAdapter requestAdapter = request.getViewAndElementDescriptor().getCreateElementRequestAdapter();
- // get the semantic request
- CreateElementRequest createElementRequest = (CreateElementRequest) requestAdapter.getAdapter(CreateElementRequest.class);
- tryToFindModelParentFromGroupFramework(createElementRequest, new AbstractGroupRequest((IGraphicalEditPart) getHost(), request, request.getViewAndElementDescriptor().getElementAdapter(), ContainerNodeDescriptorRegistry.getInstance()
- .getContainerNodeDescriptor(createElementRequest.getElementType().getEClass())) {
-
- @Override
- public GroupRequestType getGroupRequestType() {
- return GroupRequestType.CREATION;
- }
- });
- if (createElementRequest.getContainer() == null) {
- // complete the semantic request by filling in the host's semantic
- // element as the context
- View view = (View) getHost().getModel();
- EObject hostElement = ViewUtil.resolveSemanticElement(view);
- if (hostElement == null && view.getElement() == null) {
- hostElement = view;
- }
- // Returns null if host is unresolvable so that trying to create a
- // new element in an unresolved shape will not be allowed.
- if (hostElement == null) {
- return null;
- }
- createElementRequest.setContainer(hostElement);
- }
- // get the create element command based on the elementdescriptor's
- // request
- Command createElementCommand = getHost().getCommand(new EditCommandRequestWrapper((CreateElementRequest) requestAdapter.getAdapter(CreateElementRequest.class), request.getExtendedData()));
- if (createElementCommand == null) {
- return UnexecutableCommand.INSTANCE;
- }
- if (!createElementCommand.canExecute()) {
- return createElementCommand;
- }
- // create the semantic create wrapper command
- SemanticCreateCommand semanticCommand = new SemanticCreateCommand(requestAdapter, createElementCommand);
- Command viewCommand = getCreateCommand(request);
- if (viewCommand == null) {
- return UnexecutableCommand.INSTANCE;
- }
- if (!viewCommand.canExecute()) {
- return UnexecutableCommand.INSTANCE;
- }
- Command refreshConnectionCommand = getHost().getCommand(new RefreshConnectionsRequest(((List) request.getNewObject())));
- // form the compound command and return
- CompositeCommand cc = new CompositeCommand(semanticCommand.getLabel());
- cc.compose(semanticCommand);
- cc.compose(new CommandProxy(viewCommand));
- if (refreshConnectionCommand != null) {
- cc.compose(new CommandProxy(refreshConnectionCommand));
- }
- return new ICommandProxy(cc);
- }
-
- /**
- * Try to set the container of the request thanks to the group framework
- *
- * @param createElementRequest
- */
- protected void tryToFindModelParentFromGroupFramework(CreateElementRequest createElementRequest, IGroupRequest request) {
- EObject parent = GroupRequestAdvisor.getInstance().getPossibleModelParent(request);
- if (parent != null) {
- createElementRequest.setContainer(parent);
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy; + +import java.util.Iterator; +import java.util.List; + +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.commands.UnexecutableCommand; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.diagram.core.edithelpers.CreateElementRequestAdapter; +import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil; +import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.commands.SemanticCreateCommand; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GroupEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.LabelEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy; +import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramUIMessages; +import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewAndElementRequest; +import org.eclipse.gmf.runtime.diagram.ui.requests.EditCommandRequestWrapper; +import org.eclipse.gmf.runtime.diagram.ui.requests.RefreshConnectionsRequest; +import org.eclipse.gmf.runtime.emf.core.util.PackageUtil; +import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ContainerNodeDescriptorRegistry; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.GroupRequestAdvisor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.AbstractGroupRequest; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.IGroupRequest; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils; + +public class GroupCreationEditPolicy extends CreationEditPolicy { + + /** + * Node descriptor + */ + private IContainerNodeDescriptor groupDescriptor; + + /** + * @param groupDescriptor + */ + public GroupCreationEditPolicy(IContainerNodeDescriptor groupDescriptor) { + super(); + this.groupDescriptor = groupDescriptor; + } + + /** + * Return the {@link IContainerNodeDescriptor} of the group owning this edit policy + * + * @return + */ + protected IContainerNodeDescriptor getGroupDescriptor() { + return groupDescriptor; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.diagram.ui.editpolicies.CreationEditPolicy#getReparentCommand(org.eclipse.gef.requests.ChangeBoundsRequest) + */ + @Override + protected Command getReparentCommand(ChangeBoundsRequest request) { + Iterator editParts = request.getEditParts().iterator(); + View container = (View) getHost().getAdapter(View.class); + EObject context = container == null ? null : ViewUtil.resolveSemanticElement(container); + CompositeCommand cc = new CompositeCommand(DiagramUIMessages.AddCommand_Label); + while (editParts.hasNext()) { + EditPart ep = (EditPart) editParts.next(); + if (ep instanceof LabelEditPart) { + continue; + } + if (ep instanceof GroupEditPart) { + cc.compose(getReparentGroupCommand((GroupEditPart) ep)); + } + View view = (View) ep.getAdapter(View.class); + if (view == null) { + continue; + } + EObject semantic = ViewUtil.resolveSemanticElement(view); + if (semantic == null) { + cc.compose(getReparentViewCommand((IGraphicalEditPart) ep)); + } else if (context != null) { + if (shouldReparentModel(semantic, context)) { + cc.compose(getReparentCommand((IGraphicalEditPart) ep)); + } else if (shouldGraphicalyReparent(semantic, context)) { + cc.compose(getReparentViewCommand((IGraphicalEditPart) ep)); + } + } + } + return cc.isEmpty() ? null : new ICommandProxy(cc.reduce()); + } + + /** + * Return true if the node is visually contained into the host + * + * @param ep + * @return + */ + protected boolean isVisuallyContained(IGraphicalEditPart ep, ChangeBoundsRequest request) { + Rectangle hostBounds = Utils.getAbsoluteBounds((IGraphicalEditPart) getHost()); + Rectangle ndeBounds = Utils.getAbslotueRequestBounds(request, ep); + return hostBounds.contains(ndeBounds); + } + + /** + * Return true if this element should be a model child of this element + * + * @param semantic + * @param context + * @return + */ + protected boolean shouldReparentModel(EObject element, EObject newContext) { + EReference feature = PackageUtil.findFeature(newContext.eClass(), element.eClass()); + return feature != null && feature.isContainment() && shouldReparent(element, newContext) && !isSameContainer(element, newContext); + } + + /** + * Return true if the element should be a graphical child to this element + * + * @param semantic + * @param context + * @return + */ + protected boolean shouldGraphicalyReparent(EObject element, EObject newContext) { + EReference feature = findFeatureWhichReference(newContext.eClass(), element.eClass()); + return feature != null && !feature.isContainment() && shouldReparent(element, newContext); + } + + /** + * Finds a feature that can contain an object of type eClass. + * + * @param container + * The container <code>EClass</code>. + * @param eClass + * The contained <code>EClass</code>. + * @return The found feature. + */ + protected static EReference findFeatureWhichReference(EClass container, EClass eClass) { + Iterator i = container.getEAllReferences().iterator(); + while (i.hasNext()) { + EReference reference = (EReference) i.next(); + if (PackageUtil.canReference(container, reference, eClass)) { + return reference; + } + } + return null; + } + + /** + * Checks if a container <code>EClass</code> can reference another <code>EClass</code>. + * + * @param class1 + * The referencer <code>EClass</code>. + * @param class2 + * The referenced <code>EClass</code>. + * @return True if an object can contain other objects of a given type. + */ + protected static boolean canReference(EClass class1, EClass class2) { + Iterator i = class1.getEAllReferences().iterator(); + while (i.hasNext()) { + EReference reference = (EReference) i.next(); + if (!reference.isContainment()) { + EClass eType = (EClass) reference.getEType(); + if ((eType.equals(class2)) || (eType.isSuperTypeOf(class2))) { + return true; + } + } + } + return false; + } + + @Override + protected boolean shouldReparent(EObject element, EObject newContext) { + return !(element == null || element == newContext || isContainedIn(element, newContext)); + } + + /** + * Return true if the the container of the element if the newContext + * + * @param element + * @param newContext + * @return + */ + protected boolean isSameContainer(EObject element, EObject newContext) { + return element.eContainer() == newContext; + } + + /* + * This method checks to see element's containment tree already includes + * itself. This is necessary to prevent cyclic graphs in the model that + * cause StackOverflowExceptions. + */ + private boolean isContainedIn(EObject element, EObject newContext) { + EObject container = newContext.eContainer(); + while (container != null) { + if (container.equals(element)) { + return true; + } + container = container.eContainer(); + } + return false; + } + + @Override + public EditPart getTargetEditPart(Request request) { + if (request instanceof ChangeBoundsRequest) { + ChangeBoundsRequest chRequest = (ChangeBoundsRequest) request; + List editParts = chRequest.getEditParts(); + if (editParts != null) { + for (Object p : editParts) { + if (p instanceof IGraphicalEditPart) { + IGraphicalEditPart graphEditPart = (IGraphicalEditPart) p; + if (isVisuallyContained(graphEditPart, chRequest)) { + return getHost(); + } + return ((IGraphicalEditPart) getHost()).getTopGraphicEditPart().getParent(); + } + } + } + } + return super.getTargetEditPart(request); + } + + @Override + protected Command getCreateElementAndViewCommand(CreateViewAndElementRequest request) { + // get the element descriptor + CreateElementRequestAdapter requestAdapter = request.getViewAndElementDescriptor().getCreateElementRequestAdapter(); + // get the semantic request + CreateElementRequest createElementRequest = (CreateElementRequest) requestAdapter.getAdapter(CreateElementRequest.class); + tryToFindModelParentFromGroupFramework(createElementRequest, new AbstractGroupRequest((IGraphicalEditPart) getHost(), request, request.getViewAndElementDescriptor().getElementAdapter(), ContainerNodeDescriptorRegistry.getInstance() + .getContainerNodeDescriptor(createElementRequest.getElementType().getEClass())) { + + @Override + public GroupRequestType getGroupRequestType() { + return GroupRequestType.CREATION; + } + }); + if (createElementRequest.getContainer() == null) { + // complete the semantic request by filling in the host's semantic + // element as the context + View view = (View) getHost().getModel(); + EObject hostElement = ViewUtil.resolveSemanticElement(view); + if (hostElement == null && view.getElement() == null) { + hostElement = view; + } + // Returns null if host is unresolvable so that trying to create a + // new element in an unresolved shape will not be allowed. + if (hostElement == null) { + return null; + } + createElementRequest.setContainer(hostElement); + } + // get the create element command based on the elementdescriptor's + // request + Command createElementCommand = getHost().getCommand(new EditCommandRequestWrapper((CreateElementRequest) requestAdapter.getAdapter(CreateElementRequest.class), request.getExtendedData())); + if (createElementCommand == null) { + return UnexecutableCommand.INSTANCE; + } + if (!createElementCommand.canExecute()) { + return createElementCommand; + } + // create the semantic create wrapper command + SemanticCreateCommand semanticCommand = new SemanticCreateCommand(requestAdapter, createElementCommand); + Command viewCommand = getCreateCommand(request); + if (viewCommand == null) { + return UnexecutableCommand.INSTANCE; + } + if (!viewCommand.canExecute()) { + return UnexecutableCommand.INSTANCE; + } + Command refreshConnectionCommand = getHost().getCommand(new RefreshConnectionsRequest(((List) request.getNewObject()))); + // form the compound command and return + CompositeCommand cc = new CompositeCommand(semanticCommand.getLabel()); + cc.compose(semanticCommand); + cc.compose(new CommandProxy(viewCommand)); + if (refreshConnectionCommand != null) { + cc.compose(new CommandProxy(refreshConnectionCommand)); + } + return new ICommandProxy(cc); + } + + /** + * Try to set the container of the request thanks to the group framework + * + * @param createElementRequest + */ + protected void tryToFindModelParentFromGroupFramework(CreateElementRequest createElementRequest, IGroupRequest request) { + EObject parent = GroupRequestAdvisor.getInstance().getPossibleModelParent(request); + if (parent != null) { + createElementRequest.setContainer(parent); + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/InterruptibleActivityRegionContentCompartmentCreationEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/InterruptibleActivityRegionContentCompartmentCreationEditPolicy.java index bf13917ff22..444598a6c9f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/InterruptibleActivityRegionContentCompartmentCreationEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/InterruptibleActivityRegionContentCompartmentCreationEditPolicy.java @@ -1,30 +1,30 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy;
-
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-
-/**
- * Handle creation in interruptible activity region content compartment
- *
- * @author adaussy
- *
- */
-public class InterruptibleActivityRegionContentCompartmentCreationEditPolicy extends GroupCreationEditPolicy {
-
- public InterruptibleActivityRegionContentCompartmentCreationEditPolicy(IContainerNodeDescriptor groupDescriptor) {
- super(groupDescriptor);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy; + +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; + +/** + * Handle creation in interruptible activity region content compartment + * + * @author adaussy + * + */ +public class InterruptibleActivityRegionContentCompartmentCreationEditPolicy extends GroupCreationEditPolicy { + + public InterruptibleActivityRegionContentCompartmentCreationEditPolicy(IContainerNodeDescriptor groupDescriptor) { + super(groupDescriptor); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/ActivityGroupEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/ActivityGroupEditPolicy.java index e74c64f49d4..5ddd35b9e08 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/ActivityGroupEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/ActivityGroupEditPolicy.java @@ -1,84 +1,84 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers;
-
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.EditPolicy;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.commands.UnexecutableCommand;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupEditPolicies;
-
-/**
- * The aim of the edit policy if to notify changes to the Group Framework for Activities Elements
- *
- * @author arthur daussy
- *
- */
-public class ActivityGroupEditPolicy extends GroupNotifyingOnMoveEditPolicy {
-
- /**
- *
- * @param groupDescriptor
- * IContainerNodeDescriptor
- */
- public ActivityGroupEditPolicy(IContainerNodeDescriptor groupDescriptor) {
- super(groupDescriptor);
- }
-
- /**
- * Override in order to:
- * - prevent Move of more than one Activity Group
- * - Initial Moving Edit Part State
- */
- @Override
- public Command getCommand(Request request) {
- if (understandsRequest(request)) {
- if (request instanceof ChangeBoundsRequest) {
- ChangeBoundsRequest chRq = (ChangeBoundsRequest) request;
- int compt = 0;
- if (chRq.getEditParts() != null) {
- for (Object p : chRq.getEditParts()) {
- if (p instanceof EditPart) {
- EditPart part = (EditPart) p;
- EditPolicy policy = part.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY);
- if (policy instanceof ActivityGroupEditPolicy) {
- compt++;
- }
- }
- }
- if (compt > 1) {
- return UnexecutableCommand.INSTANCE;
- }
- }
- initMovingPartState(chRq);
- Command cmd = super.getCommand(request);
- stopMovingPartState(chRq);
- return cmd;
- }
- }
- return null;
- }
-
- @Override
- public boolean understandsRequest(Request req) {
- if (req instanceof ChangeBoundsRequest) {
- return true;
- }
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers; + +import org.eclipse.gef.EditPart; +import org.eclipse.gef.EditPolicy; +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.commands.UnexecutableCommand; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupEditPolicies; + +/** + * The aim of the edit policy if to notify changes to the Group Framework for Activities Elements + * + * @author arthur daussy + * + */ +public class ActivityGroupEditPolicy extends GroupNotifyingOnMoveEditPolicy { + + /** + * + * @param groupDescriptor + * IContainerNodeDescriptor + */ + public ActivityGroupEditPolicy(IContainerNodeDescriptor groupDescriptor) { + super(groupDescriptor); + } + + /** + * Override in order to: + * - prevent Move of more than one Activity Group + * - Initial Moving Edit Part State + */ + @Override + public Command getCommand(Request request) { + if (understandsRequest(request)) { + if (request instanceof ChangeBoundsRequest) { + ChangeBoundsRequest chRq = (ChangeBoundsRequest) request; + int compt = 0; + if (chRq.getEditParts() != null) { + for (Object p : chRq.getEditParts()) { + if (p instanceof EditPart) { + EditPart part = (EditPart) p; + EditPolicy policy = part.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY); + if (policy instanceof ActivityGroupEditPolicy) { + compt++; + } + } + } + if (compt > 1) { + return UnexecutableCommand.INSTANCE; + } + } + initMovingPartState(chRq); + Command cmd = super.getCommand(request); + stopMovingPartState(chRq); + return cmd; + } + } + return null; + } + + @Override + public boolean understandsRequest(Request req) { + if (req instanceof ChangeBoundsRequest) { + return true; + } + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/ActivityNodeEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/ActivityNodeEditPolicy.java index 65bb3da56f3..fd28f978f7a 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/ActivityNodeEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/ActivityNodeEditPolicy.java @@ -1,35 +1,35 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers;
-
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-import org.eclipse.uml2.uml.ActivityNode;
-
-/**
- * Implementation of {@link GroupNotifyingOnMoveEditPolicy} for {@link ActivityNode}
- *
- * @author arthur daussy
- *
- */
-public class ActivityNodeEditPolicy extends GroupNotifyingOnMoveEditPolicy {
-
- /**
- *
- * @param groupDescriptor
- */
- public ActivityNodeEditPolicy(IContainerNodeDescriptor groupDescriptor) {
- super(groupDescriptor);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers; + +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; +import org.eclipse.uml2.uml.ActivityNode; + +/** + * Implementation of {@link GroupNotifyingOnMoveEditPolicy} for {@link ActivityNode} + * + * @author arthur daussy + * + */ +public class ActivityNodeEditPolicy extends GroupNotifyingOnMoveEditPolicy { + + /** + * + * @param groupDescriptor + */ + public ActivityNodeEditPolicy(IContainerNodeDescriptor groupDescriptor) { + super(groupDescriptor); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupListenerEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupListenerEditPolicy.java index 58fa10df50c..d946dc64ce6 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupListenerEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupListenerEditPolicy.java @@ -1,245 +1,245 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.GraphicalNodeEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ContainerNodeDescriptorRegistry;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.GroupRequestAdvisor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupRequestAdvisor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils;
-
-/**
- * Edit policy use as based for Group Edit Policies
- *
- * @author arthur daussy
- *
- */
-public abstract class GroupListenerEditPolicy extends GraphicalNodeEditPolicy implements IGroupNotifier {
-
- /**
- * {@link IContainerNodeDescriptor} which describe the relation that the semantic element can handle
- */
- private IContainerNodeDescriptor groupDescriptor;
-
- /**
- * State of the part. Return true is the part is currently moving
- */
- private boolean isMoving = false;
-
- /**
- * Moving request
- */
- private ChangeBoundsRequest movingRequest;
-
- /**
- * Constructor
- *
- * @param groupDescriptor
- * {@link IContainerNodeDescriptor} which describe the relation that the semantic element can handle
- */
- public GroupListenerEditPolicy(IContainerNodeDescriptor groupDescriptor) {
- super();
- this.groupDescriptor = groupDescriptor;
- }
-
- /**
- * {@inheritDoc IGroupNotifier#getEObject()}
- */
- @Override
- public EObject getEObject() {
- EditPart editPart = getHost();
- if (editPart instanceof IGraphicalEditPart) {
- return ((IGraphicalEditPart) editPart).resolveSemanticElement();
- }
- return null;
- }
-
- /**
- * Override to unregister this edit part from the group framework
- */
- @Override
- public void deactivate() {
- GroupRequestAdvisor.getInstance().removeListenner(this);
- super.deactivate();
- }
-
- /**
- * Override to register this edit part into the group framework
- */
- @Override
- public void activate() {
- EObject resolveSemanticElement = getHostEditPart().resolveSemanticElement();
- if (resolveSemanticElement != null) {
- GroupRequestAdvisor.getInstance().addListenner(resolveSemanticElement, this);
- }
- super.activate();
- }
-
- /**
- * {@inheritDoc IGroupNotifier#getGroupDescriptor()}
- */
- @Override
- public IContainerNodeDescriptor getHostGroupDescriptor() {
- return groupDescriptor;
- }
-
- /**
- * {@inheritDoc IGroupNotifier#getGroupRequestAdvisor()}
- */
- protected IGroupRequestAdvisor getGroupRequestAdvisor() {
- return GroupRequestAdvisor.getInstance();
- }
-
- /**
- * {@inheritDoc IGroupNotifier#getHostEditPart()}
- */
- @Override
- public IGraphicalEditPart getHostEditPart() {
- return (IGraphicalEditPart) getHost();
- }
-
- /**
- * {@inheritDoc IGroupNotifier#isIncludedIn()}
- */
- @Override
- public boolean isIncludedIn(Rectangle bounds) {
- Rectangle figureBounds = null;
- if (isMoving()) {
- figureBounds = Utils.getAbslotueRequestBounds(getMovingRequest(), getHostEditPart());
- } else {
- figureBounds = Utils.getAbsoluteBounds(getHostEditPart());
- }
- return bounds.contains(figureBounds);
- }
-
- /**
- * {@inheritDoc IGroupNotifier#includes()}
- */
- @Override
- public boolean includes(Rectangle bounds) {
- if (getHost() == null) {
- return false;
- }
- IGraphicalEditPart compartmentEditPart = getHostGroupDescriptor().getCompartmentPartFromView(getHostEditPart());
- if (compartmentEditPart != null) {
- Rectangle figureBounds = null;
- if (isMoving()) {
- figureBounds = Utils.getAbslotueRequestBounds(getMovingRequest(), compartmentEditPart);
- } else {
- figureBounds = Utils.getAbsoluteBounds(compartmentEditPart);
- }
- return figureBounds.contains(bounds);
- }
- return false;
- }
-
- /**
- * {@inheritDoc IAdaptable#getAdapter(Class)}
- */
- @Override
- public Object getAdapter(Class adapter) {
- if (IContainerNodeDescriptor.class.isAssignableFrom(adapter)) {
- return groupDescriptor;
- } else {
- return getHostEditPart().getAdapter(adapter);
- }
- }
-
- /**
- * {@inheritDoc Comparable#compareTo(Object)}
- */
- @Override
- public int compareTo(IGroupNotifier o) {
- return getHostGroupDescriptor().compareTo(o.getHostGroupDescriptor());
- }
-
- /**
- * {@inheritDoc IGroupNotifier#startMoving()}
- */
- @Override
- public void startMoving(ChangeBoundsRequest request) {
- setMoving(true);
- setMovingRequest(request);
- }
-
- /**
- * {@inheritDoc IGroupNotifier#stopMoving()}
- */
- @Override
- public void stopMoving() {
- setMoving(false);
- setMovingRequest(null);
- }
-
- /**
- * Get the moving parameter
- *
- * @return
- */
- protected boolean isMoving() {
- return isMoving;
- }
-
- protected ChangeBoundsRequest getMovingRequest() {
- return movingRequest;
- }
-
- protected void setMovingRequest(ChangeBoundsRequest movingRequest) {
- this.movingRequest = movingRequest;
- }
-
- protected void setMoving(boolean isMoving) {
- this.isMoving = isMoving;
- }
-
- /**
- * {@inheritDoc IGroupNotifier#isPartMoving()}
- */
- @Override
- public boolean isPartMoving() {
- return isMoving();
- }
-
- @Override
- public IAdaptable getAdaptableView() {
- return getViewAdapter();
- }
-
- @Override
- public void eraseTargetFeedback(Request request) {
- }
-
- @Override
- public void showSourceFeedback(Request request) {
- }
-
- @Override
- public IContainerNodeDescriptor getTargetGroupDescriptor(IAdaptable eObjectAdapter) {
- Object adapted = eObjectAdapter.getAdapter(EObject.class);
- if (adapted instanceof EObject) {
- EObject eObject = (EObject) adapted;
- return ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(eObject.eClass());
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.Request; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.GraphicalNodeEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ContainerNodeDescriptorRegistry; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.GroupRequestAdvisor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupRequestAdvisor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils; + +/** + * Edit policy use as based for Group Edit Policies + * + * @author arthur daussy + * + */ +public abstract class GroupListenerEditPolicy extends GraphicalNodeEditPolicy implements IGroupNotifier { + + /** + * {@link IContainerNodeDescriptor} which describe the relation that the semantic element can handle + */ + private IContainerNodeDescriptor groupDescriptor; + + /** + * State of the part. Return true is the part is currently moving + */ + private boolean isMoving = false; + + /** + * Moving request + */ + private ChangeBoundsRequest movingRequest; + + /** + * Constructor + * + * @param groupDescriptor + * {@link IContainerNodeDescriptor} which describe the relation that the semantic element can handle + */ + public GroupListenerEditPolicy(IContainerNodeDescriptor groupDescriptor) { + super(); + this.groupDescriptor = groupDescriptor; + } + + /** + * {@inheritDoc IGroupNotifier#getEObject()} + */ + @Override + public EObject getEObject() { + EditPart editPart = getHost(); + if (editPart instanceof IGraphicalEditPart) { + return ((IGraphicalEditPart) editPart).resolveSemanticElement(); + } + return null; + } + + /** + * Override to unregister this edit part from the group framework + */ + @Override + public void deactivate() { + GroupRequestAdvisor.getInstance().removeListenner(this); + super.deactivate(); + } + + /** + * Override to register this edit part into the group framework + */ + @Override + public void activate() { + EObject resolveSemanticElement = getHostEditPart().resolveSemanticElement(); + if (resolveSemanticElement != null) { + GroupRequestAdvisor.getInstance().addListenner(resolveSemanticElement, this); + } + super.activate(); + } + + /** + * {@inheritDoc IGroupNotifier#getGroupDescriptor()} + */ + @Override + public IContainerNodeDescriptor getHostGroupDescriptor() { + return groupDescriptor; + } + + /** + * {@inheritDoc IGroupNotifier#getGroupRequestAdvisor()} + */ + protected IGroupRequestAdvisor getGroupRequestAdvisor() { + return GroupRequestAdvisor.getInstance(); + } + + /** + * {@inheritDoc IGroupNotifier#getHostEditPart()} + */ + @Override + public IGraphicalEditPart getHostEditPart() { + return (IGraphicalEditPart) getHost(); + } + + /** + * {@inheritDoc IGroupNotifier#isIncludedIn()} + */ + @Override + public boolean isIncludedIn(Rectangle bounds) { + Rectangle figureBounds = null; + if (isMoving()) { + figureBounds = Utils.getAbslotueRequestBounds(getMovingRequest(), getHostEditPart()); + } else { + figureBounds = Utils.getAbsoluteBounds(getHostEditPart()); + } + return bounds.contains(figureBounds); + } + + /** + * {@inheritDoc IGroupNotifier#includes()} + */ + @Override + public boolean includes(Rectangle bounds) { + if (getHost() == null) { + return false; + } + IGraphicalEditPart compartmentEditPart = getHostGroupDescriptor().getCompartmentPartFromView(getHostEditPart()); + if (compartmentEditPart != null) { + Rectangle figureBounds = null; + if (isMoving()) { + figureBounds = Utils.getAbslotueRequestBounds(getMovingRequest(), compartmentEditPart); + } else { + figureBounds = Utils.getAbsoluteBounds(compartmentEditPart); + } + return figureBounds.contains(bounds); + } + return false; + } + + /** + * {@inheritDoc IAdaptable#getAdapter(Class)} + */ + @Override + public Object getAdapter(Class adapter) { + if (IContainerNodeDescriptor.class.isAssignableFrom(adapter)) { + return groupDescriptor; + } else { + return getHostEditPart().getAdapter(adapter); + } + } + + /** + * {@inheritDoc Comparable#compareTo(Object)} + */ + @Override + public int compareTo(IGroupNotifier o) { + return getHostGroupDescriptor().compareTo(o.getHostGroupDescriptor()); + } + + /** + * {@inheritDoc IGroupNotifier#startMoving()} + */ + @Override + public void startMoving(ChangeBoundsRequest request) { + setMoving(true); + setMovingRequest(request); + } + + /** + * {@inheritDoc IGroupNotifier#stopMoving()} + */ + @Override + public void stopMoving() { + setMoving(false); + setMovingRequest(null); + } + + /** + * Get the moving parameter + * + * @return + */ + protected boolean isMoving() { + return isMoving; + } + + protected ChangeBoundsRequest getMovingRequest() { + return movingRequest; + } + + protected void setMovingRequest(ChangeBoundsRequest movingRequest) { + this.movingRequest = movingRequest; + } + + protected void setMoving(boolean isMoving) { + this.isMoving = isMoving; + } + + /** + * {@inheritDoc IGroupNotifier#isPartMoving()} + */ + @Override + public boolean isPartMoving() { + return isMoving(); + } + + @Override + public IAdaptable getAdaptableView() { + return getViewAdapter(); + } + + @Override + public void eraseTargetFeedback(Request request) { + } + + @Override + public void showSourceFeedback(Request request) { + } + + @Override + public IContainerNodeDescriptor getTargetGroupDescriptor(IAdaptable eObjectAdapter) { + Object adapted = eObjectAdapter.getAdapter(EObject.class); + if (adapted instanceof EObject) { + EObject eObject = (EObject) adapted; + return ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(eObject.eClass()); + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupNotifyingInCreationEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupNotifyingInCreationEditPolicy.java index 76069fddc96..c36fe23648f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupNotifyingInCreationEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupNotifyingInCreationEditPolicy.java @@ -1,152 +1,152 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers;
-
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.common.command.CompoundCommand;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.internal.commands.RefreshEditPartCommand;
-import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.commands.wrappers.EMFtoGEFCommandWrapper;
-import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper;
-import org.eclipse.papyrus.infra.emf.gmf.command.GMFtoEMFCommandWrapper;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ContainerNodeDescriptorRegistry;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.GroupRequestAdvisor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupRequestAdvisor;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Policy which catch creation event in order to integrated it into the group framework
- *
- * @author arthur daussy
- *
- */
-public class GroupNotifyingInCreationEditPolicy extends GroupListenerEditPolicy {
-
- private static String FAKE_MOVE_COMMAND_TYPE = "FAKE_MOVE_COMMAND_TYPE";
-
- public GroupNotifyingInCreationEditPolicy(IContainerNodeDescriptor groupDescriptor) {
- super(groupDescriptor);
- }
-
- @Override
- public Command getCommand(Request request) {
- if (request instanceof CreateViewRequest) {
- final CreateViewRequest c = (CreateViewRequest) request;
- return new EMFtoGEFCommandWrapper(new DeferredFakeMoveCommand(getHostEditPart().getEditingDomain(), "Fake move command to integrate into group framework", c, getHost().getViewer().getEditPartRegistry()));
- }
- return null;
- }
-
- /**
- * Fake move command with a special type which will simulate a change bounds request in the newly create element in order to integrate it in te
- * group framework
- *
- * @author arthur daussy
- *
- */
- private class DeferredFakeMoveCommand extends CompoundCommand {
-
- /**
- * Initial Create View Request
- */
- private CreateViewRequest request;
-
- /**
- * Edit part registry
- */
- private Map editPartRegistry;
-
- /**
- * Special the for the fake move command
- */
- public DeferredFakeMoveCommand(TransactionalEditingDomain domain, String label, CreateViewRequest request, Map editPartRegistry) {
- super(label);
- this.request = request;
- this.editPartRegistry = editPartRegistry;
- }
-
- @Override
- public boolean canExecute() {
- return true;
- }
-
- @Override
- public void execute() {
- Object newObject = request.getNewObject();
- /*
- * Try to get the newly created view
- */
- if (newObject instanceof List<?> && !((List<?>) newObject).isEmpty()) {
- Object newObj = ((List<?>) newObject).get(0);
- if (newObj instanceof IAdaptable) {
- IAdaptable adpatable = (IAdaptable) newObj;
- Object v = adpatable.getAdapter(View.class);
- if (v instanceof View) {
- View view = (View) v;
- /*
- * Try to get the related editpart
- */
- Object editPart = editPartRegistry.get(view);
- if (editPart instanceof IGraphicalEditPart) {
- /*
- * Send a fake change bounds request
- */
- IGraphicalEditPart graphEdit = (IGraphicalEditPart) editPart;
- IGraphicalEditPart compartmentEditPart = ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY_PARTITION).getCompartmentPartFromView(graphEdit);
- if (compartmentEditPart != null) {
- RefreshEditPartCommand refreshCommand = new RefreshEditPartCommand(compartmentEditPart, true);
- if (refreshCommand.canExecute()) {
- appendAndExecute(new GMFtoEMFCommandWrapper(refreshCommand));
- }
- }
- ChangeBoundsRequest changeBoundRequest = new ChangeBoundsRequest(FAKE_MOVE_COMMAND_TYPE);
- changeBoundRequest.setEditParts(graphEdit);
- Command fakeMoveCommand = graphEdit.getCommand(changeBoundRequest);
- if (fakeMoveCommand != null && fakeMoveCommand.canExecute()) {
- appendAndExecute(new GEFtoEMFCommandWrapper(fakeMoveCommand));
- }
- }
- }
- }
- }
- }
- }
-
- @Override
- protected IGroupRequestAdvisor getGroupRequestAdvisor() {
- return GroupRequestAdvisor.getInstance();
- }
-
- /**
- * Override in order to accept correct request
- */
- @Override
- public boolean understandsRequest(Request req) {
- if (req instanceof ChangeBoundsRequest) {
- return true;
- }
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers; + +import java.util.List; +import java.util.Map; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.common.command.CompoundCommand; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.internal.commands.RefreshEditPartCommand; +import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.commands.wrappers.EMFtoGEFCommandWrapper; +import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper; +import org.eclipse.papyrus.infra.emf.gmf.command.GMFtoEMFCommandWrapper; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ContainerNodeDescriptorRegistry; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.GroupRequestAdvisor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupRequestAdvisor; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Policy which catch creation event in order to integrated it into the group framework + * + * @author arthur daussy + * + */ +public class GroupNotifyingInCreationEditPolicy extends GroupListenerEditPolicy { + + private static String FAKE_MOVE_COMMAND_TYPE = "FAKE_MOVE_COMMAND_TYPE"; + + public GroupNotifyingInCreationEditPolicy(IContainerNodeDescriptor groupDescriptor) { + super(groupDescriptor); + } + + @Override + public Command getCommand(Request request) { + if (request instanceof CreateViewRequest) { + final CreateViewRequest c = (CreateViewRequest) request; + return new EMFtoGEFCommandWrapper(new DeferredFakeMoveCommand(getHostEditPart().getEditingDomain(), "Fake move command to integrate into group framework", c, getHost().getViewer().getEditPartRegistry())); + } + return null; + } + + /** + * Fake move command with a special type which will simulate a change bounds request in the newly create element in order to integrate it in te + * group framework + * + * @author arthur daussy + * + */ + private class DeferredFakeMoveCommand extends CompoundCommand { + + /** + * Initial Create View Request + */ + private CreateViewRequest request; + + /** + * Edit part registry + */ + private Map editPartRegistry; + + /** + * Special the for the fake move command + */ + public DeferredFakeMoveCommand(TransactionalEditingDomain domain, String label, CreateViewRequest request, Map editPartRegistry) { + super(label); + this.request = request; + this.editPartRegistry = editPartRegistry; + } + + @Override + public boolean canExecute() { + return true; + } + + @Override + public void execute() { + Object newObject = request.getNewObject(); + /* + * Try to get the newly created view + */ + if (newObject instanceof List<?> && !((List<?>) newObject).isEmpty()) { + Object newObj = ((List<?>) newObject).get(0); + if (newObj instanceof IAdaptable) { + IAdaptable adpatable = (IAdaptable) newObj; + Object v = adpatable.getAdapter(View.class); + if (v instanceof View) { + View view = (View) v; + /* + * Try to get the related editpart + */ + Object editPart = editPartRegistry.get(view); + if (editPart instanceof IGraphicalEditPart) { + /* + * Send a fake change bounds request + */ + IGraphicalEditPart graphEdit = (IGraphicalEditPart) editPart; + IGraphicalEditPart compartmentEditPart = ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(UMLPackage.Literals.ACTIVITY_PARTITION).getCompartmentPartFromView(graphEdit); + if (compartmentEditPart != null) { + RefreshEditPartCommand refreshCommand = new RefreshEditPartCommand(compartmentEditPart, true); + if (refreshCommand.canExecute()) { + appendAndExecute(new GMFtoEMFCommandWrapper(refreshCommand)); + } + } + ChangeBoundsRequest changeBoundRequest = new ChangeBoundsRequest(FAKE_MOVE_COMMAND_TYPE); + changeBoundRequest.setEditParts(graphEdit); + Command fakeMoveCommand = graphEdit.getCommand(changeBoundRequest); + if (fakeMoveCommand != null && fakeMoveCommand.canExecute()) { + appendAndExecute(new GEFtoEMFCommandWrapper(fakeMoveCommand)); + } + } + } + } + } + } + } + + @Override + protected IGroupRequestAdvisor getGroupRequestAdvisor() { + return GroupRequestAdvisor.getInstance(); + } + + /** + * Override in order to accept correct request + */ + @Override + public boolean understandsRequest(Request req) { + if (req instanceof ChangeBoundsRequest) { + return true; + } + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupNotifyingOnMoveEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupNotifyingOnMoveEditPolicy.java index e7b51f14f55..735cb7f9e97 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupNotifyingOnMoveEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/GroupNotifyingOnMoveEditPolicy.java @@ -1,148 +1,148 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers;
-
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.EditPolicy;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.GroupRequestAdvisor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupEditPolicies;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupRequestAdvisor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.AbstractGroupRequest;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.DebugUtils;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils;
-
-/**
- * Implementation of {@link GroupListenerEditPolicy} for Activity Group
- *
- * @author adaussy
- *
- */
-public class GroupNotifyingOnMoveEditPolicy extends GroupListenerEditPolicy {
-
- public GroupNotifyingOnMoveEditPolicy(IContainerNodeDescriptor groupDescriptor) {
- super(groupDescriptor);
- }
-
- /**
- * Override to :
- * -> Put in "Movin state" this edit part and all its children which are Group Framework concern
- */
- @Override
- public Command getCommand(Request request) {
- if (request instanceof ChangeBoundsRequest) {
- final ChangeBoundsRequest req = (ChangeBoundsRequest) request;
- CompositeCommand cc = new CompositeCommand("GroupNotifyingEditPolicy ");
- for (final EditPart part : Utils.getTargetedEditPart(req)) {
- ICommand cmd = getGroupRequestAdvisor().notifyGroupFramework(new AbstractGroupRequest((IGraphicalEditPart) getHost(), Utils.getChangeBoundsRequestCopy(req, part), part, getTargetGroupDescriptor(part)) {
-
- @Override
- public GroupRequestType getGroupRequestType() {
- return GroupRequestType.MOVE;
- }
- });
- if (cmd != null && cmd.canExecute()) {
- cc.compose(cmd);
- }
- }
- stopMovingPartState(req);
- if (cc != null && cc.canExecute()) {
- return new ICommandProxy(cc);
- }
- }
- return null;
- }
-
- /**
- * Set the art concern by the request to "Moving state" {@link IGroupNotifier#isPartMoving()}
- *
- * @param req
- */
- public void stopMovingPartState(final ChangeBoundsRequest req) {
- Iterable<IGraphicalEditPart> targetedEditPart = Utils.getTargetedEditPart(req);
- stopMovingParts(targetedEditPart);
- }
-
- /**
- * Set all part specify and its descendant to "Moving State"
- *
- * @param targetedEditPart
- */
- protected void stopMovingParts(Iterable<IGraphicalEditPart> targetedEditPart) {
- if (targetedEditPart != null) {
- for (EditPart part : targetedEditPart) {
- EditPolicy editPolicy = part.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY);
- if (editPolicy instanceof GroupNotifyingOnMoveEditPolicy) {
- GroupNotifyingOnMoveEditPolicy editPolicy2 = (GroupNotifyingOnMoveEditPolicy) editPolicy;
- if (DebugUtils.isDebugging()) {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(Utils.getCorrectLabel(editPolicy2.getEObject()));
- stringBuilder.append(" is stoping to move");
- DebugUtils.getLog().debug(stringBuilder.toString());
- }
- editPolicy2.stopMoving();
- }
- stopMovingParts(part.getChildren());
- }
- }
- }
-
- public void initMovingPartState(final ChangeBoundsRequest req) {
- Iterable<IGraphicalEditPart> targetedEditPart = Utils.getTargetedEditPart(req);
- startMovingParts(req, targetedEditPart);
- }
-
- protected void startMovingParts(final ChangeBoundsRequest req, Iterable<IGraphicalEditPart> targetedEditPart) {
- if (targetedEditPart != null) {
- for (final EditPart part : targetedEditPart) {
- EditPolicy editPolicy = part.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY);
- if (editPolicy instanceof GroupNotifyingOnMoveEditPolicy) {
- GroupNotifyingOnMoveEditPolicy editPolicy2 = (GroupNotifyingOnMoveEditPolicy) editPolicy;
- if (DebugUtils.isDebugging()) {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(Utils.getCorrectLabel(editPolicy2.getEObject()));
- stringBuilder.append(" is start to move");
- DebugUtils.getLog().debug(stringBuilder.toString());
- }
- editPolicy2.startMoving(req);
- }
- startMovingParts(req, part.getChildren());
- }
- }
- }
-
- @Override
- protected IGroupRequestAdvisor getGroupRequestAdvisor() {
- return GroupRequestAdvisor.getInstance();
- }
-
- /**
- * Override in order to accept correct request
- */
- @Override
- public boolean understandsRequest(Request req) {
- if (req instanceof ChangeBoundsRequest) {
- return true;
- }
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers; + +import org.eclipse.gef.EditPart; +import org.eclipse.gef.EditPolicy; +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.GroupRequestAdvisor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupEditPolicies; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IGroupRequestAdvisor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.AbstractGroupRequest; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.DebugUtils; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils; + +/** + * Implementation of {@link GroupListenerEditPolicy} for Activity Group + * + * @author adaussy + * + */ +public class GroupNotifyingOnMoveEditPolicy extends GroupListenerEditPolicy { + + public GroupNotifyingOnMoveEditPolicy(IContainerNodeDescriptor groupDescriptor) { + super(groupDescriptor); + } + + /** + * Override to : + * -> Put in "Movin state" this edit part and all its children which are Group Framework concern + */ + @Override + public Command getCommand(Request request) { + if (request instanceof ChangeBoundsRequest) { + final ChangeBoundsRequest req = (ChangeBoundsRequest) request; + CompositeCommand cc = new CompositeCommand("GroupNotifyingEditPolicy "); + for (final EditPart part : Utils.getTargetedEditPart(req)) { + ICommand cmd = getGroupRequestAdvisor().notifyGroupFramework(new AbstractGroupRequest((IGraphicalEditPart) getHost(), Utils.getChangeBoundsRequestCopy(req, part), part, getTargetGroupDescriptor(part)) { + + @Override + public GroupRequestType getGroupRequestType() { + return GroupRequestType.MOVE; + } + }); + if (cmd != null && cmd.canExecute()) { + cc.compose(cmd); + } + } + stopMovingPartState(req); + if (cc != null && cc.canExecute()) { + return new ICommandProxy(cc); + } + } + return null; + } + + /** + * Set the art concern by the request to "Moving state" {@link IGroupNotifier#isPartMoving()} + * + * @param req + */ + public void stopMovingPartState(final ChangeBoundsRequest req) { + Iterable<IGraphicalEditPart> targetedEditPart = Utils.getTargetedEditPart(req); + stopMovingParts(targetedEditPart); + } + + /** + * Set all part specify and its descendant to "Moving State" + * + * @param targetedEditPart + */ + protected void stopMovingParts(Iterable<IGraphicalEditPart> targetedEditPart) { + if (targetedEditPart != null) { + for (EditPart part : targetedEditPart) { + EditPolicy editPolicy = part.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY); + if (editPolicy instanceof GroupNotifyingOnMoveEditPolicy) { + GroupNotifyingOnMoveEditPolicy editPolicy2 = (GroupNotifyingOnMoveEditPolicy) editPolicy; + if (DebugUtils.isDebugging()) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(Utils.getCorrectLabel(editPolicy2.getEObject())); + stringBuilder.append(" is stoping to move"); + DebugUtils.getLog().debug(stringBuilder.toString()); + } + editPolicy2.stopMoving(); + } + stopMovingParts(part.getChildren()); + } + } + } + + public void initMovingPartState(final ChangeBoundsRequest req) { + Iterable<IGraphicalEditPart> targetedEditPart = Utils.getTargetedEditPart(req); + startMovingParts(req, targetedEditPart); + } + + protected void startMovingParts(final ChangeBoundsRequest req, Iterable<IGraphicalEditPart> targetedEditPart) { + if (targetedEditPart != null) { + for (final EditPart part : targetedEditPart) { + EditPolicy editPolicy = part.getEditPolicy(IGroupEditPolicies.GROUP_FRAMEWORK_NOTIFYING_ON_MOVE_EDIT_POLICY); + if (editPolicy instanceof GroupNotifyingOnMoveEditPolicy) { + GroupNotifyingOnMoveEditPolicy editPolicy2 = (GroupNotifyingOnMoveEditPolicy) editPolicy; + if (DebugUtils.isDebugging()) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(Utils.getCorrectLabel(editPolicy2.getEObject())); + stringBuilder.append(" is start to move"); + DebugUtils.getLog().debug(stringBuilder.toString()); + } + editPolicy2.startMoving(req); + } + startMovingParts(req, part.getChildren()); + } + } + } + + @Override + protected IGroupRequestAdvisor getGroupRequestAdvisor() { + return GroupRequestAdvisor.getInstance(); + } + + /** + * Override in order to accept correct request + */ + @Override + public boolean understandsRequest(Request req) { + if (req instanceof ChangeBoundsRequest) { + return true; + } + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/IGroupNotifier.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/IGroupNotifier.java index 3691022889d..9f94bff50d6 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/IGroupNotifier.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/editpolicy/notifiers/IGroupNotifier.java @@ -1,106 +1,106 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.EditPolicy;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-
-/**
- * This interface represent an element that can notify to the group framework some changes that may impact Activity groups
- *
- * @author arthur daussy
- *
- */
-public interface IGroupNotifier extends IAdaptable, EditPolicy, Comparable<IGroupNotifier> {
-
- /**
- * Get the {@link EObject} which is the notifier
- *
- * @return
- */
- public EObject getEObject();
-
- /**
- *
- * @return {@link IContainerNodeDescriptor} of the notifier
- */
- public abstract IContainerNodeDescriptor getHostGroupDescriptor();
-
- /**
- *
- * @return {@link IContainerNodeDescriptor} of the target
- */
- public abstract IContainerNodeDescriptor getTargetGroupDescriptor(IAdaptable eObjectAdapter);
-
- /**
- * Get the view of the notifier
- *
- * @return {@link IAdaptable} of the view of the element
- */
- public abstract IAdaptable getAdaptableView();
-
- /**
- * Get the {@link IGraphicalEditPart} host
- * (Sam as than getHost() but with GMF)
- *
- * @return
- */
- public IGraphicalEditPart getHostEditPart();
-
- /**
- * Return true if the element is included on the specified bounds
- * This method should take into account if the node is currently moving or not
- *
- * @param bounds
- * {@link Rectangle} in which the element is tested
- * @return
- */
- public boolean isIncludedIn(Rectangle bounds);
-
- /**
- * Return true if the specified bounds are included in the bounds of the element.
- * This method should take into account if the node is currently moving or not
- *
- * @param bounds
- * @return
- */
- public boolean includes(Rectangle bounds);
-
- /**
- * Notify edit policy that edit part start to move
- * This method represent a state of the edit part
- *
- * @param request
- */
- public void startMoving(ChangeBoundsRequest request);
-
- /**
- * Notify edit policy that edit part stop moving
- * This method represent a state of the edit part
- */
- public void stopMoving();
-
- /**
- * Return true if the part is moving
- *
- * @return
- */
- public boolean isPartMoving();
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.EditPolicy; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; + +/** + * This interface represent an element that can notify to the group framework some changes that may impact Activity groups + * + * @author arthur daussy + * + */ +public interface IGroupNotifier extends IAdaptable, EditPolicy, Comparable<IGroupNotifier> { + + /** + * Get the {@link EObject} which is the notifier + * + * @return + */ + public EObject getEObject(); + + /** + * + * @return {@link IContainerNodeDescriptor} of the notifier + */ + public abstract IContainerNodeDescriptor getHostGroupDescriptor(); + + /** + * + * @return {@link IContainerNodeDescriptor} of the target + */ + public abstract IContainerNodeDescriptor getTargetGroupDescriptor(IAdaptable eObjectAdapter); + + /** + * Get the view of the notifier + * + * @return {@link IAdaptable} of the view of the element + */ + public abstract IAdaptable getAdaptableView(); + + /** + * Get the {@link IGraphicalEditPart} host + * (Sam as than getHost() but with GMF) + * + * @return + */ + public IGraphicalEditPart getHostEditPart(); + + /** + * Return true if the element is included on the specified bounds + * This method should take into account if the node is currently moving or not + * + * @param bounds + * {@link Rectangle} in which the element is tested + * @return + */ + public boolean isIncludedIn(Rectangle bounds); + + /** + * Return true if the specified bounds are included in the bounds of the element. + * This method should take into account if the node is currently moving or not + * + * @param bounds + * @return + */ + public boolean includes(Rectangle bounds); + + /** + * Notify edit policy that edit part start to move + * This method represent a state of the edit part + * + * @param request + */ + public void startMoving(ChangeBoundsRequest request); + + /** + * Notify edit policy that edit part stop moving + * This method represent a state of the edit part + */ + public void stopMoving(); + + /** + * Return true if the part is moving + * + * @return + */ + public boolean isPartMoving(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/functions/FromIGroupNotifierToEObject.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/functions/FromIGroupNotifierToEObject.java index 007e5673959..489e7ca5a6e 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/functions/FromIGroupNotifierToEObject.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/functions/FromIGroupNotifierToEObject.java @@ -1,60 +1,60 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.functions;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier;
-
-import com.google.common.base.Function;
-import com.google.common.collect.Iterables;
-
-/**
- * Transform an IGroupNotifier to an EObject they reference
- *
- * @author adaussy
- *
- */
-public class FromIGroupNotifierToEObject implements Function<IGroupNotifier, EObject> {
-
- FromIGroupNotifierToEObject() {
- }
-
- /**
- * @author adaussy
- *
- */
- private static class SingletonHolder {
-
- public static final FromIGroupNotifierToEObject INSTANCE = new FromIGroupNotifierToEObject();
- }
-
- /**
- * Get the singleton object
- *
- * @return
- */
- public static FromIGroupNotifierToEObject getInstance() {
- return SingletonHolder.INSTANCE;
- }
-
- public static Iterable<EObject> transform(Iterable<IGroupNotifier> from) {
- return Iterables.transform(from, FromIGroupNotifierToEObject.getInstance());
- }
-
- @Override
- public EObject apply(IGroupNotifier from) {
- return from.getEObject();
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.functions; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier; + +import com.google.common.base.Function; +import com.google.common.collect.Iterables; + +/** + * Transform an IGroupNotifier to an EObject they reference + * + * @author adaussy + * + */ +public class FromIGroupNotifierToEObject implements Function<IGroupNotifier, EObject> { + + FromIGroupNotifierToEObject() { + } + + /** + * @author adaussy + * + */ + private static class SingletonHolder { + + public static final FromIGroupNotifierToEObject INSTANCE = new FromIGroupNotifierToEObject(); + } + + /** + * Get the singleton object + * + * @return + */ + public static FromIGroupNotifierToEObject getInstance() { + return SingletonHolder.INSTANCE; + } + + public static Iterable<EObject> transform(Iterable<IGroupNotifier> from) { + return Iterables.transform(from, FromIGroupNotifierToEObject.getInstance()); + } + + @Override + public EObject apply(IGroupNotifier from) { + return from.getEObject(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityContainment.java index df4c42e378f..93770d9c205 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityContainment.java @@ -1,108 +1,108 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityActivityContentCompartmentEditPart;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Node descriptor for an activity
- *
- * @author adaussy
- *
- */
-public class ActivityContainment extends AbstractContainerNodeDescriptor {
-
- private List<EReference> parentReferences;
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getContainerEClass()
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.Literals.ACTIVITY;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getChildrenReferences()
- */
- @Override
- public List<EReference> getChildrenReferences() {
- if (parentReferences == null) {
- parentReferences = new ArrayList<EReference>();
- parentReferences.add(UMLPackage.Literals.ACTIVITY__OWNED_NODE);
- parentReferences.add(UMLPackage.Literals.ACTIVITY__OWNED_GROUP);
- }
- return parentReferences;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getParentReferences()
- */
- @Override
- public List<EReference> getParentReferences() {
- return Collections.emptyList();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getCompartmentPartFromView(org.eclipse.gmf.runtime.diagram
- * .ui.editparts.IGraphicalEditPart)
- */
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- String hint = "" + ActivityActivityContentCompartmentEditPart.VISUAL_ID;
- return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor#getGroupPriority()
- */
- @Override
- public int getGroupPriority() {
- return IGroupPriority.ACTIVITY_PRIORITY;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getParentEOppositeReferences()
- */
- @Override
- public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() {
- return Collections.emptyMap();
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityActivityContentCompartmentEditPart; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Node descriptor for an activity + * + * @author adaussy + * + */ +public class ActivityContainment extends AbstractContainerNodeDescriptor { + + private List<EReference> parentReferences; + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getContainerEClass() + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.Literals.ACTIVITY; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getChildrenReferences() + */ + @Override + public List<EReference> getChildrenReferences() { + if (parentReferences == null) { + parentReferences = new ArrayList<EReference>(); + parentReferences.add(UMLPackage.Literals.ACTIVITY__OWNED_NODE); + parentReferences.add(UMLPackage.Literals.ACTIVITY__OWNED_GROUP); + } + return parentReferences; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getParentReferences() + */ + @Override + public List<EReference> getParentReferences() { + return Collections.emptyList(); + } + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getCompartmentPartFromView(org.eclipse.gmf.runtime.diagram + * .ui.editparts.IGraphicalEditPart) + */ + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + String hint = "" + ActivityActivityContentCompartmentEditPart.VISUAL_ID; + return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor#getGroupPriority() + */ + @Override + public int getGroupPriority() { + return IGroupPriority.ACTIVITY_PRIORITY; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getParentEOppositeReferences() + */ + @Override + public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() { + return Collections.emptyMap(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityNodeContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityNodeContainment.java index 35ab145f939..20bc907ce24 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityNodeContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityNodeContainment.java @@ -1,115 +1,115 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Descriptor for an Activity Node
- *
- * @author adaussy
- *
- */
-public class ActivityNodeContainment extends AbstractContainerNodeDescriptor {
-
- private List<EReference> parentReferences;
-
- private Map<EStructuralFeature, EStructuralFeature> parentOpositeReferences;
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getContainerEClass()
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.Literals.ACTIVITY_NODE;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getChildrenReferences()
- */
- @Override
- public List<EReference> getChildrenReferences() {
- return Collections.emptyList();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getParentReferences()
- */
- @Override
- public List<EReference> getParentReferences() {
- if (parentReferences == null) {
- parentReferences = new ArrayList<EReference>();
- parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__IN_STRUCTURED_NODE);
- parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__ACTIVITY);
- }
- return parentReferences;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getParentEOppositeReferences()
- */
- @Override
- public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() {
- if (parentOpositeReferences == null) {
- parentOpositeReferences = new HashMap<EStructuralFeature, EStructuralFeature>();
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION, UMLPackage.Literals.INTERRUPTIBLE_ACTIVITY_REGION__NODE);
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_PARTITION, UMLPackage.Literals.ACTIVITY_PARTITION__NODE);
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_STRUCTURED_NODE, UMLPackage.Literals.STRUCTURED_ACTIVITY_NODE__NODE);
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__ACTIVITY, UMLPackage.Literals.ACTIVITY__OWNED_NODE);
- }
- return parentOpositeReferences;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getCompartmentPartFromView(org.eclipse.gmf.runtime.diagram
- * .ui.editparts.IGraphicalEditPart)
- */
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- return null;// no compartment for activity node
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor#getGroupPriority()
- */
- @Override
- public int getGroupPriority() {
- return IGroupPriority.ACTIVITY_NODE_PRIORITY;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Descriptor for an Activity Node + * + * @author adaussy + * + */ +public class ActivityNodeContainment extends AbstractContainerNodeDescriptor { + + private List<EReference> parentReferences; + + private Map<EStructuralFeature, EStructuralFeature> parentOpositeReferences; + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getContainerEClass() + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.Literals.ACTIVITY_NODE; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getChildrenReferences() + */ + @Override + public List<EReference> getChildrenReferences() { + return Collections.emptyList(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getParentReferences() + */ + @Override + public List<EReference> getParentReferences() { + if (parentReferences == null) { + parentReferences = new ArrayList<EReference>(); + parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__IN_STRUCTURED_NODE); + parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__ACTIVITY); + } + return parentReferences; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getParentEOppositeReferences() + */ + @Override + public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() { + if (parentOpositeReferences == null) { + parentOpositeReferences = new HashMap<EStructuralFeature, EStructuralFeature>(); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION, UMLPackage.Literals.INTERRUPTIBLE_ACTIVITY_REGION__NODE); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_PARTITION, UMLPackage.Literals.ACTIVITY_PARTITION__NODE); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_STRUCTURED_NODE, UMLPackage.Literals.STRUCTURED_ACTIVITY_NODE__NODE); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__ACTIVITY, UMLPackage.Literals.ACTIVITY__OWNED_NODE); + } + return parentOpositeReferences; + } + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor#getCompartmentPartFromView(org.eclipse.gmf.runtime.diagram + * .ui.editparts.IGraphicalEditPart) + */ + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + return null;// no compartment for activity node + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor#getGroupPriority() + */ + @Override + public int getGroupPriority() { + return IGroupPriority.ACTIVITY_NODE_PRIORITY; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityPartitionContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityPartitionContainment.java index 5e0f8577fb9..648d770eeec 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityPartitionContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ActivityPartitionContainment.java @@ -1,97 +1,97 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionActivityPartitionContentCompartmentEditPart;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * The descriptor for ActivityPartition node used by
- * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point.
- *
- * @author vhemery
- */
-public class ActivityPartitionContainment extends AbstractContainerNodeDescriptor {
-
- private List<EReference> parentReferences;
-
- private Map<EStructuralFeature, EStructuralFeature> parentOpositeReferences;
-
- /**
- * Get the eclass of the model eobject represented by the node
- *
- * @return ActivityPartition eclass
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.eINSTANCE.getActivityPartition();
- }
-
- /**
- * Get the list of references linking the ActivityPartition to children
- * element.
- *
- * @return the references to contained elements
- */
- @Override
- public List<EReference> getChildrenReferences() {
- List<EReference> references = new ArrayList<EReference>(3);
- references.add(UMLPackage.eINSTANCE.getActivityPartition_Subpartition());
- references.add(UMLPackage.eINSTANCE.getElement_OwnedComment());
- return references;
- }
-
- @Override
- public List<EReference> getParentReferences() {
- if (parentReferences == null) {
- parentReferences = new ArrayList<EReference>();
- parentReferences.add(UMLPackage.Literals.ACTIVITY_PARTITION__SUPER_PARTITION);
- parentReferences.add(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY);
- }
- return parentReferences;
- }
-
- @Override
- public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() {
- if (parentOpositeReferences == null) {
- parentOpositeReferences = new HashMap<EStructuralFeature, EStructuralFeature>();
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_PARTITION__SUPER_PARTITION, UMLPackage.Literals.ACTIVITY_PARTITION__SUBPARTITION);
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY, UMLPackage.Literals.ACTIVITY__OWNED_GROUP);
- }
- return parentOpositeReferences;
- }
-
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- String hint = "" + ActivityPartitionActivityPartitionContentCompartmentEditPart.VISUAL_ID;
- return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint);
- }
-
- @Override
- public int getGroupPriority() {
- return IGroupPriority.ACTIVITY_PARTITION_PRIORITY;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionActivityPartitionContentCompartmentEditPart; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * The descriptor for ActivityPartition node used by + * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point. + * + * @author vhemery + */ +public class ActivityPartitionContainment extends AbstractContainerNodeDescriptor { + + private List<EReference> parentReferences; + + private Map<EStructuralFeature, EStructuralFeature> parentOpositeReferences; + + /** + * Get the eclass of the model eobject represented by the node + * + * @return ActivityPartition eclass + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.eINSTANCE.getActivityPartition(); + } + + /** + * Get the list of references linking the ActivityPartition to children + * element. + * + * @return the references to contained elements + */ + @Override + public List<EReference> getChildrenReferences() { + List<EReference> references = new ArrayList<EReference>(3); + references.add(UMLPackage.eINSTANCE.getActivityPartition_Subpartition()); + references.add(UMLPackage.eINSTANCE.getElement_OwnedComment()); + return references; + } + + @Override + public List<EReference> getParentReferences() { + if (parentReferences == null) { + parentReferences = new ArrayList<EReference>(); + parentReferences.add(UMLPackage.Literals.ACTIVITY_PARTITION__SUPER_PARTITION); + parentReferences.add(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY); + } + return parentReferences; + } + + @Override + public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() { + if (parentOpositeReferences == null) { + parentOpositeReferences = new HashMap<EStructuralFeature, EStructuralFeature>(); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_PARTITION__SUPER_PARTITION, UMLPackage.Literals.ACTIVITY_PARTITION__SUBPARTITION); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY, UMLPackage.Literals.ACTIVITY__OWNED_GROUP); + } + return parentOpositeReferences; + } + + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + String hint = "" + ActivityPartitionActivityPartitionContentCompartmentEditPart.VISUAL_ID; + return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint); + } + + @Override + public int getGroupPriority() { + return IGroupPriority.ACTIVITY_PARTITION_PRIORITY; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ConditionalNodeContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ConditionalNodeContainment.java index 252e164d661..82adcebcad8 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ConditionalNodeContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ConditionalNodeContainment.java @@ -1,45 +1,45 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ConditionalNodeStructuredActivityNodeContentCompartmentEditPart;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * The descriptor for ConditionalNode node used by
- * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point.
- *
- * @author vhemery
- */
-public class ConditionalNodeContainment extends StructuredActivityNodeContainment {
-
- /**
- * Get the eclass of the model eobject represented by the node
- *
- * @return ConditionalNode eclass
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.eINSTANCE.getConditionalNode();
- }
-
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- String hint = "" + ConditionalNodeStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID;
- return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ConditionalNodeStructuredActivityNodeContentCompartmentEditPart; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * The descriptor for ConditionalNode node used by + * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point. + * + * @author vhemery + */ +public class ConditionalNodeContainment extends StructuredActivityNodeContainment { + + /** + * Get the eclass of the model eobject represented by the node + * + * @return ConditionalNode eclass + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.eINSTANCE.getConditionalNode(); + } + + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + String hint = "" + ConditionalNodeStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID; + return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ExpansionRegionContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ExpansionRegionContainment.java index b348b9f6204..98d340da5fb 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ExpansionRegionContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/ExpansionRegionContainment.java @@ -1,45 +1,45 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ExpansionRegionStructuredActivityNodeContentCompartmentEditPart;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * The descriptor for ExpansionRegion node used by
- * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point.
- *
- * @author vhemery
- */
-public class ExpansionRegionContainment extends StructuredActivityNodeContainment {
-
- /**
- * Get the eclass of the model eobject represented by the node
- *
- * @return ExpansionRegion eclass
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.eINSTANCE.getExpansionRegion();
- }
-
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- String hint = "" + ExpansionRegionStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID;
- return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ExpansionRegionStructuredActivityNodeContentCompartmentEditPart; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * The descriptor for ExpansionRegion node used by + * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point. + * + * @author vhemery + */ +public class ExpansionRegionContainment extends StructuredActivityNodeContainment { + + /** + * Get the eclass of the model eobject represented by the node + * + * @return ExpansionRegion eclass + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.eINSTANCE.getExpansionRegion(); + } + + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + String hint = "" + ExpansionRegionStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID; + return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/IGroupPriority.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/IGroupPriority.java index 12896eda882..3134101ba52 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/IGroupPriority.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/IGroupPriority.java @@ -1,34 +1,34 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-/**
- * Define the priority of groups to be a graphicla parent of a child
- *
- * @author adaussy
- *
- */
-public interface IGroupPriority {
-
- public static int STRUCTURED_ACTIVITY_NODE_PRIORITY = 100;
-
- public static int ACTIVITY_PARTITION_PRIORITY = 90;
-
- public static int INTERRUPTIBLE_REGION_PRIORITY = 80;
-
- public static int ACTIVITY_PRIORITY = 50;
-
- public static int ACTIVITY_NODE_PRIORITY = -1;
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +/** + * Define the priority of groups to be a graphicla parent of a child + * + * @author adaussy + * + */ +public interface IGroupPriority { + + public static int STRUCTURED_ACTIVITY_NODE_PRIORITY = 100; + + public static int ACTIVITY_PARTITION_PRIORITY = 90; + + public static int INTERRUPTIBLE_REGION_PRIORITY = 80; + + public static int ACTIVITY_PRIORITY = 50; + + public static int ACTIVITY_NODE_PRIORITY = -1; +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/InterruptibleActivityRegionContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/InterruptibleActivityRegionContainment.java index 9515f31924d..84005d1bc4c 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/InterruptibleActivityRegionContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/InterruptibleActivityRegionContainment.java @@ -1,85 +1,85 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * The descriptor for InterruptibleActivityRegion node used by
- * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point.
- *
- * @author vhemery
- */
-public class InterruptibleActivityRegionContainment extends AbstractContainerNodeDescriptor {
-
- private Map<EStructuralFeature, EStructuralFeature> parentOpositeReferences;
-
- /**
- * Get the eclass of the model eobject represented by the node
- *
- * @return InterruptibleActivityRegion eclass
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.eINSTANCE.getInterruptibleActivityRegion();
- }
-
- /**
- * Get the list of references linking the InterruptibleActivityRegion to
- * children element.
- *
- * @return the references to contained elements
- */
- @Override
- public List<EReference> getChildrenReferences() {
- return Collections.emptyList();
- }
-
- @Override
- public List<EReference> getParentReferences() {
- return Collections.singletonList(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY);
- }
-
- @Override
- public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() {
- if (parentOpositeReferences == null) {
- parentOpositeReferences = new HashMap<EStructuralFeature, EStructuralFeature>();
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY, UMLPackage.Literals.ACTIVITY__OWNED_GROUP);
- }
- return parentOpositeReferences;
- }
-
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- String hint = "" + InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart.VISUAL_ID;
- return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint);
- }
-
- @Override
- public int getGroupPriority() {
- return IGroupPriority.INTERRUPTIBLE_REGION_PRIORITY;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * The descriptor for InterruptibleActivityRegion node used by + * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point. + * + * @author vhemery + */ +public class InterruptibleActivityRegionContainment extends AbstractContainerNodeDescriptor { + + private Map<EStructuralFeature, EStructuralFeature> parentOpositeReferences; + + /** + * Get the eclass of the model eobject represented by the node + * + * @return InterruptibleActivityRegion eclass + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.eINSTANCE.getInterruptibleActivityRegion(); + } + + /** + * Get the list of references linking the InterruptibleActivityRegion to + * children element. + * + * @return the references to contained elements + */ + @Override + public List<EReference> getChildrenReferences() { + return Collections.emptyList(); + } + + @Override + public List<EReference> getParentReferences() { + return Collections.singletonList(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY); + } + + @Override + public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() { + if (parentOpositeReferences == null) { + parentOpositeReferences = new HashMap<EStructuralFeature, EStructuralFeature>(); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY, UMLPackage.Literals.ACTIVITY__OWNED_GROUP); + } + return parentOpositeReferences; + } + + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + String hint = "" + InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart.VISUAL_ID; + return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint); + } + + @Override + public int getGroupPriority() { + return IGroupPriority.INTERRUPTIBLE_REGION_PRIORITY; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/LoopNodeContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/LoopNodeContainment.java index b309d20cdfa..2d888dffb8a 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/LoopNodeContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/LoopNodeContainment.java @@ -1,45 +1,45 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.LoopNodeStructuredActivityNodeContentCompartmentEditPart;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * The descriptor for LoopNode node used by
- * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point.
- *
- * @author vhemery
- */
-public class LoopNodeContainment extends StructuredActivityNodeContainment {
-
- /**
- * Get the eclass of the model eobject represented by the node
- *
- * @return LoopNode eclass
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.eINSTANCE.getLoopNode();
- }
-
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- String hint = "" + LoopNodeStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID;
- return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.LoopNodeStructuredActivityNodeContentCompartmentEditPart; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * The descriptor for LoopNode node used by + * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point. + * + * @author vhemery + */ +public class LoopNodeContainment extends StructuredActivityNodeContainment { + + /** + * Get the eclass of the model eobject represented by the node + * + * @return LoopNode eclass + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.eINSTANCE.getLoopNode(); + } + + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + String hint = "" + LoopNodeStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID; + return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/SequenceNodeContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/SequenceNodeContainment.java index 5afef82d41e..a4a84d1313b 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/SequenceNodeContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/SequenceNodeContainment.java @@ -1,45 +1,45 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.SequenceNodeStructuredActivityNodeContentCompartmentEditPart;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * The descriptor for SequenceNode node used by
- * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point.
- *
- * @author vhemery
- */
-public class SequenceNodeContainment extends StructuredActivityNodeContainment {
-
- /**
- * Get the eclass of the model eobject represented by the node
- *
- * @return SequenceNode eclass
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.eINSTANCE.getSequenceNode();
- }
-
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- String hint = "" + SequenceNodeStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID;
- return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.SequenceNodeStructuredActivityNodeContentCompartmentEditPart; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * The descriptor for SequenceNode node used by + * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point. + * + * @author vhemery + */ +public class SequenceNodeContainment extends StructuredActivityNodeContainment { + + /** + * Get the eclass of the model eobject represented by the node + * + * @return SequenceNode eclass + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.eINSTANCE.getSequenceNode(); + } + + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + String hint = "" + SequenceNodeStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID; + return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/StructuredActivityNodeContainment.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/StructuredActivityNodeContainment.java index f76b724dfbe..1441e17811d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/StructuredActivityNodeContainment.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/groupcontainment/StructuredActivityNodeContainment.java @@ -1,104 +1,104 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.StructuredActivityNodeStructuredActivityNodeContentCompartmentEditPart;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * The descriptor for StructuredActivityNode node used by
- * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point.
- *
- * @author vhemery
- */
-public class StructuredActivityNodeContainment extends AbstractContainerNodeDescriptor {
-
- private ArrayList<EReference> childrenReferences;
-
- private ArrayList<EReference> parentReferences;
-
- private Map<EStructuralFeature, EStructuralFeature> parentOpositeReferences;
-
- /**
- * Get the eclass of the model eobject represented by the node
- *
- * @return StructuredActivityNode eclass
- */
- @Override
- public EClass getContainerEClass() {
- return UMLPackage.eINSTANCE.getStructuredActivityNode();
- }
-
- /**
- * Get the list of references linking the StructuredActivityNode to children
- * element.
- *
- * @return the references to contained elements
- */
- @Override
- public List<EReference> getChildrenReferences() {
- if (childrenReferences == null) {
- childrenReferences = new ArrayList<EReference>(2);
- childrenReferences.add(UMLPackage.eINSTANCE.getStructuredActivityNode_Node());
- childrenReferences.add(UMLPackage.eINSTANCE.getStructuredActivityNode_Edge());
- }
- return childrenReferences;
- }
-
- @Override
- public List<EReference> getParentReferences() {
- if (parentReferences == null) {
- parentReferences = new ArrayList<EReference>();
- parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION);
- parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__IN_PARTITION);
- parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__IN_STRUCTURED_NODE);
- parentReferences.add(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY);
- }
- return parentReferences;
- }
-
- @Override
- public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() {
- if (parentOpositeReferences == null) {
- parentOpositeReferences = new HashMap<EStructuralFeature, EStructuralFeature>();
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION, UMLPackage.Literals.INTERRUPTIBLE_ACTIVITY_REGION__NODE);
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_PARTITION, UMLPackage.Literals.ACTIVITY_PARTITION__NODE);
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_STRUCTURED_NODE, UMLPackage.Literals.STRUCTURED_ACTIVITY_NODE__NODE);
- parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__ACTIVITY, UMLPackage.Literals.ACTIVITY__OWNED_NODE);
- }
- return parentOpositeReferences;
- }
-
- @Override
- public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) {
- String hint = "" + StructuredActivityNodeStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID;
- return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint);
- }
-
- @Override
- public int getGroupPriority() {
- return IGroupPriority.STRUCTURED_ACTIVITY_NODE_PRIORITY;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.groupcontainment; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.AbstractContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.StructuredActivityNodeStructuredActivityNodeContentCompartmentEditPart; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * The descriptor for StructuredActivityNode node used by + * org.eclipse.papyrus.uml.diagram.common.groups.groupcontainment extension point. + * + * @author vhemery + */ +public class StructuredActivityNodeContainment extends AbstractContainerNodeDescriptor { + + private ArrayList<EReference> childrenReferences; + + private ArrayList<EReference> parentReferences; + + private Map<EStructuralFeature, EStructuralFeature> parentOpositeReferences; + + /** + * Get the eclass of the model eobject represented by the node + * + * @return StructuredActivityNode eclass + */ + @Override + public EClass getContainerEClass() { + return UMLPackage.eINSTANCE.getStructuredActivityNode(); + } + + /** + * Get the list of references linking the StructuredActivityNode to children + * element. + * + * @return the references to contained elements + */ + @Override + public List<EReference> getChildrenReferences() { + if (childrenReferences == null) { + childrenReferences = new ArrayList<EReference>(2); + childrenReferences.add(UMLPackage.eINSTANCE.getStructuredActivityNode_Node()); + childrenReferences.add(UMLPackage.eINSTANCE.getStructuredActivityNode_Edge()); + } + return childrenReferences; + } + + @Override + public List<EReference> getParentReferences() { + if (parentReferences == null) { + parentReferences = new ArrayList<EReference>(); + parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION); + parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__IN_PARTITION); + parentReferences.add(UMLPackage.Literals.ACTIVITY_NODE__IN_STRUCTURED_NODE); + parentReferences.add(UMLPackage.Literals.ACTIVITY_GROUP__IN_ACTIVITY); + } + return parentReferences; + } + + @Override + public Map<EStructuralFeature, EStructuralFeature> getParentEOppositeReferences() { + if (parentOpositeReferences == null) { + parentOpositeReferences = new HashMap<EStructuralFeature, EStructuralFeature>(); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION, UMLPackage.Literals.INTERRUPTIBLE_ACTIVITY_REGION__NODE); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_PARTITION, UMLPackage.Literals.ACTIVITY_PARTITION__NODE); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__IN_STRUCTURED_NODE, UMLPackage.Literals.STRUCTURED_ACTIVITY_NODE__NODE); + parentOpositeReferences.put(UMLPackage.Literals.ACTIVITY_NODE__ACTIVITY, UMLPackage.Literals.ACTIVITY__OWNED_NODE); + } + return parentOpositeReferences; + } + + @Override + public IGraphicalEditPart getCompartmentPartFromView(IGraphicalEditPart editpart) { + String hint = "" + StructuredActivityNodeStructuredActivityNodeContentCompartmentEditPart.VISUAL_ID; + return ((GraphicalEditPart) editpart).getChildBySemanticHintOnPrimaryView(hint); + } + + @Override + public int getGroupPriority() { + return IGroupPriority.STRUCTURED_ACTIVITY_NODE_PRIORITY; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/AncestorFilter.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/AncestorFilter.java index c2e500055a2..bef21a3a18a 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/AncestorFilter.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/AncestorFilter.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-
-import com.google.common.base.Predicate;
-
-/**
- * Filter all ancestors
- *
- * @author arthur daussy
- *
- */
-public class AncestorFilter implements Predicate<EObject> {
-
- private Iterable<? extends EObject> initialCollection;
-
- public AncestorFilter(Iterable<? extends EObject> initialCollection) {
- super();
- this.initialCollection = initialCollection;
- }
-
- @Override
- public boolean apply(EObject input) {
- for (EObject target : initialCollection) {
- if (target == input) {
- continue;
- }
- if (EcoreUtil.isAncestor(target, input)) {
- return false;
- }
- }
- return true;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.util.EcoreUtil; + +import com.google.common.base.Predicate; + +/** + * Filter all ancestors + * + * @author arthur daussy + * + */ +public class AncestorFilter implements Predicate<EObject> { + + private Iterable<? extends EObject> initialCollection; + + public AncestorFilter(Iterable<? extends EObject> initialCollection) { + super(); + this.initialCollection = initialCollection; + } + + @Override + public boolean apply(EObject input) { + for (EObject target : initialCollection) { + if (target == input) { + continue; + } + if (EcoreUtil.isAncestor(target, input)) { + return false; + } + } + return true; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/DescendantsFilter.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/DescendantsFilter.java index 89ffded6c4f..088cd2ce9da 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/DescendantsFilter.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/DescendantsFilter.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-
-import com.google.common.base.Predicate;
-
-/**
- * Same as {@link EcoreUtil#filterDescendants(java.util.Collection)}
- *
- * @author arthur daussy
- *
- */
-public class DescendantsFilter implements Predicate<EObject> {
-
- private Iterable<? extends EObject> initialCollection;
-
- public DescendantsFilter(Iterable<? extends EObject> initialCollection) {
- super();
- this.initialCollection = initialCollection;
- }
-
- @Override
- public boolean apply(EObject input) {
- for (EObject target : initialCollection) {
- if (target == input) {
- continue;
- }
- if (EcoreUtil.isAncestor(input, target)) {
- return false;
- }
- }
- return true;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.util.EcoreUtil; + +import com.google.common.base.Predicate; + +/** + * Same as {@link EcoreUtil#filterDescendants(java.util.Collection)} + * + * @author arthur daussy + * + */ +public class DescendantsFilter implements Predicate<EObject> { + + private Iterable<? extends EObject> initialCollection; + + public DescendantsFilter(Iterable<? extends EObject> initialCollection) { + super(); + this.initialCollection = initialCollection; + } + + @Override + public boolean apply(EObject input) { + for (EObject target : initialCollection) { + if (target == input) { + continue; + } + if (EcoreUtil.isAncestor(input, target)) { + return false; + } + } + return true; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/DescendantsFilterIGroupNotifier.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/DescendantsFilterIGroupNotifier.java index 53e5745c98f..d600930e7cb 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/DescendantsFilterIGroupNotifier.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/DescendantsFilterIGroupNotifier.java @@ -1,55 +1,55 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier;
-
-import com.google.common.base.Predicate;
-
-/**
- * Same as {@link EcoreUtil#filterDescendants(java.util.Collection)}
- *
- * @author arthur daussy
- *
- */
-public class DescendantsFilterIGroupNotifier implements Predicate<IGroupNotifier> {
-
- private Iterable<? extends IGroupNotifier> initialCollection;
-
- public DescendantsFilterIGroupNotifier(Iterable<? extends IGroupNotifier> initialCollection) {
- super();
- this.initialCollection = initialCollection;
- }
-
- @Override
- public boolean apply(IGroupNotifier input) {
- for (IGroupNotifier target : initialCollection) {
- EObject targetEObject = target.getEObject();
- EObject inputEObject = input.getEObject();
- if (targetEObject == inputEObject) {
- continue;
- }
- if (inputEObject == null) {
- return false;
- }
- if (EcoreUtil.isAncestor(inputEObject, targetEObject)) {
- return false;
- }
- }
- return true;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier; + +import com.google.common.base.Predicate; + +/** + * Same as {@link EcoreUtil#filterDescendants(java.util.Collection)} + * + * @author arthur daussy + * + */ +public class DescendantsFilterIGroupNotifier implements Predicate<IGroupNotifier> { + + private Iterable<? extends IGroupNotifier> initialCollection; + + public DescendantsFilterIGroupNotifier(Iterable<? extends IGroupNotifier> initialCollection) { + super(); + this.initialCollection = initialCollection; + } + + @Override + public boolean apply(IGroupNotifier input) { + for (IGroupNotifier target : initialCollection) { + EObject targetEObject = target.getEObject(); + EObject inputEObject = input.getEObject(); + if (targetEObject == inputEObject) { + continue; + } + if (inputEObject == null) { + return false; + } + if (EcoreUtil.isAncestor(inputEObject, targetEObject)) { + return false; + } + } + return true; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/SameContainerFilter.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/SameContainerFilter.java index fc7ff93c8a0..2be158462ef 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/SameContainerFilter.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/predicates/SameContainerFilter.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates;
-
-import org.eclipse.uml2.uml.Element;
-
-import com.google.common.base.Predicate;
-
-/**
- * filter which return true or element which have the same container
- *
- * @author arthur
- *
- */
-public class SameContainerFilter implements Predicate<Element> {
-
- private Element parent;
-
- private Element container;
-
- public SameContainerFilter(Element parent) {
- super();
- this.parent = parent;
- }
-
- @Override
- public boolean apply(Element arg0) {
- return getContainer() != null && getContainer().equals(arg0.getOwner());
- }
-
- private Element getContainer() {
- if (container == null) {
- container = parent.getOwner();
- }
- return container;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates; + +import org.eclipse.uml2.uml.Element; + +import com.google.common.base.Predicate; + +/** + * filter which return true or element which have the same container + * + * @author arthur + * + */ +public class SameContainerFilter implements Predicate<Element> { + + private Element parent; + + private Element container; + + public SameContainerFilter(Element parent) { + super(); + this.parent = parent; + } + + @Override + public boolean apply(Element arg0) { + return getContainer() != null && getContainer().equals(arg0.getOwner()); + } + + private Element getContainer() { + if (container == null) { + container = parent.getOwner(); + } + return container; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/preferences/OpacityFactoryHelper.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/preferences/OpacityFactoryHelper.java index 8b9bf99700d..707ad6e2ff8 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/preferences/OpacityFactoryHelper.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/preferences/OpacityFactoryHelper.java @@ -1,82 +1,82 @@ -/*****************************************************************************
- * Copyright (c) 2011 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.preferences;
-
-import org.eclipse.draw2d.Shape;
-import org.eclipse.jface.dialogs.DialogPage;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * Factory Helper used to set the opacity setting on groups ( setAlpha , listenner, preferences etc...)
- *
- * @author adaussy
- *
- */
-public class OpacityFactoryHelper {
-
- /**
- * Get the preference group to set the opqcity
- *
- * @param parent
- * @param key
- * @param dialogPage
- * @param preferenceName
- * @return
- */
- static public OpacityGroup getOpacityGroup(Composite parent, String key, DialogPage dialogPage, String preferenceName) {
- return new OpacityGroup(parent, key, dialogPage, preferenceName);
- }
-
- /**
- * Init the opacity preferences of a figure
- *
- * @param preferenceName
- * Name of the preferences which point to the alpha preference
- * @param store
- * Preference Store
- * @param figure
- * Figure on which the alpha setting has to be made
- */
- static public void initOpacityPreferences(final String preferenceName, final IPreferenceStore store, final Shape figure) {
- Integer defaultAlpha = getStoredValueOfOpacity(preferenceName, store);
- figure.setAlpha(defaultAlpha);
- store.addPropertyChangeListener(new IPropertyChangeListener() {
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (preferenceName.equals(event.getProperty())) {
- if (figure != null) {
- figure.setAlpha(store.getInt(preferenceName));
- }
- }
- }
- });
- }
-
- /**
- * Get the store value of the alpha setting
- *
- * @param preferenceName
- * name of the preference
- * @param store
- * Preference store
- * @return
- */
- static public Integer getStoredValueOfOpacity(String preferenceName, IPreferenceStore store) {
- return new Integer(store.getInt(preferenceName));
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.preferences; + +import org.eclipse.draw2d.Shape; +import org.eclipse.jface.dialogs.DialogPage; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.swt.widgets.Composite; + +/** + * Factory Helper used to set the opacity setting on groups ( setAlpha , listenner, preferences etc...) + * + * @author adaussy + * + */ +public class OpacityFactoryHelper { + + /** + * Get the preference group to set the opqcity + * + * @param parent + * @param key + * @param dialogPage + * @param preferenceName + * @return + */ + static public OpacityGroup getOpacityGroup(Composite parent, String key, DialogPage dialogPage, String preferenceName) { + return new OpacityGroup(parent, key, dialogPage, preferenceName); + } + + /** + * Init the opacity preferences of a figure + * + * @param preferenceName + * Name of the preferences which point to the alpha preference + * @param store + * Preference Store + * @param figure + * Figure on which the alpha setting has to be made + */ + static public void initOpacityPreferences(final String preferenceName, final IPreferenceStore store, final Shape figure) { + Integer defaultAlpha = getStoredValueOfOpacity(preferenceName, store); + figure.setAlpha(defaultAlpha); + store.addPropertyChangeListener(new IPropertyChangeListener() { + + @Override + public void propertyChange(PropertyChangeEvent event) { + if (preferenceName.equals(event.getProperty())) { + if (figure != null) { + figure.setAlpha(store.getInt(preferenceName)); + } + } + } + }); + } + + /** + * Get the store value of the alpha setting + * + * @param preferenceName + * name of the preference + * @param store + * Preference store + * @return + */ + static public Integer getStoredValueOfOpacity(String preferenceName, IPreferenceStore store) { + return new Integer(store.getInt(preferenceName)); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/preferences/OpacityGroup.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/preferences/OpacityGroup.java index 07e32d7c3fb..699cf7ec9fc 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/preferences/OpacityGroup.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/preferences/OpacityGroup.java @@ -1,63 +1,63 @@ -/*****************************************************************************
- * Copyright (c) 2011 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.preferences;
-
-import org.eclipse.jface.dialogs.DialogPage;
-import org.eclipse.jface.preference.ScaleFieldEditor;
-import org.eclipse.papyrus.infra.gmfdiag.preferences.ui.AbstractGroup;
-import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-
-/**
- * Group use to set the opacity of a compartment of a group
- *
- * @author adaussy
- *
- */
-public class OpacityGroup extends AbstractGroup {
-
- /**
- * Name of the preferance to set
- */
- protected String preferenceName;
-
- public OpacityGroup(Composite parent, String key, DialogPage dialogPage, String preferenceName) {
- super(parent, key, dialogPage);
- this.preferenceName = preferenceName;
- createContent(parent);
- }
-
- /**
- * Creates the content.
- *
- * @param parent
- * the parent
- */
- public void createContent(Composite parent) {
- Group visibilityGroup = new Group(parent, SWT.SCROLL_PAGE);
- /*
- * TODO Refactor layout (help component at the end of the line)
- */
- visibilityGroup.setLayout(new GridLayout());
- visibilityGroup.setText("Opacity of the compartment");
- ScaleFieldEditor alphaEditor = new ScaleFieldEditor(preferenceName, "Opacity", visibilityGroup, 0, 255, 5, 20);
- alphaEditor.setPage(dialogPage);
- addFieldEditor(alphaEditor);
- HelpComponentFactory.createHelpComponent(visibilityGroup, new FormToolkit(parent.getDisplay()), "Set to min to make the compartment totally transparent");
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.preferences; + +import org.eclipse.jface.dialogs.DialogPage; +import org.eclipse.jface.preference.ScaleFieldEditor; +import org.eclipse.papyrus.infra.gmfdiag.preferences.ui.AbstractGroup; +import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Group; +import org.eclipse.ui.forms.widgets.FormToolkit; + +/** + * Group use to set the opacity of a compartment of a group + * + * @author adaussy + * + */ +public class OpacityGroup extends AbstractGroup { + + /** + * Name of the preferance to set + */ + protected String preferenceName; + + public OpacityGroup(Composite parent, String key, DialogPage dialogPage, String preferenceName) { + super(parent, key, dialogPage); + this.preferenceName = preferenceName; + createContent(parent); + } + + /** + * Creates the content. + * + * @param parent + * the parent + */ + public void createContent(Composite parent) { + Group visibilityGroup = new Group(parent, SWT.SCROLL_PAGE); + /* + * TODO Refactor layout (help component at the end of the line) + */ + visibilityGroup.setLayout(new GridLayout()); + visibilityGroup.setText("Opacity of the compartment"); + ScaleFieldEditor alphaEditor = new ScaleFieldEditor(preferenceName, "Opacity", visibilityGroup, 0, 255, 5, 20); + alphaEditor.setPage(dialogPage); + addFieldEditor(alphaEditor); + HelpComponentFactory.createHelpComponent(visibilityGroup, new FormToolkit(parent.getDisplay()), "Set to min to make the compartment totally transparent"); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/AbstractGroupRequest.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/AbstractGroupRequest.java index bdbc0f7117d..ad53ece915b 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/AbstractGroupRequest.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/AbstractGroupRequest.java @@ -1,141 +1,141 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.gef.Request;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils;
-
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-
-public abstract class AbstractGroupRequest extends Request implements IGroupRequest {
-
- protected IGraphicalEditPart host;
-
- protected Request request;
-
- protected IAdaptable target;
-
- protected IContainerNodeDescriptor nodeDescriptor;
-
- /**
- * Map to link to a parent with a EReference
- */
- private Multimap<EReference, EObject> eParentRefenceMap;
-
- /**
- * Map to link to a child with {@link EReference}
- */
- private Multimap<EReference, EObject> eChildrenRefenceMap;
-
- public AbstractGroupRequest(IGraphicalEditPart host, Request request, IAdaptable target, IContainerNodeDescriptor nodeDescriptor) {
- super();
- this.host = host;
- this.request = request;
- this.target = target;
- this.nodeDescriptor = nodeDescriptor;
- }
-
- @Override
- public IGraphicalEditPart getHostRequest() {
- return host;
- }
-
- @Override
- public Request getInitialRequest() {
- return request;
- }
-
- @Override
- public IContainerNodeDescriptor getNodeDescpitor() {
- return nodeDescriptor;
- }
-
- @Override
- public IAdaptable getTargetElement() {
- return target;
- }
-
- @Override
- public String getLabel() {
- StringBuilder builder = new StringBuilder(" IGroupRequest :\n \t Request : ").append(request).append("\n \t Target : ");
- Object eObject = getTargetElement().getAdapter(EObject.class);
- if (eObject instanceof EObject) {
- return "";
- }
- builder.append(Utils.getCorrectLabel(eObject));
- builder.append("\n \t Host :").append(Utils.getCorrectLabel(getHostRequest()));
- builder.append("\n \t Type :").append(getGroupRequestType());
- return builder.toString();
- }
-
- // /**
- // * Get the absolute bounds of the initial target.
- // * For example for changeBoudnsRequest in group. This will represent the bounds of the group after the bounds have changed
- // *
- // * @return
- // */
- // public Rectangle getIntialTargetAbsoluteBounds() {
- // @SuppressWarnings("rawtypes")
- // Map metadata = request.getExtendedData();
- // if(metadata != null) {
- // Object bounds_ = metadata.get((Object)INITIAL_TARGET_REQUEST_NEW_BOUNDS);
- // if(bounds_ instanceof Rectangle) {
- // Rectangle bounds = (Rectangle)bounds_;
- // return bounds;
- // }
- // }
- // return null;
- // }
- // /**
- // * Set the absolute bounds of the initial target.
- // * For example for changeBoudnsRequest in group. This will represent the bounds of the group after the bounds have changed
- // *
- // * @return
- // */
- //
- // public void setIntialTargetAbsoluteBounds(Rectangle bounds) {
- // Map metadata = request.getExtendedData();
- // if(bounds == null) {
- // return;
- // }
- // if(metadata != null) {
- // Object oldsBounds = metadata.put((Object)INITIAL_TARGET_REQUEST_NEW_BOUNDS, bounds);
- // if(DebugUtils.isDebugging()) {
- // DebugUtils.getLog().debug("The absolute bounds of " + Utils.getCorrectLabel(getTargetElement()) + " went from " + oldsBounds + " to " + bounds);
- // }
- // }
- // }
- @Override
- public Multimap<EReference, EObject> getParentEReferenceMap() {
- if (eParentRefenceMap == null) {
- eParentRefenceMap = ArrayListMultimap.create();
- }
- return this.eParentRefenceMap;
- }
-
- @Override
- public Multimap<EReference, EObject> getChildrenEReferenceMap() {
- if (eChildrenRefenceMap == null) {
- eChildrenRefenceMap = ArrayListMultimap.create();
- }
- return this.eChildrenRefenceMap;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.gef.Request; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.Utils; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; + +public abstract class AbstractGroupRequest extends Request implements IGroupRequest { + + protected IGraphicalEditPart host; + + protected Request request; + + protected IAdaptable target; + + protected IContainerNodeDescriptor nodeDescriptor; + + /** + * Map to link to a parent with a EReference + */ + private Multimap<EReference, EObject> eParentRefenceMap; + + /** + * Map to link to a child with {@link EReference} + */ + private Multimap<EReference, EObject> eChildrenRefenceMap; + + public AbstractGroupRequest(IGraphicalEditPart host, Request request, IAdaptable target, IContainerNodeDescriptor nodeDescriptor) { + super(); + this.host = host; + this.request = request; + this.target = target; + this.nodeDescriptor = nodeDescriptor; + } + + @Override + public IGraphicalEditPart getHostRequest() { + return host; + } + + @Override + public Request getInitialRequest() { + return request; + } + + @Override + public IContainerNodeDescriptor getNodeDescpitor() { + return nodeDescriptor; + } + + @Override + public IAdaptable getTargetElement() { + return target; + } + + @Override + public String getLabel() { + StringBuilder builder = new StringBuilder(" IGroupRequest :\n \t Request : ").append(request).append("\n \t Target : "); + Object eObject = getTargetElement().getAdapter(EObject.class); + if (eObject instanceof EObject) { + return ""; + } + builder.append(Utils.getCorrectLabel(eObject)); + builder.append("\n \t Host :").append(Utils.getCorrectLabel(getHostRequest())); + builder.append("\n \t Type :").append(getGroupRequestType()); + return builder.toString(); + } + + // /** + // * Get the absolute bounds of the initial target. + // * For example for changeBoudnsRequest in group. This will represent the bounds of the group after the bounds have changed + // * + // * @return + // */ + // public Rectangle getIntialTargetAbsoluteBounds() { + // @SuppressWarnings("rawtypes") + // Map metadata = request.getExtendedData(); + // if(metadata != null) { + // Object bounds_ = metadata.get((Object)INITIAL_TARGET_REQUEST_NEW_BOUNDS); + // if(bounds_ instanceof Rectangle) { + // Rectangle bounds = (Rectangle)bounds_; + // return bounds; + // } + // } + // return null; + // } + // /** + // * Set the absolute bounds of the initial target. + // * For example for changeBoudnsRequest in group. This will represent the bounds of the group after the bounds have changed + // * + // * @return + // */ + // + // public void setIntialTargetAbsoluteBounds(Rectangle bounds) { + // Map metadata = request.getExtendedData(); + // if(bounds == null) { + // return; + // } + // if(metadata != null) { + // Object oldsBounds = metadata.put((Object)INITIAL_TARGET_REQUEST_NEW_BOUNDS, bounds); + // if(DebugUtils.isDebugging()) { + // DebugUtils.getLog().debug("The absolute bounds of " + Utils.getCorrectLabel(getTargetElement()) + " went from " + oldsBounds + " to " + bounds); + // } + // } + // } + @Override + public Multimap<EReference, EObject> getParentEReferenceMap() { + if (eParentRefenceMap == null) { + eParentRefenceMap = ArrayListMultimap.create(); + } + return this.eParentRefenceMap; + } + + @Override + public Multimap<EReference, EObject> getChildrenEReferenceMap() { + if (eChildrenRefenceMap == null) { + eChildrenRefenceMap = ArrayListMultimap.create(); + } + return this.eChildrenRefenceMap; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/DeferredMoveRequest.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/DeferredMoveRequest.java index ca54db2811a..720809eb71c 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/DeferredMoveRequest.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/DeferredMoveRequest.java @@ -1,112 +1,112 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gmf.runtime.emf.type.core.requests.MoveRequest;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.DebugUtils;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-
-public class DeferredMoveRequest extends MoveRequest {
-
- /**
- * IAdaptable of the container
- */
- private IAdaptable targetContainer;
-
- /**
- * {@link IAdaptable} of the element to move
- */
- private Map<IAdaptable, Object> iAdaptableToMove;
-
- /**
- * {@link EObject= to move
- */
- private Map<EObject, Object> elementsToMove;
-
- /**
- * Class used to adapt the IAdaptable (for example {@link EObject} or {@link View}
- */
- private Class<? extends EObject> classToCast;
-
- /**
- *
- * @param editingDomain
- * @param targetContainer
- * @param elementsToMove
- */
- public DeferredMoveRequest(TransactionalEditingDomain editingDomain, IAdaptable targetContainer, List<? extends IAdaptable> elementsToMove, Class<? extends EObject> classToCast) {
- super(editingDomain, null, elementsToMove);
- this.targetContainer = targetContainer;
- this.iAdaptableToMove = new HashMap<IAdaptable, Object>();
- this.classToCast = classToCast;
- for (Iterator<? extends IAdaptable> i = elementsToMove.iterator(); i.hasNext();) {
- this.iAdaptableToMove.put(i.next(), null);
- }
- }
-
- public DeferredMoveRequest(TransactionalEditingDomain editingDomain, IAdaptable targetContainer, EReference targetFeature, IAdaptable elementToMove, Class<? extends EObject> classToCast) {
- super(editingDomain, null, targetFeature, null);
- this.targetContainer = targetContainer;
- this.iAdaptableToMove = new HashMap<IAdaptable, Object>();
- this.classToCast = classToCast;
- iAdaptableToMove.put(elementToMove, targetFeature);
- }
-
- public DeferredMoveRequest(TransactionalEditingDomain editingDomain, IAdaptable targetContainer, Map<IAdaptable, Object> elementsToMove, Class<? extends EObject> classToCast) {
- super(editingDomain, null, elementsToMove);
- this.targetContainer = targetContainer;
- this.classToCast = classToCast;
- this.iAdaptableToMove = elementsToMove;
- }
-
- @Override
- public Map getElementsToMove() {
- if (elementsToMove == null) {
- elementsToMove = new HashMap<EObject, Object>(iAdaptableToMove.size());
- for (Entry<IAdaptable, Object> entry : iAdaptableToMove.entrySet()) {
- IAdaptable key = entry.getKey();
- Object object = key.getAdapter(classToCast);
- if (object instanceof EObject) {
- elementsToMove.put((EObject) object, entry.getValue());
- } else if (UMLDiagramEditorPlugin.getInstance().isDebugging()) {
- DebugUtils.getLog().warn("Unable to retrieve the Eobject to move (" + key + ")");
- }
- }
- }
- return elementsToMove;
- }
-
- @Override
- public EObject getTargetContainer() {
- Object object = targetContainer.getAdapter(classToCast);
- if (object instanceof EObject) {
- return (EObject) object;
- } else if (UMLDiagramEditorPlugin.getInstance().isDebugging()) {
- DebugUtils.getLog().warn("Unable to retrieve the Eobject of the target container (" + targetContainer + ")");
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gmf.runtime.emf.type.core.requests.MoveRequest; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils.DebugUtils; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; + +public class DeferredMoveRequest extends MoveRequest { + + /** + * IAdaptable of the container + */ + private IAdaptable targetContainer; + + /** + * {@link IAdaptable} of the element to move + */ + private Map<IAdaptable, Object> iAdaptableToMove; + + /** + * {@link EObject= to move + */ + private Map<EObject, Object> elementsToMove; + + /** + * Class used to adapt the IAdaptable (for example {@link EObject} or {@link View} + */ + private Class<? extends EObject> classToCast; + + /** + * + * @param editingDomain + * @param targetContainer + * @param elementsToMove + */ + public DeferredMoveRequest(TransactionalEditingDomain editingDomain, IAdaptable targetContainer, List<? extends IAdaptable> elementsToMove, Class<? extends EObject> classToCast) { + super(editingDomain, null, elementsToMove); + this.targetContainer = targetContainer; + this.iAdaptableToMove = new HashMap<IAdaptable, Object>(); + this.classToCast = classToCast; + for (Iterator<? extends IAdaptable> i = elementsToMove.iterator(); i.hasNext();) { + this.iAdaptableToMove.put(i.next(), null); + } + } + + public DeferredMoveRequest(TransactionalEditingDomain editingDomain, IAdaptable targetContainer, EReference targetFeature, IAdaptable elementToMove, Class<? extends EObject> classToCast) { + super(editingDomain, null, targetFeature, null); + this.targetContainer = targetContainer; + this.iAdaptableToMove = new HashMap<IAdaptable, Object>(); + this.classToCast = classToCast; + iAdaptableToMove.put(elementToMove, targetFeature); + } + + public DeferredMoveRequest(TransactionalEditingDomain editingDomain, IAdaptable targetContainer, Map<IAdaptable, Object> elementsToMove, Class<? extends EObject> classToCast) { + super(editingDomain, null, elementsToMove); + this.targetContainer = targetContainer; + this.classToCast = classToCast; + this.iAdaptableToMove = elementsToMove; + } + + @Override + public Map getElementsToMove() { + if (elementsToMove == null) { + elementsToMove = new HashMap<EObject, Object>(iAdaptableToMove.size()); + for (Entry<IAdaptable, Object> entry : iAdaptableToMove.entrySet()) { + IAdaptable key = entry.getKey(); + Object object = key.getAdapter(classToCast); + if (object instanceof EObject) { + elementsToMove.put((EObject) object, entry.getValue()); + } else if (UMLDiagramEditorPlugin.getInstance().isDebugging()) { + DebugUtils.getLog().warn("Unable to retrieve the Eobject to move (" + key + ")"); + } + } + } + return elementsToMove; + } + + @Override + public EObject getTargetContainer() { + Object object = targetContainer.getAdapter(classToCast); + if (object instanceof EObject) { + return (EObject) object; + } else if (UMLDiagramEditorPlugin.getInstance().isDebugging()) { + DebugUtils.getLog().warn("Unable to retrieve the Eobject of the target container (" + targetContainer + ")"); + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/IGroupRequest.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/IGroupRequest.java index b9c3b8f4e0d..d768376c57d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/IGroupRequest.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/IGroupRequest.java @@ -1,87 +1,87 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.gef.Request;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-
-import com.google.common.collect.Multimap;
-
-public interface IGroupRequest {
-
- public static enum GroupRequestType {
- /**
- * Refer to an creation event
- */
- CREATION,
- /**
- * Refer to an move(and or resize) event
- */
- MOVE,
- /**
- * Refresh groups request
- */
- REFRESH
- }
-
- public static String INITIAL_TARGET_REQUEST_NEW_BOUNDS = "GroupFramework_InitialTargetRequestNewBounds";////$NON-NLS-1$
-
- public GroupRequestType getGroupRequestType();
-
- public IGraphicalEditPart getHostRequest();
-
- public Request getInitialRequest();
-
- public IAdaptable getTargetElement();
-
- /**
- * Get the label of the request
- *
- * @return
- */
- public String getLabel();
-
- public IContainerNodeDescriptor getNodeDescpitor();
-
- // /**
- // * Get the absolute bounds of the initial target.
- // * For example for changeBoudnsRequest in group. This will represent the bounds of the group after the bounds have changed
- // * @return
- // */
- // public Rectangle getIntialTargetAbsoluteBounds();
- // /**
- // * Set the absolute bounds of the initial target.
- // * For example for changeBoudnsRequest in group. This will represent the bounds of the group after the bounds have changed
- // * @return
- // */
- // public void setIntialTargetAbsoluteBounds(Rectangle bounds);
- /**
- * Map which link an An Reference to it's values
- *
- * @return
- */
- public Multimap<EReference, EObject> getParentEReferenceMap();
-
- /**
- * Map which link an EObject to its {@link EReference} of the current target
- *
- * @return
- */
- public Multimap<EReference, EObject> getChildrenEReferenceMap();
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.gef.Request; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; + +import com.google.common.collect.Multimap; + +public interface IGroupRequest { + + public static enum GroupRequestType { + /** + * Refer to an creation event + */ + CREATION, + /** + * Refer to an move(and or resize) event + */ + MOVE, + /** + * Refresh groups request + */ + REFRESH + } + + public static String INITIAL_TARGET_REQUEST_NEW_BOUNDS = "GroupFramework_InitialTargetRequestNewBounds";////$NON-NLS-1$ + + public GroupRequestType getGroupRequestType(); + + public IGraphicalEditPart getHostRequest(); + + public Request getInitialRequest(); + + public IAdaptable getTargetElement(); + + /** + * Get the label of the request + * + * @return + */ + public String getLabel(); + + public IContainerNodeDescriptor getNodeDescpitor(); + + // /** + // * Get the absolute bounds of the initial target. + // * For example for changeBoudnsRequest in group. This will represent the bounds of the group after the bounds have changed + // * @return + // */ + // public Rectangle getIntialTargetAbsoluteBounds(); + // /** + // * Set the absolute bounds of the initial target. + // * For example for changeBoudnsRequest in group. This will represent the bounds of the group after the bounds have changed + // * @return + // */ + // public void setIntialTargetAbsoluteBounds(Rectangle bounds); + /** + * Map which link an An Reference to it's values + * + * @return + */ + public Multimap<EReference, EObject> getParentEReferenceMap(); + + /** + * Map which link an EObject to its {@link EReference} of the current target + * + * @return + */ + public Multimap<EReference, EObject> getChildrenEReferenceMap(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/RefreshGroupsRequest.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/RefreshGroupsRequest.java index b7c5be666b3..b238ec8ea25 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/RefreshGroupsRequest.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/RefreshGroupsRequest.java @@ -1,33 +1,33 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-
-public class RefreshGroupsRequest extends AbstractGroupRequest {
-
- public RefreshGroupsRequest(IGraphicalEditPart host, IAdaptable target, IContainerNodeDescriptor nodeDescriptor) {
- super(host, null, target, nodeDescriptor);
- request = new ChangeBoundsRequest();
- }
-
- @Override
- public GroupRequestType getGroupRequestType() {
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; + +public class RefreshGroupsRequest extends AbstractGroupRequest { + + public RefreshGroupsRequest(IGraphicalEditPart host, IAdaptable target, IContainerNodeDescriptor nodeDescriptor) { + super(host, null, target, nodeDescriptor); + request = new ChangeBoundsRequest(); + } + + @Override + public GroupRequestType getGroupRequestType() { + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/SetDeferredRequest.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/SetDeferredRequest.java index be457eaacc8..b463a0008e5 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/SetDeferredRequest.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/request/SetDeferredRequest.java @@ -1,45 +1,45 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request;
-
-import java.util.List;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-
-public class SetDeferredRequest extends SetRequest {
-
- protected IAdaptable elementToEdit;
-
- public SetDeferredRequest(TransactionalEditingDomain editinDomain, IAdaptable elementToEdit, EStructuralFeature feature, Object value) {
- super(editinDomain, null, feature, value);
- this.elementToEdit = elementToEdit;
- }
-
- public IAdaptable getElementToSet() {
- return elementToEdit;
- }
-
- /**
- * @deprecated use {@link SetDeferredRequest#getElementToSet()}
- */
- @Deprecated
- @Override
- public List getElementsToEdit() {
- return super.getElementsToEdit();
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.request; + +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; + +public class SetDeferredRequest extends SetRequest { + + protected IAdaptable elementToEdit; + + public SetDeferredRequest(TransactionalEditingDomain editinDomain, IAdaptable elementToEdit, EStructuralFeature feature, Object value) { + super(editinDomain, null, feature, value); + this.elementToEdit = elementToEdit; + } + + public IAdaptable getElementToSet() { + return elementToEdit; + } + + /** + * @deprecated use {@link SetDeferredRequest#getElementToSet()} + */ + @Deprecated + @Override + public List getElementsToEdit() { + return super.getElementsToEdit(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ui/GroupNotifierLabelProvider.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ui/GroupNotifierLabelProvider.java index 139e6fca05b..0a9bb242b89 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ui/GroupNotifierLabelProvider.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ui/GroupNotifierLabelProvider.java @@ -1,57 +1,57 @@ -/*****************************************************************************
- * Copyright (c) 2011, 2014 Atos, CEA, and others.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- * Christian W. Damus (CEA) - bug 410346
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.ui;
-
-import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
-import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * {@link LabelProvider} for {@link IGroupNotifier}
- */
-public class GroupNotifierLabelProvider extends LabelProvider {
-
- private ComposedAdapterFactory factory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
- private AdapterFactoryLabelProvider delegate = new AdapterFactoryLabelProvider(factory);
-
- @Override
- public String getText(Object element) {
- if (element instanceof IGroupNotifier) {
- IGroupNotifier notifier = (IGroupNotifier) element;
- return delegate.getText(notifier.getEObject());
- }
- return super.getText(element);
- }
-
- @Override
- public Image getImage(Object element) {
- if (element instanceof IGroupNotifier) {
- IGroupNotifier notifier = (IGroupNotifier) element;
- return delegate.getImage(notifier.getEObject());
- }
- return super.getImage(element);
- }
-
- @Override
- public void dispose() {
- delegate.dispose();
- factory.dispose();
-
- super.dispose();
- }
-}
+/***************************************************************************** + * Copyright (c) 2011, 2014 Atos, CEA, and others. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * Christian W. Damus (CEA) - bug 410346 + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.ui; + +import org.eclipse.emf.edit.provider.ComposedAdapterFactory; +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier; +import org.eclipse.swt.graphics.Image; + +/** + * {@link LabelProvider} for {@link IGroupNotifier} + */ +public class GroupNotifierLabelProvider extends LabelProvider { + + private ComposedAdapterFactory factory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE); + private AdapterFactoryLabelProvider delegate = new AdapterFactoryLabelProvider(factory); + + @Override + public String getText(Object element) { + if (element instanceof IGroupNotifier) { + IGroupNotifier notifier = (IGroupNotifier) element; + return delegate.getText(notifier.getEObject()); + } + return super.getText(element); + } + + @Override + public Image getImage(Object element) { + if (element instanceof IGroupNotifier) { + IGroupNotifier notifier = (IGroupNotifier) element; + return delegate.getImage(notifier.getEObject()); + } + return super.getImage(element); + } + + @Override + public void dispose() { + delegate.dispose(); + factory.dispose(); + + super.dispose(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ui/IntegrateViewToConfigureComposite.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ui/IntegrateViewToConfigureComposite.java index 45316d22b27..4789e545897 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ui/IntegrateViewToConfigureComposite.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/ui/IntegrateViewToConfigureComposite.java @@ -1,84 +1,84 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.ui;
-
-import java.util.List;
-
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-/**
- * Composite used to notify user of new visual child
- */
-public class IntegrateViewToConfigureComposite extends Composite {
-
- /**
- *
- */
- private Table table;
-
- /**
- *
- */
- private CheckboxTableViewer checkboxTableViewer;
-
- /**
- * Create the composite.
- *
- * @param parent
- * @param style
- */
- public IntegrateViewToConfigureComposite(Composite parent, int style, List<IGroupNotifier> newChildren, String label) {
- super(parent, style);
- setLayout(new GridLayout(1, false));
- Label lblNewLabel = new Label(this, SWT.NONE);
- lblNewLabel.setText(label);
- checkboxTableViewer = CheckboxTableViewer.newCheckList(this, SWT.FULL_SELECTION);
- table = checkboxTableViewer.getTable();
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
- checkboxTableViewer.setContentProvider(new ArrayContentProvider());
- checkboxTableViewer.setLabelProvider(new GroupNotifierLabelProvider());
- checkboxTableViewer.setInput(newChildren);
- checkboxTableViewer.setAllChecked(true);
- }
-
- @Override
- protected void checkSubclass() {
- }
-
- public Iterable<IGroupNotifier> getSelectedNotifier() {
- Object[] selection = checkboxTableViewer.getCheckedElements();
- Iterable<Object> groupNotifiers = Iterables.filter(Lists.newArrayList(selection), Predicates.instanceOf(IGroupNotifier.class));
- return Iterables.transform(groupNotifiers, new Function<Object, IGroupNotifier>() {
-
- @Override
- public IGroupNotifier apply(Object arg0) {
- return (IGroupNotifier) arg0;
- }
- });
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.ui; + +import java.util.List; + +import org.eclipse.jface.viewers.ArrayContentProvider; +import org.eclipse.jface.viewers.CheckboxTableViewer; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.editpolicy.notifiers.IGroupNotifier; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Table; + +import com.google.common.base.Function; +import com.google.common.base.Predicates; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Composite used to notify user of new visual child + */ +public class IntegrateViewToConfigureComposite extends Composite { + + /** + * + */ + private Table table; + + /** + * + */ + private CheckboxTableViewer checkboxTableViewer; + + /** + * Create the composite. + * + * @param parent + * @param style + */ + public IntegrateViewToConfigureComposite(Composite parent, int style, List<IGroupNotifier> newChildren, String label) { + super(parent, style); + setLayout(new GridLayout(1, false)); + Label lblNewLabel = new Label(this, SWT.NONE); + lblNewLabel.setText(label); + checkboxTableViewer = CheckboxTableViewer.newCheckList(this, SWT.FULL_SELECTION); + table = checkboxTableViewer.getTable(); + table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); + checkboxTableViewer.setContentProvider(new ArrayContentProvider()); + checkboxTableViewer.setLabelProvider(new GroupNotifierLabelProvider()); + checkboxTableViewer.setInput(newChildren); + checkboxTableViewer.setAllChecked(true); + } + + @Override + protected void checkSubclass() { + } + + public Iterable<IGroupNotifier> getSelectedNotifier() { + Object[] selection = checkboxTableViewer.getCheckedElements(); + Iterable<Object> groupNotifiers = Iterables.filter(Lists.newArrayList(selection), Predicates.instanceOf(IGroupNotifier.class)); + return Iterables.transform(groupNotifiers, new Function<Object, IGroupNotifier>() { + + @Override + public IGroupNotifier apply(Object arg0) { + return (IGroupNotifier) arg0; + } + }); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/utils/DebugUtils.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/utils/DebugUtils.java index a0332677f17..34df7b758dc 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/utils/DebugUtils.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/utils/DebugUtils.java @@ -1,74 +1,74 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils;
-
-import java.util.Map.Entry;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.papyrus.infra.core.log.LogHelper;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-
-import com.google.common.collect.Multimap;
-
-public class DebugUtils {
-
- /**
- * Allow user during debug to desactivation debug notficcation
- */
- private static final boolean LOCAL_DESACTIVATOR = true;
-
- private static LogHelper log = null;
-
- /**
- * Get loger
- *
- * @return
- */
- public static LogHelper getLog() {
- if (log == null) {
- log = new LogHelper(UMLDiagramEditorPlugin.getInstance());
- }
- return log;
- }
-
- /**
- * return true if debugging
- *
- * @return
- */
- public static boolean isDebugging() {
- return UMLDiagramEditorPlugin.getInstance().isDebugging() && LOCAL_DESACTIVATOR;
- }
-
- /**
- * Display a multi map
- *
- * @param message
- * @param multimap
- */
- public static void displayMultipmapDebug(String message, Multimap<EReference, EObject> multimap) {
- if (DebugUtils.isDebugging()) {
- DebugUtils.getLog().debug(message);
- for (Entry<EReference, EObject> e : multimap.entries()) {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(Utils.getCorrectLabel(e.getValue()));
- stringBuilder.append(" --> ");
- stringBuilder.append(e.getKey().getName());
- DebugUtils.getLog().debug(stringBuilder.toString());
- }
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils; + +import java.util.Map.Entry; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.papyrus.infra.core.log.LogHelper; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; + +import com.google.common.collect.Multimap; + +public class DebugUtils { + + /** + * Allow user during debug to desactivation debug notficcation + */ + private static final boolean LOCAL_DESACTIVATOR = true; + + private static LogHelper log = null; + + /** + * Get loger + * + * @return + */ + public static LogHelper getLog() { + if (log == null) { + log = new LogHelper(UMLDiagramEditorPlugin.getInstance()); + } + return log; + } + + /** + * return true if debugging + * + * @return + */ + public static boolean isDebugging() { + return UMLDiagramEditorPlugin.getInstance().isDebugging() && LOCAL_DESACTIVATOR; + } + + /** + * Display a multi map + * + * @param message + * @param multimap + */ + public static void displayMultipmapDebug(String message, Multimap<EReference, EObject> multimap) { + if (DebugUtils.isDebugging()) { + DebugUtils.getLog().debug(message); + for (Entry<EReference, EObject> e : multimap.entries()) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(Utils.getCorrectLabel(e.getValue())); + stringBuilder.append(" --> "); + stringBuilder.append(e.getKey().getName()); + DebugUtils.getLog().debug(stringBuilder.toString()); + } + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/utils/Utils.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/utils/Utils.java index 221432fc325..7bdc59d017e 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/utils/Utils.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/activitygroup/utils/Utils.java @@ -1,286 +1,286 @@ -/*****************************************************************************
- * Copyright (c) 2011, 2014 Atos, CEA, and others.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- * Christian W. Damus (CEA) - bug 410346
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest;
-import org.eclipse.gmf.runtime.notation.Bounds;
-import org.eclipse.gmf.runtime.notation.LayoutConstraint;
-import org.eclipse.gmf.runtime.notation.Node;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.DescendantsFilter;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.IGroupRequest;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Sets;
-
-public class Utils {
-
- /**
- * Debug message
- */
- private static final String OLD_PARENT = "Old parent :";
-
- /**
- * Return a iterable of each targeted edit part
- *
- * @param req
- * @return
- */
- public static Iterable<IGraphicalEditPart> getTargetedEditPart(ChangeBoundsRequest req) {
- if (req != null && req.getEditParts() != null) {
- return Iterables.transform(Iterables.filter((Iterable<Object>) req.getEditParts(), new Predicate<Object>() {
-
- @Override
- public boolean apply(Object input) {
- return input instanceof IGraphicalEditPart;
- }
- }), new Function<Object, IGraphicalEditPart>() {
-
- @Override
- public IGraphicalEditPart apply(Object from) {
- return (IGraphicalEditPart) from;
- }
- });
- }
- return Collections.EMPTY_LIST;
- }
-
- /**
- * Get the abslotue bounds of a figure after a change bounds request
- *
- * @param request
- * @param host
- * @return
- */
- public static Rectangle getAbslotueRequestBounds(ChangeBoundsRequest request, IGraphicalEditPart host) {
- Rectangle bounds = getAbsoluteBounds(host);
- return request.getTransformedRectangle(bounds);
- }
-
- /**
- * Get the bounds of an edit part
- *
- * @param part
- * edit part to find bounds
- * @return part's bounds in absolute coordinates
- */
- public static Rectangle getAbsoluteBounds(IGraphicalEditPart part) {
- // take bounds from figure
- part.refresh();
- part.getFigure().invalidate();
- part.getFigure().validate();
- Rectangle bounds = part.getFigure().getBounds().getCopy();
- if (part.getNotationView() instanceof Node) {
- // rather update with up to date model bounds
- Node node = (Node) part.getNotationView();
- LayoutConstraint cst = node.getLayoutConstraint();
- if (cst instanceof Bounds) {
- Bounds b = (Bounds) cst;
- Point parentLoc = part.getFigure().getParent().getBounds().getLocation();
- if (b.getX() > 0) {
- bounds.x = b.getX() + parentLoc.x;
- }
- if (b.getY() > 0) {
- bounds.y = b.getY() + parentLoc.y;
- }
- if (b.getHeight() != -1) {
- bounds.height = b.getHeight();
- }
- if (b.getWidth() != -1) {
- bounds.width = b.getWidth();
- }
- }
- }
- part.getFigure().getParent().translateToAbsolute(bounds);
- return bounds;
- }
-
- // /**
- // * Get the bounds of an edit part
- // *
- // * @param part
- // * edit part to find bounds
- // * @return part's bounds in absolute coordinates
- // */
- // public static Rectangle getAbsoluteBounds(Shape s) {
- // s.
- // // take bounds from figure
- // part.getTopGraphicEditPart().refresh();
- // Rectangle bounds = part.getFigure().getBounds().getCopy();
- //
- // if(part.getNotationView() instanceof Node) {
- // // rather update with up to date model bounds
- // Node node = (Node)part.getNotationView();
- // LayoutConstraint cst = node.getLayoutConstraint();
- // if(cst instanceof Bounds) {
- // Bounds b = (Bounds)cst;
- // Point parentLoc = part.getFigure().getParent().getBounds().getLocation();
- // if(b.getX() > 0) {
- // bounds.x = b.getX() + parentLoc.x;
- // }
- // if(b.getY() > 0) {
- // bounds.y = b.getY() + parentLoc.y;
- // }
- // if(b.getHeight() != -1) {
- // bounds.height = b.getHeight();
- // }
- // if(b.getWidth() != -1) {
- // bounds.width = b.getWidth();
- // }
- // }
- // }
- //
- // part.getFigure().getParent().translateToAbsolute(bounds);
- //
- // return bounds;
- // }
- /**
- * Same as {@link EcoreUtil#filterDescendants(Collection)}
- *
- * @param all
- * @return
- */
- public static Set<EObject> filterDescendants(Set<EObject> all) {
- return Sets.filter(all, new DescendantsFilter(all));
- }
-
- static AdapterFactoryLabelProvider factory = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory());
-
- public static String getCorrectLabel(Object object) {
- if (object instanceof EObject) {
- return factory.getText(object);
- } else if (object instanceof EReference) {
- return ((EReference) object).getName();
- } else {
- return String.valueOf(object); // null safe
- }
- }
-
- public static String getCorrectLabel(IAdaptable object) {
- Object view = object.getAdapter(EObject.class);
- if (view instanceof EObject) {
- return getCorrectLabel(view);
- } else {
- return object.toString();
- }
- }
-
- /**
- * Get old parent references {@link EObject} sorted with {@link EReference} as keys
- *
- * @param request
- * @return
- */
- public static Multimap<EReference, EObject> getOldParents(IGroupRequest request) {
- if (request.getNodeDescpitor() != null) {
- return getReferenceMultimap(request, request.getNodeDescpitor().getParentReferences());
- }
- return ArrayListMultimap.create();
- }
-
- /**
- * Get old getOldChildren references {@link EObject} sorted with {@link EReference} as keys
- *
- * @param request
- * @return
- */
- public static Multimap<EReference, EObject> getOldChildren(IGroupRequest request) {
- if (request.getNodeDescpitor() != null) {
- return getReferenceMultimap(request, request.getNodeDescpitor().getChildrenReferences());
- }
- return ArrayListMultimap.create();
- }
-
- /**
- * Get the the multimap relative a request and a {@link Iterable} of {@link EReference}
- *
- * @param request
- * @param references
- * @return
- */
- protected static Multimap<EReference, EObject> getReferenceMultimap(IGroupRequest request, Iterable<EReference> references) {
- Object elementAdapter = request.getTargetElement().getAdapter(EObject.class);
- if (elementAdapter instanceof EObject && references != null) {
- Multimap<EReference, EObject> result = ArrayListMultimap.create();
- EObject targetElement = (EObject) elementAdapter;
- if (targetElement != null) {
- for (EReference ref : references) {
- if (ref.isMany()) {
- Collection<EObject> values = (Collection<EObject>) targetElement.eGet(ref);
- for (EObject v : values) {
- result.put(ref, v);
- }
- } else {
- Object value = targetElement.eGet(ref);
- ;
- if (value instanceof EObject) {
- result.put(ref, (EObject) value);
- }
- }
- }
- }
- return result;
- }
- return ArrayListMultimap.create();
- }
-
- /**
- * Copy a ChangeBoundsRequest.
- * Do not copy metadata
- *
- * @param req
- * @param part
- * @return
- */
- public static ChangeBoundsRequest getChangeBoundsRequestCopy(final ChangeBoundsRequest req, final EditPart part) {
- ChangeBoundsRequest auxRequest = new ChangeBoundsRequest(req.getType());
- auxRequest.setLocation(req.getLocation());
- auxRequest.setEditParts(Collections.singletonList(part));
- auxRequest.setMoveDelta(req.getMoveDelta());
- auxRequest.setResizeDirection(req.getResizeDirection());
- auxRequest.setSizeDelta(req.getSizeDelta());
- return auxRequest;
- }
-
- public static Rectangle getAbslotueRequestBounds(CreateViewRequest initialRequest) {
- Point location = initialRequest.getLocation();
- Dimension size = initialRequest.getSize();
- /**
- * TODO get default size
- */
- Rectangle creationBounds = new Rectangle(location != null ? location : new Point(0, 0), size != null ? size : new Dimension(20, 20));
- return creationBounds;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011, 2014 Atos, CEA, and others. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * Christian W. Damus (CEA) - bug 410346 + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.activitygroup.utils; + +import java.util.Collection; +import java.util.Collections; +import java.util.Set; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.requests.CreateViewRequest; +import org.eclipse.gmf.runtime.notation.Bounds; +import org.eclipse.gmf.runtime.notation.LayoutConstraint; +import org.eclipse.gmf.runtime.notation.Node; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.predicates.DescendantsFilter; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.IGroupRequest; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Iterables; +import com.google.common.collect.Multimap; +import com.google.common.collect.Sets; + +public class Utils { + + /** + * Debug message + */ + private static final String OLD_PARENT = "Old parent :"; + + /** + * Return a iterable of each targeted edit part + * + * @param req + * @return + */ + public static Iterable<IGraphicalEditPart> getTargetedEditPart(ChangeBoundsRequest req) { + if (req != null && req.getEditParts() != null) { + return Iterables.transform(Iterables.filter((Iterable<Object>) req.getEditParts(), new Predicate<Object>() { + + @Override + public boolean apply(Object input) { + return input instanceof IGraphicalEditPart; + } + }), new Function<Object, IGraphicalEditPart>() { + + @Override + public IGraphicalEditPart apply(Object from) { + return (IGraphicalEditPart) from; + } + }); + } + return Collections.EMPTY_LIST; + } + + /** + * Get the abslotue bounds of a figure after a change bounds request + * + * @param request + * @param host + * @return + */ + public static Rectangle getAbslotueRequestBounds(ChangeBoundsRequest request, IGraphicalEditPart host) { + Rectangle bounds = getAbsoluteBounds(host); + return request.getTransformedRectangle(bounds); + } + + /** + * Get the bounds of an edit part + * + * @param part + * edit part to find bounds + * @return part's bounds in absolute coordinates + */ + public static Rectangle getAbsoluteBounds(IGraphicalEditPart part) { + // take bounds from figure + part.refresh(); + part.getFigure().invalidate(); + part.getFigure().validate(); + Rectangle bounds = part.getFigure().getBounds().getCopy(); + if (part.getNotationView() instanceof Node) { + // rather update with up to date model bounds + Node node = (Node) part.getNotationView(); + LayoutConstraint cst = node.getLayoutConstraint(); + if (cst instanceof Bounds) { + Bounds b = (Bounds) cst; + Point parentLoc = part.getFigure().getParent().getBounds().getLocation(); + if (b.getX() > 0) { + bounds.x = b.getX() + parentLoc.x; + } + if (b.getY() > 0) { + bounds.y = b.getY() + parentLoc.y; + } + if (b.getHeight() != -1) { + bounds.height = b.getHeight(); + } + if (b.getWidth() != -1) { + bounds.width = b.getWidth(); + } + } + } + part.getFigure().getParent().translateToAbsolute(bounds); + return bounds; + } + + // /** + // * Get the bounds of an edit part + // * + // * @param part + // * edit part to find bounds + // * @return part's bounds in absolute coordinates + // */ + // public static Rectangle getAbsoluteBounds(Shape s) { + // s. + // // take bounds from figure + // part.getTopGraphicEditPart().refresh(); + // Rectangle bounds = part.getFigure().getBounds().getCopy(); + // + // if(part.getNotationView() instanceof Node) { + // // rather update with up to date model bounds + // Node node = (Node)part.getNotationView(); + // LayoutConstraint cst = node.getLayoutConstraint(); + // if(cst instanceof Bounds) { + // Bounds b = (Bounds)cst; + // Point parentLoc = part.getFigure().getParent().getBounds().getLocation(); + // if(b.getX() > 0) { + // bounds.x = b.getX() + parentLoc.x; + // } + // if(b.getY() > 0) { + // bounds.y = b.getY() + parentLoc.y; + // } + // if(b.getHeight() != -1) { + // bounds.height = b.getHeight(); + // } + // if(b.getWidth() != -1) { + // bounds.width = b.getWidth(); + // } + // } + // } + // + // part.getFigure().getParent().translateToAbsolute(bounds); + // + // return bounds; + // } + /** + * Same as {@link EcoreUtil#filterDescendants(Collection)} + * + * @param all + * @return + */ + public static Set<EObject> filterDescendants(Set<EObject> all) { + return Sets.filter(all, new DescendantsFilter(all)); + } + + static AdapterFactoryLabelProvider factory = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()); + + public static String getCorrectLabel(Object object) { + if (object instanceof EObject) { + return factory.getText(object); + } else if (object instanceof EReference) { + return ((EReference) object).getName(); + } else { + return String.valueOf(object); // null safe + } + } + + public static String getCorrectLabel(IAdaptable object) { + Object view = object.getAdapter(EObject.class); + if (view instanceof EObject) { + return getCorrectLabel(view); + } else { + return object.toString(); + } + } + + /** + * Get old parent references {@link EObject} sorted with {@link EReference} as keys + * + * @param request + * @return + */ + public static Multimap<EReference, EObject> getOldParents(IGroupRequest request) { + if (request.getNodeDescpitor() != null) { + return getReferenceMultimap(request, request.getNodeDescpitor().getParentReferences()); + } + return ArrayListMultimap.create(); + } + + /** + * Get old getOldChildren references {@link EObject} sorted with {@link EReference} as keys + * + * @param request + * @return + */ + public static Multimap<EReference, EObject> getOldChildren(IGroupRequest request) { + if (request.getNodeDescpitor() != null) { + return getReferenceMultimap(request, request.getNodeDescpitor().getChildrenReferences()); + } + return ArrayListMultimap.create(); + } + + /** + * Get the the multimap relative a request and a {@link Iterable} of {@link EReference} + * + * @param request + * @param references + * @return + */ + protected static Multimap<EReference, EObject> getReferenceMultimap(IGroupRequest request, Iterable<EReference> references) { + Object elementAdapter = request.getTargetElement().getAdapter(EObject.class); + if (elementAdapter instanceof EObject && references != null) { + Multimap<EReference, EObject> result = ArrayListMultimap.create(); + EObject targetElement = (EObject) elementAdapter; + if (targetElement != null) { + for (EReference ref : references) { + if (ref.isMany()) { + Collection<EObject> values = (Collection<EObject>) targetElement.eGet(ref); + for (EObject v : values) { + result.put(ref, v); + } + } else { + Object value = targetElement.eGet(ref); + ; + if (value instanceof EObject) { + result.put(ref, (EObject) value); + } + } + } + } + return result; + } + return ArrayListMultimap.create(); + } + + /** + * Copy a ChangeBoundsRequest. + * Do not copy metadata + * + * @param req + * @param part + * @return + */ + public static ChangeBoundsRequest getChangeBoundsRequestCopy(final ChangeBoundsRequest req, final EditPart part) { + ChangeBoundsRequest auxRequest = new ChangeBoundsRequest(req.getType()); + auxRequest.setLocation(req.getLocation()); + auxRequest.setEditParts(Collections.singletonList(part)); + auxRequest.setMoveDelta(req.getMoveDelta()); + auxRequest.setResizeDirection(req.getResizeDirection()); + auxRequest.setSizeDelta(req.getSizeDelta()); + return auxRequest; + } + + public static Rectangle getAbslotueRequestBounds(CreateViewRequest initialRequest) { + Point location = initialRequest.getLocation(); + Dimension size = initialRequest.getSize(); + /** + * TODO get default size + */ + Rectangle creationBounds = new Rectangle(location != null ? location : new Point(0, 0), size != null ? size : new Dimension(20, 20)); + return creationBounds; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/ChangeParentCommand.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/ChangeParentCommand.java index 30a2719bf5d..dbc35b95d99 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/ChangeParentCommand.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/ChangeParentCommand.java @@ -1,152 +1,152 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.commands;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.gmf.runtime.diagram.core.internal.l10n.DiagramCoreMessages;
-import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
-import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.gmf.runtime.notation.NotationPackage;
-import org.eclipse.gmf.runtime.notation.View;
-
-public class ChangeParentCommand extends AbstractTransactionalCommand {
-
- private IAdaptable parent;
-
- private IAdaptable child;
-
- private int index;
-
- /**
- * Creates a new <code>AddCommand</code>
- *
- * @param editingDomain
- * the editing domain through which model changes are made
- * @param parent
- * The parent view adapter
- * @param child
- * The child view adapter
- */
- public ChangeParentCommand(TransactionalEditingDomain editingDomain, IAdaptable parent, IAdaptable child) {
- this(editingDomain, parent, child, ViewUtil.APPEND);
- }
-
- /**
- * Creates a new <code>AddCommand</code>
- *
- * @param editingDomain
- * the editing domain through which model changes are made
- * @param parent
- * The parent view adapter
- * @param child
- * The child view adapter
- * @param index
- * the child insertion index
- */
- public ChangeParentCommand(TransactionalEditingDomain editingDomain, IAdaptable parent, IAdaptable child, int index) {
- super(editingDomain, DiagramCoreMessages.AddCommand_Label, null);
- assert null != parent : "Null parent in AddCommand";//$NON-NLS-1$
- assert null != child : "Null child in AddCommand";//$NON-NLS-1$
- this.parent = parent;
- this.child = child;
- this.index = index;
- }
-
- @Override
- public List getAffectedFiles() {
- View view = (View) parent.getAdapter(View.class);
- if (view != null) {
- List result = new ArrayList();
- IFile file = WorkspaceSynchronizer.getFile(view.eResource());
- if (file != null) {
- result.add(file);
- }
- return result;
- }
- return super.getAffectedFiles();
- }
-
- /**
- * executes the command; which will get the child and the containaer from
- * the <code>IAdaptable<code> and then insert the child at the given index
- * in the containers child list.
- */
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- /**
- * Change graphical parent
- */
- View childView = (View) child.getAdapter(View.class);
- View parentView = (View) parent.getAdapter(View.class);
- EObject oldParent = childView.eContainer();
- if (oldParent instanceof View) {
- ((View) oldParent).removeChild(childView);
- }
- if (index == ViewUtil.APPEND) {
- parentView.insertChild(childView);
- } else {
- parentView.insertChildAt(childView, index);
- }
- /**
- * Change coordiante
- */
- Point childViewCoordinate = getLocation(childView);
- Point parentViewCoordinate = getLocation(parentView);
- ViewUtil.setStructuralFeatureValue(childView, NotationPackage.eINSTANCE.getLocation_X(), Integer.valueOf(110));
- ViewUtil.setStructuralFeatureValue(childView, NotationPackage.eINSTANCE.getLocation_Y(), Integer.valueOf(110));
- return CommandResult.newOKCommandResult();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.common.core.command.ICommand#getLabel()
- */
- @Override
- public String getLabel() {
- return DiagramCoreMessages.AddCommand_Label;
- }
-
- protected Point getAbsoluteLocation(View v) {
- Point result = getLocation(v);
- EObject container = v.eContainer();
- while (container instanceof View) {
- View parentView = (View) container;
- Point parentCoordinate = getLocation(parentView);
- if (parentCoordinate != null) {
- result.translate(parentCoordinate);
- }
- container = parentView.eContainer();
- }
- return result;
- }
-
- protected Point getLocation(View v) {
- Integer x = (Integer) ViewUtil.getStructuralFeatureValue(v, NotationPackage.eINSTANCE.getLocation_X());
- Integer y = (Integer) ViewUtil.getStructuralFeatureValue(v, NotationPackage.eINSTANCE.getLocation_Y());
- return new Point(x, y);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.commands; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.emf.workspace.util.WorkspaceSynchronizer; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.gmf.runtime.diagram.core.internal.l10n.DiagramCoreMessages; +import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil; +import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.gmf.runtime.notation.NotationPackage; +import org.eclipse.gmf.runtime.notation.View; + +public class ChangeParentCommand extends AbstractTransactionalCommand { + + private IAdaptable parent; + + private IAdaptable child; + + private int index; + + /** + * Creates a new <code>AddCommand</code> + * + * @param editingDomain + * the editing domain through which model changes are made + * @param parent + * The parent view adapter + * @param child + * The child view adapter + */ + public ChangeParentCommand(TransactionalEditingDomain editingDomain, IAdaptable parent, IAdaptable child) { + this(editingDomain, parent, child, ViewUtil.APPEND); + } + + /** + * Creates a new <code>AddCommand</code> + * + * @param editingDomain + * the editing domain through which model changes are made + * @param parent + * The parent view adapter + * @param child + * The child view adapter + * @param index + * the child insertion index + */ + public ChangeParentCommand(TransactionalEditingDomain editingDomain, IAdaptable parent, IAdaptable child, int index) { + super(editingDomain, DiagramCoreMessages.AddCommand_Label, null); + assert null != parent : "Null parent in AddCommand";//$NON-NLS-1$ + assert null != child : "Null child in AddCommand";//$NON-NLS-1$ + this.parent = parent; + this.child = child; + this.index = index; + } + + @Override + public List getAffectedFiles() { + View view = (View) parent.getAdapter(View.class); + if (view != null) { + List result = new ArrayList(); + IFile file = WorkspaceSynchronizer.getFile(view.eResource()); + if (file != null) { + result.add(file); + } + return result; + } + return super.getAffectedFiles(); + } + + /** + * executes the command; which will get the child and the containaer from + * the <code>IAdaptable<code> and then insert the child at the given index + * in the containers child list. + */ + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + /** + * Change graphical parent + */ + View childView = (View) child.getAdapter(View.class); + View parentView = (View) parent.getAdapter(View.class); + EObject oldParent = childView.eContainer(); + if (oldParent instanceof View) { + ((View) oldParent).removeChild(childView); + } + if (index == ViewUtil.APPEND) { + parentView.insertChild(childView); + } else { + parentView.insertChildAt(childView, index); + } + /** + * Change coordiante + */ + Point childViewCoordinate = getLocation(childView); + Point parentViewCoordinate = getLocation(parentView); + ViewUtil.setStructuralFeatureValue(childView, NotationPackage.eINSTANCE.getLocation_X(), Integer.valueOf(110)); + ViewUtil.setStructuralFeatureValue(childView, NotationPackage.eINSTANCE.getLocation_Y(), Integer.valueOf(110)); + return CommandResult.newOKCommandResult(); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.common.core.command.ICommand#getLabel() + */ + @Override + public String getLabel() { + return DiagramCoreMessages.AddCommand_Label; + } + + protected Point getAbsoluteLocation(View v) { + Point result = getLocation(v); + EObject container = v.eContainer(); + while (container instanceof View) { + View parentView = (View) container; + Point parentCoordinate = getLocation(parentView); + if (parentCoordinate != null) { + result.translate(parentCoordinate); + } + container = parentView.eContainer(); + } + return result; + } + + protected Point getLocation(View v) { + Integer x = (Integer) ViewUtil.getStructuralFeatureValue(v, NotationPackage.eINSTANCE.getLocation_X()); + Integer y = (Integer) ViewUtil.getStructuralFeatureValue(v, NotationPackage.eINSTANCE.getLocation_Y()); + return new Point(x, y); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/CreatePinToParameterLinkEAnnotation.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/CreatePinToParameterLinkEAnnotation.java index 81393a1b7a0..aaa3fc09ab9 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/CreatePinToParameterLinkEAnnotation.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/CreatePinToParameterLinkEAnnotation.java @@ -1,104 +1,104 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : [Activitydiagram] Papyrus should provide a way to manually resynchronize pins and parameters on Call Actions
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.commands;
-
-import org.eclipse.emf.common.util.EMap;
-import org.eclipse.emf.ecore.EAnnotation;
-import org.eclipse.emf.ecore.EModelElement;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.xmi.XMIResource;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.papyrus.infra.emf.commands.CreateEAnnotationCommand;
-import org.eclipse.papyrus.uml.diagram.activity.helper.IPinToParameterLinkCommand;
-import org.eclipse.papyrus.uml.diagram.activity.helper.datastructure.ILinkPinToTarget;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.Pin;
-
-/**
- * Command to create or update the EAnnoation which store the link from a {@link Pin} to a {@link Parameter}
- *
- * @author arthur daussy
- *
- */
-public class CreatePinToParameterLinkEAnnotation extends CreateEAnnotationCommand implements IPinToParameterLinkCommand {
-
- /**
- * {@link Parameter}
- */
- private Element target;
-
- /**
- * {@link EAnnotation}
- */
- protected EAnnotation eAnnotation;
-
- /**
- * Pin which will old the {@link EAnnotation}
- */
- protected EModelElement modelOwner;
-
- public CreatePinToParameterLinkEAnnotation(TransactionalEditingDomain domain, Pin object, Element target) {
- super(domain, object, PIN_TO_PARAMETER_LINK);
- this.target = target;
- this.modelOwner = object;
- }
-
- public CreatePinToParameterLinkEAnnotation(TransactionalEditingDomain domain, ILinkPinToTarget link) {
- super(domain, link.getPin(), PIN_TO_PARAMETER_LINK);
- this.target = link.getTarget();
- this.modelOwner = link.getPin();
- }
-
- @Override
- protected EAnnotation createEAnnotation() {
- eAnnotation = super.createEAnnotation();
- return eAnnotation;
- }
-
- @Override
- protected void doExecute() {
- // try to get an old EAnnotation
- eAnnotation = modelOwner.getEAnnotation(PIN_TO_PARAMETER_LINK);
- if (eAnnotation == null) {
- super.doExecute();
- }
- EMap<String, String> details = eAnnotation.getDetails();
- if (details != null) {
- details.put(PIN_TO_PARAMETER_LINK, getXmiID(target));
- }
- }
-
- /**
- * Get the XMI id to identify the parameter
- *
- * @param p
- * {@link Parameter} to identify
- * @return XMI id og the {@link Parameter}
- */
- protected String getXmiID(EObject p) {
- Resource ressource = p.eResource();
- if (ressource instanceof XMIResource) {
- return ((XMIResource) ressource).getID(p);
- }
- return NO_PARAMETER_ID;
- }
-
- @Override
- public boolean canExecute() {
- return super.canExecute() && modelOwner != null && target != null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : [Activitydiagram] Papyrus should provide a way to manually resynchronize pins and parameters on Call Actions + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.commands; + +import org.eclipse.emf.common.util.EMap; +import org.eclipse.emf.ecore.EAnnotation; +import org.eclipse.emf.ecore.EModelElement; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.xmi.XMIResource; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.papyrus.infra.emf.commands.CreateEAnnotationCommand; +import org.eclipse.papyrus.uml.diagram.activity.helper.IPinToParameterLinkCommand; +import org.eclipse.papyrus.uml.diagram.activity.helper.datastructure.ILinkPinToTarget; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.Pin; + +/** + * Command to create or update the EAnnoation which store the link from a {@link Pin} to a {@link Parameter} + * + * @author arthur daussy + * + */ +public class CreatePinToParameterLinkEAnnotation extends CreateEAnnotationCommand implements IPinToParameterLinkCommand { + + /** + * {@link Parameter} + */ + private Element target; + + /** + * {@link EAnnotation} + */ + protected EAnnotation eAnnotation; + + /** + * Pin which will old the {@link EAnnotation} + */ + protected EModelElement modelOwner; + + public CreatePinToParameterLinkEAnnotation(TransactionalEditingDomain domain, Pin object, Element target) { + super(domain, object, PIN_TO_PARAMETER_LINK); + this.target = target; + this.modelOwner = object; + } + + public CreatePinToParameterLinkEAnnotation(TransactionalEditingDomain domain, ILinkPinToTarget link) { + super(domain, link.getPin(), PIN_TO_PARAMETER_LINK); + this.target = link.getTarget(); + this.modelOwner = link.getPin(); + } + + @Override + protected EAnnotation createEAnnotation() { + eAnnotation = super.createEAnnotation(); + return eAnnotation; + } + + @Override + protected void doExecute() { + // try to get an old EAnnotation + eAnnotation = modelOwner.getEAnnotation(PIN_TO_PARAMETER_LINK); + if (eAnnotation == null) { + super.doExecute(); + } + EMap<String, String> details = eAnnotation.getDetails(); + if (details != null) { + details.put(PIN_TO_PARAMETER_LINK, getXmiID(target)); + } + } + + /** + * Get the XMI id to identify the parameter + * + * @param p + * {@link Parameter} to identify + * @return XMI id og the {@link Parameter} + */ + protected String getXmiID(EObject p) { + Resource ressource = p.eResource(); + if (ressource instanceof XMIResource) { + return ((XMIResource) ressource).getID(p); + } + return NO_PARAMETER_ID; + } + + @Override + public boolean canExecute() { + return super.canExecute() && modelOwner != null && target != null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/DeferredSetValueCommand.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/DeferredSetValueCommand.java index a7c5a88cdad..162dfdf8683 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/DeferredSetValueCommand.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/DeferredSetValueCommand.java @@ -1,41 +1,41 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.commands;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.SetDeferredRequest;
-
-public class DeferredSetValueCommand extends org.eclipse.gmf.runtime.emf.type.core.commands.DeferredSetValueCommand {
-
- protected SetDeferredRequest request;
-
- protected EObject elementToEdit;
-
- public DeferredSetValueCommand(SetDeferredRequest request) {
- super(request);
- this.request = request;
- }
-
- @Override
- protected EObject getElementToEdit() {
- if (elementToEdit == null) {
- Object adapter = request.getElementToSet().getAdapter(EObject.class);
- if (adapter instanceof EObject) {
- elementToEdit = (EObject) adapter;
- }
- }
- return elementToEdit;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.commands; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.request.SetDeferredRequest; + +public class DeferredSetValueCommand extends org.eclipse.gmf.runtime.emf.type.core.commands.DeferredSetValueCommand { + + protected SetDeferredRequest request; + + protected EObject elementToEdit; + + public DeferredSetValueCommand(SetDeferredRequest request) { + super(request); + this.request = request; + } + + @Override + protected EObject getElementToEdit() { + if (elementToEdit == null) { + Object adapter = request.getElementToSet().getAdapter(EObject.class); + if (adapter instanceof EObject) { + elementToEdit = (EObject) adapter; + } + } + return elementToEdit; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/RunNotificationCommand.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/RunNotificationCommand.java index 4bd4bd8d660..3f8bfd468d6 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/RunNotificationCommand.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/commands/RunNotificationCommand.java @@ -1,67 +1,67 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.commands;
-
-import java.util.List;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.INotification;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder;
-
-import com.google.common.collect.Lists;
-
-/**
- * Command used to launch a notification
- *
- * @author arthur daussy
- *
- */
-public class RunNotificationCommand extends AbstractTransactionalCommand {
-
- private NotificationBuilder notification;
-
- private static List<INotification> notifs = Lists.newArrayList();
-
- public RunNotificationCommand(TransactionalEditingDomain domain, String label, List affectedFiles, NotificationBuilder notification) {
- super(domain, label, affectedFiles);
- this.notification = notification;
- }
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- /**
- * Clear old notif
- */
- clearOldNotif();
- addNotif(notification.run());
- return CommandResult.newOKCommandResult();
- }
-
- private synchronized void addNotif(INotification notif) {
- notifs.add(notif);
- }
-
- private synchronized void clearOldNotif() {
- for (INotification notif : notifs) {
- notif.delete();
- }
- notifs.clear();
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.commands; + +import java.util.List; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.INotification; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder; + +import com.google.common.collect.Lists; + +/** + * Command used to launch a notification + * + * @author arthur daussy + * + */ +public class RunNotificationCommand extends AbstractTransactionalCommand { + + private NotificationBuilder notification; + + private static List<INotification> notifs = Lists.newArrayList(); + + public RunNotificationCommand(TransactionalEditingDomain domain, String label, List affectedFiles, NotificationBuilder notification) { + super(domain, label, affectedFiles); + this.notification = notification; + } + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + /** + * Clear old notif + */ + clearOldNotif(); + addNotif(notification.run()); + return CommandResult.newOKCommandResult(); + } + + private synchronized void addNotif(INotification notif) { + notifs.add(notif); + } + + private synchronized void clearOldNotif() { + for (INotification notif : notifs) { + notif.delete(); + } + notifs.clear(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/CenteredColumnConstraint.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/CenteredColumnConstraint.java index 2007205942d..e114e310bff 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/CenteredColumnConstraint.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/CenteredColumnConstraint.java @@ -1,37 +1,37 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.draw2d;
-
-/**
- * Constraint to use with {@link CenteredColumnLayout}. Specifies whether figure
- * fills extra space
- */
-public class CenteredColumnConstraint {
-
- private boolean fill;
-
- /**
- * Constructor.
- *
- * @param fillAvailableSpace
- * whether available space is filled by this figure
- */
- public CenteredColumnConstraint(boolean fillAvailableSpace) {
- fill = fillAvailableSpace;
- }
-
- public boolean isAvailableSpaceFilled() {
- return fill;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.draw2d; + +/** + * Constraint to use with {@link CenteredColumnLayout}. Specifies whether figure + * fills extra space + */ +public class CenteredColumnConstraint { + + private boolean fill; + + /** + * Constructor. + * + * @param fillAvailableSpace + * whether available space is filled by this figure + */ + public CenteredColumnConstraint(boolean fillAvailableSpace) { + fill = fillAvailableSpace; + } + + public boolean isAvailableSpaceFilled() { + return fill; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/CenteredColumnLayout.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/CenteredColumnLayout.java index cde12099be1..b514647bfc4 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/CenteredColumnLayout.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/CenteredColumnLayout.java @@ -1,122 +1,122 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.draw2d;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.StackLayout;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.papyrus.uml.diagram.common.draw2d.CenterLayout;
-
-/**
- * This implementation is based on {@link CenterLayout}, except it avoids
- * superposing figures. Elements are centered and placed in a row. Available
- * extra place is dispatched between figures with fill constraint.
- *
- * @see CenteredColumnConstraint
- */
-public class CenteredColumnLayout extends StackLayout {
-
- private static final Rectangle RECTANGLE = new Rectangle();
-
- /** Extra margin (for avoiding cut) */
- private static final int MARGIN = 5;
-
- private Map<IFigure, CenteredColumnConstraint> constraints = new HashMap<IFigure, CenteredColumnConstraint>();
-
- @Override
- public void layout(IFigure figure) {
- Rectangle rect = figure.getClientArea();
- final int centerX = rect.x + rect.width / 2;
- int yAxe = rect.y;
- int availableExtraHeight = rect.height;
- int numberOfFillChildren = 0;
- List<IFigure> orderedFigures = new LinkedList<IFigure>();
- List<?> children = figure.getChildren();
- IFigure child;
- for (int i = 0; i < children.size(); i++) {
- child = (IFigure) children.get(i);
- Dimension prefSize = child.getPreferredSize(-1, -1);
- availableExtraHeight -= prefSize.height + MARGIN;
- if (constraints.get(child) != null && constraints.get(child).isAvailableSpaceFilled()) {
- numberOfFillChildren++;
- }
- if (!constraints.containsKey(child)) {
- constraints.put(child, null);
- }
- orderedFigures.add(i, child);
- }
- int fillExtraHeight = 0;
- if (numberOfFillChildren > 0) {
- fillExtraHeight = availableExtraHeight / numberOfFillChildren;
- }
- for (IFigure childF : orderedFigures) {
- boolean fill = constraints.get(childF).isAvailableSpaceFilled();
- Dimension prefSize = childF.getPreferredSize(-1, -1);
- RECTANGLE.x = centerX - prefSize.width / 2;
- RECTANGLE.y = yAxe;
- RECTANGLE.width = prefSize.width;
- if (!fill) {
- RECTANGLE.height = prefSize.height + MARGIN;
- } else {
- RECTANGLE.height = prefSize.height + MARGIN + fillExtraHeight;
- }
- // Workaround for 209648
- childF.setBounds(RECTANGLE);
- yAxe += RECTANGLE.height;
- }
- }
-
- @Override
- public void setConstraint(IFigure child, Object constraint) {
- if (constraint instanceof CenteredColumnConstraint) {
- constraints.put(child, (CenteredColumnConstraint) constraint);
- }
- super.setConstraint(child, constraint);
- }
-
- @Override
- public Object getConstraint(IFigure child) {
- return constraints.get(child);
- }
-
- @Override
- protected Dimension calculateMinimumSize(IFigure figure, int wHint, int hHint) {
- if (wHint > -1) {
- wHint = Math.max(0, wHint - figure.getInsets().getWidth());
- }
- if (hHint > -1) {
- hHint = Math.max(0, hHint - figure.getInsets().getHeight());
- }
- Dimension d = new Dimension();
- List children = figure.getChildren();
- IFigure child;
- for (int i = 0; i < children.size(); i++) {
- child = (IFigure) children.get(i);
- if (!isObservingVisibility() || child.isVisible()) {
- Dimension childSize = child.getMinimumSize(wHint, hHint);
- d.height += childSize.height;
- d.width = Math.max(d.width, childSize.width);
- }
- }
- d.expand(figure.getInsets().getWidth(), figure.getInsets().getHeight());
- d.union(getBorderPreferredSize(figure));
- return d;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.draw2d; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.StackLayout; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.papyrus.uml.diagram.common.draw2d.CenterLayout; + +/** + * This implementation is based on {@link CenterLayout}, except it avoids + * superposing figures. Elements are centered and placed in a row. Available + * extra place is dispatched between figures with fill constraint. + * + * @see CenteredColumnConstraint + */ +public class CenteredColumnLayout extends StackLayout { + + private static final Rectangle RECTANGLE = new Rectangle(); + + /** Extra margin (for avoiding cut) */ + private static final int MARGIN = 5; + + private Map<IFigure, CenteredColumnConstraint> constraints = new HashMap<IFigure, CenteredColumnConstraint>(); + + @Override + public void layout(IFigure figure) { + Rectangle rect = figure.getClientArea(); + final int centerX = rect.x + rect.width / 2; + int yAxe = rect.y; + int availableExtraHeight = rect.height; + int numberOfFillChildren = 0; + List<IFigure> orderedFigures = new LinkedList<IFigure>(); + List<?> children = figure.getChildren(); + IFigure child; + for (int i = 0; i < children.size(); i++) { + child = (IFigure) children.get(i); + Dimension prefSize = child.getPreferredSize(-1, -1); + availableExtraHeight -= prefSize.height + MARGIN; + if (constraints.get(child) != null && constraints.get(child).isAvailableSpaceFilled()) { + numberOfFillChildren++; + } + if (!constraints.containsKey(child)) { + constraints.put(child, null); + } + orderedFigures.add(i, child); + } + int fillExtraHeight = 0; + if (numberOfFillChildren > 0) { + fillExtraHeight = availableExtraHeight / numberOfFillChildren; + } + for (IFigure childF : orderedFigures) { + boolean fill = constraints.get(childF).isAvailableSpaceFilled(); + Dimension prefSize = childF.getPreferredSize(-1, -1); + RECTANGLE.x = centerX - prefSize.width / 2; + RECTANGLE.y = yAxe; + RECTANGLE.width = prefSize.width; + if (!fill) { + RECTANGLE.height = prefSize.height + MARGIN; + } else { + RECTANGLE.height = prefSize.height + MARGIN + fillExtraHeight; + } + // Workaround for 209648 + childF.setBounds(RECTANGLE); + yAxe += RECTANGLE.height; + } + } + + @Override + public void setConstraint(IFigure child, Object constraint) { + if (constraint instanceof CenteredColumnConstraint) { + constraints.put(child, (CenteredColumnConstraint) constraint); + } + super.setConstraint(child, constraint); + } + + @Override + public Object getConstraint(IFigure child) { + return constraints.get(child); + } + + @Override + protected Dimension calculateMinimumSize(IFigure figure, int wHint, int hHint) { + if (wHint > -1) { + wHint = Math.max(0, wHint - figure.getInsets().getWidth()); + } + if (hHint > -1) { + hHint = Math.max(0, hHint - figure.getInsets().getHeight()); + } + Dimension d = new Dimension(); + List children = figure.getChildren(); + IFigure child; + for (int i = 0; i < children.size(); i++) { + child = (IFigure) children.get(i); + if (!isObservingVisibility() || child.isVisible()) { + Dimension childSize = child.getMinimumSize(wHint, hHint); + d.height += childSize.height; + d.width = Math.max(d.width, childSize.width); + } + } + d.expand(figure.getInsets().getWidth(), figure.getInsets().getHeight()); + d.union(getBorderPreferredSize(figure)); + return d; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/FlowLayoutAdvanced.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/FlowLayoutAdvanced.java index d7a7682d1f6..100095b7a8f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/FlowLayoutAdvanced.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/FlowLayoutAdvanced.java @@ -1,158 +1,158 @@ -/*****************************************************************************
- * Copyright (c) 2011 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.draw2d;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.draw2d.FlowLayout;
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Rectangle;
-
-/**
- * Layout to create a row (or colunm) layout All children will be displayer
- * under the previous one You can add constraint with {@link FlowLayoutAdvancedConstraint}
- *
- * @author arthur daussy - arthur.daussy@atosorigin.com
- *
- */
-public class FlowLayoutAdvanced extends FlowLayout {
-
- /***
- * Orientation of the layout
- *
- * @author adaussy
- *
- */
- public enum Orientation {
- HORIZONTAL, VERTICAL
- }
-
- /**
- * Not implemented yet TODO
- */
- private Orientation orientation = Orientation.VERTICAL;
-
- private Map<IFigure, Object> constraints = new HashMap<IFigure, Object>();
-
- @Override
- protected void setBoundsOfChild(IFigure parent, IFigure child, Rectangle bounds) {
- parent.getClientArea(Rectangle.SINGLETON);
- bounds.translate(Rectangle.SINGLETON.x, Rectangle.SINGLETON.y);
- Dimension childDim = this.getChildSize(child, Rectangle.SINGLETON.width, Rectangle.SINGLETON.height).getCopy();
- bounds.setSize(childDim);
- Object _constraint = getConstraint(child);
- if (_constraint instanceof FlowLayoutAdvancedConstraint) {
- FlowLayoutAdvancedConstraint constraint = (FlowLayoutAdvancedConstraint) _constraint;
- if (constraint != null) {
- if (constraint.isFill()) {
- if (Orientation.VERTICAL.equals(orientation)) {
- bounds.setSize(bounds.getSize().getCopy().width, getAvailableSpaceForFilledElement(child, Rectangle.SINGLETON.getSize().getCopy()).getCopy().height);
- } else {
- bounds.setSize(getAvailableSpaceForFilledElement(child, Rectangle.SINGLETON.getSize().getCopy()).getCopy().width, bounds.getSize().getCopy().height);
- }
- }
- if (constraint.isFull()) {
- bounds.setSize(Rectangle.SINGLETON.getSize().getCopy());
- bounds.setLocation(Rectangle.SINGLETON.getLocation().getCopy());
- }
- }
- }
- child.setBounds(bounds);
- }
-
- @Override
- public Object getConstraint(IFigure child) {
- return constraints.get(child);
- }
-
- /**
- *
- * @see org.eclipse.draw2d.AbstractLayout#setConstraint(org.eclipse.draw2d.IFigure, java.lang.Object) Use this kind of constraint {@link FlowLayoutAdvancedConstraint}
- * @param child
- * @param constraint
- */
- @Override
- public void setConstraint(IFigure child, Object constraint) {
- if (constraint instanceof FlowLayoutAdvancedConstraint || constraint == null) {
- constraints.put(child, constraint);
- }
- }
-
- private Dimension getAvailableSpaceForFilledElement(IFigure currentChild, Dimension parentDim) {
- Set<IFigure> children = constraints.keySet();
- if (children.isEmpty()) {
- throw new RuntimeException("Current layout is not set on any figure");// TODO
- // externalize
- }
- int numberOfFilledElement = 0;
- for (Object _child : children) {
- if (_child instanceof IFigure) {
- IFigure child = (IFigure) _child;
- if (constraints.containsKey(child)) {
- FlowLayoutAdvancedConstraint localConstraint = (FlowLayoutAdvancedConstraint) constraints.get(child);
- if (localConstraint != null && localConstraint.isFill()) {
- numberOfFilledElement++;
- }
- }
- /*
- * TODO set with the orientation attribute
- */
- if (!child.equals(currentChild)) {
- parentDim = parentDim.getShrinked(0, getChildSize(child, Rectangle.SINGLETON.width, Rectangle.SINGLETON.height).height);
- }
- }
- }
- if (Orientation.VERTICAL.equals(orientation)) {
- parentDim.setHeight((int) ((float) parentDim.height / (float) numberOfFilledElement));
- // parentDim.setWidth(0);
- } else {
- parentDim.setWidth((int) ((float) parentDim.width / (float) numberOfFilledElement));
- // parentDim.setHeight(0);
- }
- return parentDim;
- }
-
- public Orientation getOrientation() {
- return orientation;
- }
-
- public void setOrientation(Orientation orientation) {
- this.orientation = orientation;
- }
-
- @Override
- public Dimension getMinimumSize(IFigure container, int w, int h) {
- Dimension minDim = null;
- for (IFigure figure : constraints.keySet()) {
- Object _c = constraints.get(figure);
- if (_c instanceof FlowLayoutAdvancedConstraint) {
- FlowLayoutAdvancedConstraint constraint = (FlowLayoutAdvancedConstraint) _c;
- if (constraint.isHasMinsize()) {
- if (minDim == null) {
- minDim = figure.getMinimumSize();
- } else {
- minDim = Dimension.min(minDim, figure.getMinimumSize());
- }
- }
- }
- }
- if (minDim == null) {
- minDim = new Dimension(0, 0);
- }
- return minDim;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.draw2d; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.eclipse.draw2d.FlowLayout; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Rectangle; + +/** + * Layout to create a row (or colunm) layout All children will be displayer + * under the previous one You can add constraint with {@link FlowLayoutAdvancedConstraint} + * + * @author arthur daussy - arthur.daussy@atosorigin.com + * + */ +public class FlowLayoutAdvanced extends FlowLayout { + + /*** + * Orientation of the layout + * + * @author adaussy + * + */ + public enum Orientation { + HORIZONTAL, VERTICAL + } + + /** + * Not implemented yet TODO + */ + private Orientation orientation = Orientation.VERTICAL; + + private Map<IFigure, Object> constraints = new HashMap<IFigure, Object>(); + + @Override + protected void setBoundsOfChild(IFigure parent, IFigure child, Rectangle bounds) { + parent.getClientArea(Rectangle.SINGLETON); + bounds.translate(Rectangle.SINGLETON.x, Rectangle.SINGLETON.y); + Dimension childDim = this.getChildSize(child, Rectangle.SINGLETON.width, Rectangle.SINGLETON.height).getCopy(); + bounds.setSize(childDim); + Object _constraint = getConstraint(child); + if (_constraint instanceof FlowLayoutAdvancedConstraint) { + FlowLayoutAdvancedConstraint constraint = (FlowLayoutAdvancedConstraint) _constraint; + if (constraint != null) { + if (constraint.isFill()) { + if (Orientation.VERTICAL.equals(orientation)) { + bounds.setSize(bounds.getSize().getCopy().width, getAvailableSpaceForFilledElement(child, Rectangle.SINGLETON.getSize().getCopy()).getCopy().height); + } else { + bounds.setSize(getAvailableSpaceForFilledElement(child, Rectangle.SINGLETON.getSize().getCopy()).getCopy().width, bounds.getSize().getCopy().height); + } + } + if (constraint.isFull()) { + bounds.setSize(Rectangle.SINGLETON.getSize().getCopy()); + bounds.setLocation(Rectangle.SINGLETON.getLocation().getCopy()); + } + } + } + child.setBounds(bounds); + } + + @Override + public Object getConstraint(IFigure child) { + return constraints.get(child); + } + + /** + * + * @see org.eclipse.draw2d.AbstractLayout#setConstraint(org.eclipse.draw2d.IFigure, java.lang.Object) Use this kind of constraint {@link FlowLayoutAdvancedConstraint} + * @param child + * @param constraint + */ + @Override + public void setConstraint(IFigure child, Object constraint) { + if (constraint instanceof FlowLayoutAdvancedConstraint || constraint == null) { + constraints.put(child, constraint); + } + } + + private Dimension getAvailableSpaceForFilledElement(IFigure currentChild, Dimension parentDim) { + Set<IFigure> children = constraints.keySet(); + if (children.isEmpty()) { + throw new RuntimeException("Current layout is not set on any figure");// TODO + // externalize + } + int numberOfFilledElement = 0; + for (Object _child : children) { + if (_child instanceof IFigure) { + IFigure child = (IFigure) _child; + if (constraints.containsKey(child)) { + FlowLayoutAdvancedConstraint localConstraint = (FlowLayoutAdvancedConstraint) constraints.get(child); + if (localConstraint != null && localConstraint.isFill()) { + numberOfFilledElement++; + } + } + /* + * TODO set with the orientation attribute + */ + if (!child.equals(currentChild)) { + parentDim = parentDim.getShrinked(0, getChildSize(child, Rectangle.SINGLETON.width, Rectangle.SINGLETON.height).height); + } + } + } + if (Orientation.VERTICAL.equals(orientation)) { + parentDim.setHeight((int) ((float) parentDim.height / (float) numberOfFilledElement)); + // parentDim.setWidth(0); + } else { + parentDim.setWidth((int) ((float) parentDim.width / (float) numberOfFilledElement)); + // parentDim.setHeight(0); + } + return parentDim; + } + + public Orientation getOrientation() { + return orientation; + } + + public void setOrientation(Orientation orientation) { + this.orientation = orientation; + } + + @Override + public Dimension getMinimumSize(IFigure container, int w, int h) { + Dimension minDim = null; + for (IFigure figure : constraints.keySet()) { + Object _c = constraints.get(figure); + if (_c instanceof FlowLayoutAdvancedConstraint) { + FlowLayoutAdvancedConstraint constraint = (FlowLayoutAdvancedConstraint) _c; + if (constraint.isHasMinsize()) { + if (minDim == null) { + minDim = figure.getMinimumSize(); + } else { + minDim = Dimension.min(minDim, figure.getMinimumSize()); + } + } + } + } + if (minDim == null) { + minDim = new Dimension(0, 0); + } + return minDim; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/FlowLayoutAdvancedConstraint.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/FlowLayoutAdvancedConstraint.java index 34768bb7e3d..d54849b77b6 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/FlowLayoutAdvancedConstraint.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/FlowLayoutAdvancedConstraint.java @@ -1,111 +1,111 @@ -/*****************************************************************************
- * Copyright (c) 2011 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.draw2d;
-
-/**
- * Constraint used for FlowAdvancedLayout
- *
- * @author Arthur Daussy - arthur.daussy@atosorigin.com
- *
- */
-public class FlowLayoutAdvancedConstraint {
-
- /**
- * If true then the figure take all the free space left (divided by the
- * number of fill element (An element is event full or fill)
- */
- private boolean fill;
-
- /**
- * If true then the figure take the same size than the parent (An element is
- * event full or fill)
- */
- private boolean full;
-
- /**
- * Has minimum size
- */
- private boolean hasMinsize;
-
- /**
- *
- * Constructor. Init all contants to false
- */
- public FlowLayoutAdvancedConstraint() {
- super();
- fill = false;
- full = false;
- hasMinsize = false;
- }
-
- /**
- * {@link #fill}
- *
- * @param fill
- */
- public void setFill(boolean fill) {
- if (fill) {
- full = false;
- }
- this.fill = fill;
- }
-
- /**
- * {@link #fill}
- *
- * @return
- */
- public boolean isFull() {
- return full;
- }
-
- /**
- * {@link #full}
- *
- * @param full
- */
- public void setFull(boolean full) {
- if (full) {
- fill = false;
- }
- this.full = full;
- }
-
- /**
- * {@link #full}
- *
- * @return
- */
- public boolean isFill() {
- return fill;
- }
-
- /**
- * {@link #hasMinsize}
- *
- * @return
- */
- public boolean isHasMinsize() {
- return hasMinsize;
- }
-
- /**
- * {@link #hasMinsize}
- *
- * @param hasMinsize
- */
- public void setHasMinsize(boolean hasMinsize) {
- this.hasMinsize = hasMinsize;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.draw2d; + +/** + * Constraint used for FlowAdvancedLayout + * + * @author Arthur Daussy - arthur.daussy@atosorigin.com + * + */ +public class FlowLayoutAdvancedConstraint { + + /** + * If true then the figure take all the free space left (divided by the + * number of fill element (An element is event full or fill) + */ + private boolean fill; + + /** + * If true then the figure take the same size than the parent (An element is + * event full or fill) + */ + private boolean full; + + /** + * Has minimum size + */ + private boolean hasMinsize; + + /** + * + * Constructor. Init all contants to false + */ + public FlowLayoutAdvancedConstraint() { + super(); + fill = false; + full = false; + hasMinsize = false; + } + + /** + * {@link #fill} + * + * @param fill + */ + public void setFill(boolean fill) { + if (fill) { + full = false; + } + this.fill = fill; + } + + /** + * {@link #fill} + * + * @return + */ + public boolean isFull() { + return full; + } + + /** + * {@link #full} + * + * @param full + */ + public void setFull(boolean full) { + if (full) { + fill = false; + } + this.full = full; + } + + /** + * {@link #full} + * + * @return + */ + public boolean isFill() { + return fill; + } + + /** + * {@link #hasMinsize} + * + * @return + */ + public boolean isHasMinsize() { + return hasMinsize; + } + + /** + * {@link #hasMinsize} + * + * @param hasMinsize + */ + public void setHasMinsize(boolean hasMinsize) { + this.hasMinsize = hasMinsize; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/GravityConstrainedFlowLayoutConstraint.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/GravityConstrainedFlowLayoutConstraint.java index effd4533f50..d0323afd05a 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/GravityConstrainedFlowLayoutConstraint.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/draw2d/GravityConstrainedFlowLayoutConstraint.java @@ -1,39 +1,39 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.draw2d;
-
-import org.eclipse.gmf.runtime.draw2d.ui.figures.GravityConstrainedFlowLayout;
-
-/**
- * This class is used to pass a Constraint to a {@link GravityConstrainedFlowLayout}. This is a workaround to allow this
- * constraint in a generate way
- *
- * @author adaussy
- *
- */
-public class GravityConstrainedFlowLayoutConstraint {
-
- /**
- * Constraint use by {@link GravityConstrainedFlowLayout}
- */
- private Integer align = new Integer(GravityConstrainedFlowLayout.ALIGN_TOPLEFT);
-
- public int getAlign() {
- return align;
- }
-
- public void setAlign(int align) {
- this.align = align;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.draw2d; + +import org.eclipse.gmf.runtime.draw2d.ui.figures.GravityConstrainedFlowLayout; + +/** + * This class is used to pass a Constraint to a {@link GravityConstrainedFlowLayout}. This is a workaround to allow this + * constraint in a generate way + * + * @author adaussy + * + */ +public class GravityConstrainedFlowLayoutConstraint { + + /** + * Constraint use by {@link GravityConstrainedFlowLayout} + */ + private Integer align = new Integer(GravityConstrainedFlowLayout.ALIGN_TOPLEFT); + + public int getAlign() { + return align; + } + + public void setAlign(int align) { + this.align = align; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CallBehaviorActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CallBehaviorActionEditHelperAdvice.java index a7f8258a8ec..f4fabb8e2e8 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CallBehaviorActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CallBehaviorActionEditHelperAdvice.java @@ -1,100 +1,100 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- * 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:
- * Remi Schnekenburger (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
-import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallBehaviorActionDialog;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.Behavior;
-import org.eclipse.uml2.uml.CallBehaviorAction;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Edit helper advice for Call Behavior Action, that pops up a dialog during creation
- */
-public class CallBehaviorActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- public static String CALL_BEHAVIOR_ACTION = "CallBehaviorAction";
- public static String POPUP_TYPE = "popupType";
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected ICommand getBeforeConfigureCommand(ConfigureRequest request) {
- // get the activity containing the new element
- Activity parentActivity = null;
- EObject parent = request.getElementToConfigure();
- while (parent != null && parentActivity == null) {
- if (parent instanceof Activity) {
- parentActivity = (Activity) parent;
- }
- parent = parent.eContainer();
- }
- if (CALL_BEHAVIOR_ACTION.equals(request.getParameter(POPUP_TYPE))) {
- CreateCallBehaviorActionDialog dialog = new CreateCallBehaviorActionDialog(Display.getDefault().getActiveShell(), parentActivity, (InvocationAction) request.getElementToConfigure());
- if (IDialogConstants.OK_ID == dialog.open()) {
- // initialize the invoked element (no need to use a command, since action is being created)
- CompositeCommand command = new CompositeCommand("Configure created element");
- IElementEditService service = ElementEditServiceUtils.getCommandProvider(request.getElementToConfigure());
- EObject behavior = dialog.getSelectedInvoked();
- if (behavior instanceof Behavior) {
- SetRequest setBehaviorRequest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior(), behavior);
- command.add(service.getEditCommand(setBehaviorRequest));
- }
- // initialize synchronous
- SetRequest setSynchronousReqest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getCallAction_IsSynchronous(), dialog.getIsSynchronous());
- command.add(service.getEditCommand(setSynchronousReqest));
- return command;
- }
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void configureRequest(IEditCommandRequest request) {
- request.getParameters().put(POPUP_TYPE, CALL_BEHAVIOR_ACTION);
- }
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterSetCommand(SetRequest request) {
- CallBehaviorAction editedModelElement = (CallBehaviorAction)request.getElementToEdit();
- if(request.getFeature()==UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior()){
- IPinUpdater<CallBehaviorAction> updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement);
- return new PinUpdateCommand<CallBehaviorAction>("Update call behavior action pins", updater, editedModelElement);
- }else{
- return null;
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * 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: + * Remi Schnekenburger (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils; +import org.eclipse.papyrus.infra.services.edit.service.IElementEditService; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallBehaviorActionDialog; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.swt.widgets.Display; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.Behavior; +import org.eclipse.uml2.uml.CallBehaviorAction; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Edit helper advice for Call Behavior Action, that pops up a dialog during creation + */ +public class CallBehaviorActionEditHelperAdvice extends AbstractEditHelperAdvice { + + public static String CALL_BEHAVIOR_ACTION = "CallBehaviorAction"; + public static String POPUP_TYPE = "popupType"; + + /** + * {@inheritDoc} + */ + @Override + protected ICommand getBeforeConfigureCommand(ConfigureRequest request) { + // get the activity containing the new element + Activity parentActivity = null; + EObject parent = request.getElementToConfigure(); + while (parent != null && parentActivity == null) { + if (parent instanceof Activity) { + parentActivity = (Activity) parent; + } + parent = parent.eContainer(); + } + if (CALL_BEHAVIOR_ACTION.equals(request.getParameter(POPUP_TYPE))) { + CreateCallBehaviorActionDialog dialog = new CreateCallBehaviorActionDialog(Display.getDefault().getActiveShell(), parentActivity, (InvocationAction) request.getElementToConfigure()); + if (IDialogConstants.OK_ID == dialog.open()) { + // initialize the invoked element (no need to use a command, since action is being created) + CompositeCommand command = new CompositeCommand("Configure created element"); + IElementEditService service = ElementEditServiceUtils.getCommandProvider(request.getElementToConfigure()); + EObject behavior = dialog.getSelectedInvoked(); + if (behavior instanceof Behavior) { + SetRequest setBehaviorRequest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior(), behavior); + command.add(service.getEditCommand(setBehaviorRequest)); + } + // initialize synchronous + SetRequest setSynchronousReqest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getCallAction_IsSynchronous(), dialog.getIsSynchronous()); + command.add(service.getEditCommand(setSynchronousReqest)); + return command; + } + } + return null; + } + + @SuppressWarnings("unchecked") + @Override + public void configureRequest(IEditCommandRequest request) { + request.getParameters().put(POPUP_TYPE, CALL_BEHAVIOR_ACTION); + } + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterSetCommand(SetRequest request) { + CallBehaviorAction editedModelElement = (CallBehaviorAction)request.getElementToEdit(); + if(request.getFeature()==UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior()){ + IPinUpdater<CallBehaviorAction> updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement); + return new PinUpdateCommand<CallBehaviorAction>("Update call behavior action pins", updater, editedModelElement); + }else{ + return null; + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CallOperationActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CallOperationActionEditHelperAdvice.java index dac247e8b07..fbe54c24ca2 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CallOperationActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CallOperationActionEditHelperAdvice.java @@ -1,88 +1,88 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- * 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:
- * Remi Schnekenburger (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
-import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallOperationActionDialog;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.CallOperationAction;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.Operation;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Edit helper advice for {@link CallOperationAction}, that pops up a dialog during creation
- */
-public class CallOperationActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected ICommand getBeforeConfigureCommand(ConfigureRequest request) {
- // get the activity containing the new element
- Activity parentActivity = null;
- EObject parent = request.getElementToConfigure();
- while (parent != null && parentActivity == null) {
- if (parent instanceof Activity) {
- parentActivity = (Activity) parent;
- }
- parent = parent.eContainer();
- }
- CreateCallOperationActionDialog dialog = new CreateCallOperationActionDialog(Display.getDefault().getActiveShell(), parentActivity, (InvocationAction) request.getElementToConfigure());
- if (IDialogConstants.OK_ID == dialog.open()) {
- // initialize the invoked element (no need to use a command, since action is being created)
- CompositeCommand command = new CompositeCommand("Configure created element");
- IElementEditService service = ElementEditServiceUtils.getCommandProvider(request.getElementToConfigure());
- EObject operation = dialog.getSelectedInvoked();
- if (operation instanceof Operation) {
- SetRequest setOperationRequest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getCallOperationAction_Operation(), operation);
- command.add(service.getEditCommand(setOperationRequest));
- }
- // initialize synchronous
- SetRequest setSynchronousReqest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getCallAction_IsSynchronous(), dialog.getIsSynchronous());
- command.add(service.getEditCommand(setSynchronousReqest));
- return command;
- }
- return null;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterSetCommand(SetRequest request) {
- CallOperationAction editedModelElement = (CallOperationAction) request.getElementToEdit();
- if(request.getFeature()==UMLPackage.eINSTANCE.getCallOperationAction_Operation()){
- IPinUpdater<CallOperationAction> updater =PinUpdaterFactory.getInstance().instantiate(editedModelElement);
- return new PinUpdateCommand<CallOperationAction>("Update call operation action pins", updater, editedModelElement);
- }else{
- return null;
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * 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: + * Remi Schnekenburger (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils; +import org.eclipse.papyrus.infra.services.edit.service.IElementEditService; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallOperationActionDialog; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.swt.widgets.Display; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.CallOperationAction; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.Operation; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Edit helper advice for {@link CallOperationAction}, that pops up a dialog during creation + */ +public class CallOperationActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * {@inheritDoc} + */ + @Override + protected ICommand getBeforeConfigureCommand(ConfigureRequest request) { + // get the activity containing the new element + Activity parentActivity = null; + EObject parent = request.getElementToConfigure(); + while (parent != null && parentActivity == null) { + if (parent instanceof Activity) { + parentActivity = (Activity) parent; + } + parent = parent.eContainer(); + } + CreateCallOperationActionDialog dialog = new CreateCallOperationActionDialog(Display.getDefault().getActiveShell(), parentActivity, (InvocationAction) request.getElementToConfigure()); + if (IDialogConstants.OK_ID == dialog.open()) { + // initialize the invoked element (no need to use a command, since action is being created) + CompositeCommand command = new CompositeCommand("Configure created element"); + IElementEditService service = ElementEditServiceUtils.getCommandProvider(request.getElementToConfigure()); + EObject operation = dialog.getSelectedInvoked(); + if (operation instanceof Operation) { + SetRequest setOperationRequest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getCallOperationAction_Operation(), operation); + command.add(service.getEditCommand(setOperationRequest)); + } + // initialize synchronous + SetRequest setSynchronousReqest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getCallAction_IsSynchronous(), dialog.getIsSynchronous()); + command.add(service.getEditCommand(setSynchronousReqest)); + return command; + } + return null; + } + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterSetCommand(SetRequest request) { + CallOperationAction editedModelElement = (CallOperationAction) request.getElementToEdit(); + if(request.getFeature()==UMLPackage.eINSTANCE.getCallOperationAction_Operation()){ + IPinUpdater<CallOperationAction> updater =PinUpdaterFactory.getInstance().instantiate(editedModelElement); + return new PinUpdateCommand<CallOperationAction>("Update call operation action pins", updater, editedModelElement); + }else{ + return null; + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CreateObjectActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CreateObjectActionEditHelperAdvice.java index 649e25d7a72..5e20227324a 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CreateObjectActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/CreateObjectActionEditHelperAdvice.java @@ -1,86 +1,86 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.uml2.uml.CreateObjectAction;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- *
- * Pins of CreateObjectAction should be create and update automatically
- * @since 3.0
- *
- */
-public class CreateObjectActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterSetCommand(SetRequest request) {
- // 1] check if the setFeature is classifier
- if (request.getFeature().equals(UMLPackage.eINSTANCE.getCreateObjectAction_Classifier())) {
- // 2] get the preference for CreateObjectAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.CREATE_OBJECT_ACTION_ACCELERATOR).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 3] check preference
- if (synchronizePin) {
- CreateObjectAction createObjectAction = (CreateObjectAction) request.getElementToEdit();
- if(createObjectAction != null && request.getFeature() == UMLPackage.eINSTANCE.getCreateObjectAction_Classifier()){
- // 4] call the command for the CreateObjectAction
- return new PinUpdateCommand<CreateObjectAction>("Update create object action pins", //$NON-NLS-1$
- PinUpdaterFactory.getInstance().instantiate(createObjectAction), createObjectAction);
- }
- }
- }
- return null;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getBeforeConfigureCommand(ConfigureRequest request) {
- // 1] get the preference for CreateObjectAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.CREATE_OBJECT_ACTION_ACCELERATOR).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 2] check preference
- if (synchronizePin) {
- CreateObjectAction createObjectAction = (CreateObjectAction) request.getElementToConfigure();
- if(createObjectAction != null){
- // 3] call the command for the CreateObjectAction
- return new PinUpdateCommand<CreateObjectAction>("Update create object action pins", //$NON-NLS-1$
- PinUpdaterFactory.getInstance().instantiate(createObjectAction), createObjectAction);
- }
- }
- return null;
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.uml2.uml.CreateObjectAction; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * + * Pins of CreateObjectAction should be create and update automatically + * @since 3.0 + * + */ +public class CreateObjectActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterSetCommand(SetRequest request) { + // 1] check if the setFeature is classifier + if (request.getFeature().equals(UMLPackage.eINSTANCE.getCreateObjectAction_Classifier())) { + // 2] get the preference for CreateObjectAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.CREATE_OBJECT_ACTION_ACCELERATOR).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 3] check preference + if (synchronizePin) { + CreateObjectAction createObjectAction = (CreateObjectAction) request.getElementToEdit(); + if(createObjectAction != null && request.getFeature() == UMLPackage.eINSTANCE.getCreateObjectAction_Classifier()){ + // 4] call the command for the CreateObjectAction + return new PinUpdateCommand<CreateObjectAction>("Update create object action pins", //$NON-NLS-1$ + PinUpdaterFactory.getInstance().instantiate(createObjectAction), createObjectAction); + } + } + } + return null; + } + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getBeforeConfigureCommand(ConfigureRequest request) { + // 1] get the preference for CreateObjectAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.CREATE_OBJECT_ACTION_ACCELERATOR).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 2] check preference + if (synchronizePin) { + CreateObjectAction createObjectAction = (CreateObjectAction) request.getElementToConfigure(); + if(createObjectAction != null){ + // 3] call the command for the CreateObjectAction + return new PinUpdateCommand<CreateObjectAction>("Update create object action pins", //$NON-NLS-1$ + PinUpdaterFactory.getInstance().instantiate(createObjectAction), createObjectAction); + } + } + return null; + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/InputPinStartObjectBehaviorActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/InputPinStartObjectBehaviorActionEditHelperAdvice.java index 7f7d0e5c0f9..c7d53076968 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/InputPinStartObjectBehaviorActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/InputPinStartObjectBehaviorActionEditHelperAdvice.java @@ -1,67 +1,67 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- * 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:
- * (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-/**
- *
- * Pins of StartObjectBehaviorAction should be create and update automatically
- *
- */
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.StartObjectBehaviorActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.uml2.uml.InputPin;
-import org.eclipse.uml2.uml.StartObjectBehaviorAction;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Edit helper advice for {@link StartObjectBehaviorAction}
- * @since 3.0
- */
-public class InputPinStartObjectBehaviorActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterSetCommand(SetRequest request) {
- // 1] check if the setFeature is type
- if (request.getFeature().equals(UMLPackage.eINSTANCE.getTypedElement_Type())) {
- // 2] get the preference for StartObjectBehaviorAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.START_OBJECT_BEHAVIOR_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 3] check preference
- if (synchronizePin) {
- if (request.getElementToEdit() instanceof InputPin) {
- InputPin inputPin = (InputPin) request.getElementToEdit();
- if (inputPin.getOwner() instanceof StartObjectBehaviorAction) {
- // 4] call the command for the StartObjectBehaviorAction which owned the current input pin
- IPinUpdater<StartObjectBehaviorAction> updater = new StartObjectBehaviorActionPinUpdater();
- return new PinUpdateCommand<StartObjectBehaviorAction>("Update start object behavior action pins", updater, (StartObjectBehaviorAction) inputPin.getOwner());
- }
- }
- }
- }
- return super.getAfterSetCommand(request);
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * 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: + * (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +/** + * + * Pins of StartObjectBehaviorAction should be create and update automatically + * + */ +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.StartObjectBehaviorActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.uml2.uml.InputPin; +import org.eclipse.uml2.uml.StartObjectBehaviorAction; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Edit helper advice for {@link StartObjectBehaviorAction} + * @since 3.0 + */ +public class InputPinStartObjectBehaviorActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterSetCommand(SetRequest request) { + // 1] check if the setFeature is type + if (request.getFeature().equals(UMLPackage.eINSTANCE.getTypedElement_Type())) { + // 2] get the preference for StartObjectBehaviorAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.START_OBJECT_BEHAVIOR_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 3] check preference + if (synchronizePin) { + if (request.getElementToEdit() instanceof InputPin) { + InputPin inputPin = (InputPin) request.getElementToEdit(); + if (inputPin.getOwner() instanceof StartObjectBehaviorAction) { + // 4] call the command for the StartObjectBehaviorAction which owned the current input pin + IPinUpdater<StartObjectBehaviorAction> updater = new StartObjectBehaviorActionPinUpdater(); + return new PinUpdateCommand<StartObjectBehaviorAction>("Update start object behavior action pins", updater, (StartObjectBehaviorAction) inputPin.getOwner()); + } + } + } + } + return super.getAfterSetCommand(request); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/ReadSelfActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/ReadSelfActionEditHelperAdvice.java index e10e20d0bdf..b451e4ea7b2 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/ReadSelfActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/ReadSelfActionEditHelperAdvice.java @@ -1,57 +1,57 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- * 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:
- * (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.uml2.uml.ReadSelfAction;
-
-/**
- *
- * Pin of ReadSelfAction should be create and update automatically
- * @since 3.0
- *
- */
-public class ReadSelfActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterConfigureCommand(ConfigureRequest request) {
- // 1] get the preference for ReadSelfAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.READ_SELF_ACTION_ACCELERATOR).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 2] check preference
- if (synchronizePin) {
- ReadSelfAction editedModelElement = (ReadSelfAction) request.getElementToConfigure();
- if (editedModelElement != null) {
- // 3] call the command for the ReadSelfAction
- IPinUpdater<ReadSelfAction> updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement);
- return new PinUpdateCommand<ReadSelfAction>("Update read self action pins", updater, editedModelElement);
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * 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: + * (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.uml2.uml.ReadSelfAction; + +/** + * + * Pin of ReadSelfAction should be create and update automatically + * @since 3.0 + * + */ +public class ReadSelfActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterConfigureCommand(ConfigureRequest request) { + // 1] get the preference for ReadSelfAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.READ_SELF_ACTION_ACCELERATOR).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 2] check preference + if (synchronizePin) { + ReadSelfAction editedModelElement = (ReadSelfAction) request.getElementToConfigure(); + if (editedModelElement != null) { + // 3] call the command for the ReadSelfAction + IPinUpdater<ReadSelfAction> updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement); + return new PinUpdateCommand<ReadSelfAction>("Update read self action pins", updater, editedModelElement); + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/SendSignalActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/SendSignalActionEditHelperAdvice.java index 1cb94f12d1e..3dac4db3a52 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/SendSignalActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/SendSignalActionEditHelperAdvice.java @@ -1,88 +1,88 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- * 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:
- * Remi Schnekenburger (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils;
-import org.eclipse.papyrus.infra.services.edit.service.IElementEditService;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateSendSignalActionDialog;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.SendSignalAction;
-import org.eclipse.uml2.uml.Signal;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Edit helper advice for {@link SendSignalAction}, that pops up a dialog during creation
- */
-public class SendSignalActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected ICommand getBeforeConfigureCommand(ConfigureRequest request) {
- // get the activity containing the new element
- Activity parentActivity = null;
- EObject parent = request.getElementToConfigure();
- while (parent != null && parentActivity == null) {
- if (parent instanceof Activity) {
- parentActivity = (Activity) parent;
- }
- parent = parent.eContainer();
- }
- CreateSendSignalActionDialog dialog = new CreateSendSignalActionDialog(Display.getDefault().getActiveShell(), parentActivity, (InvocationAction) request.getElementToConfigure());
- if (IDialogConstants.OK_ID == dialog.open()) {
- // initialize the invoked element (no need to use a command, since action is being created)
- CompositeCommand command = new CompositeCommand("Configure created element");
- IElementEditService service = ElementEditServiceUtils.getCommandProvider(request.getElementToConfigure());
- EObject signal = dialog.getSelectedInvoked();
- if (signal instanceof Signal) {
- SetRequest setSignalRequest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getSendSignalAction_Signal(), signal);
- command.add(service.getEditCommand(setSignalRequest));
- // initialize the action name with the signal
- SetRequest setNameRequest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getNamedElement_Name(), "Send".concat(((Signal) signal).getName()));
- command.add(service.getEditCommand(setNameRequest));
- }
- return command;
- }
- return null;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterSetCommand(SetRequest request) {
- SendSignalAction editedModelElement = (SendSignalAction) request.getElementToEdit();
- if(request.getFeature()==UMLPackage.eINSTANCE.getSendSignalAction_Signal()){
- IPinUpdater<SendSignalAction > updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement);
- return new PinUpdateCommand<SendSignalAction>("Update send signal action pins", updater, editedModelElement);
- }else{
- return null;
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * 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: + * Remi Schnekenburger (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.papyrus.infra.services.edit.service.ElementEditServiceUtils; +import org.eclipse.papyrus.infra.services.edit.service.IElementEditService; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateSendSignalActionDialog; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.swt.widgets.Display; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.SendSignalAction; +import org.eclipse.uml2.uml.Signal; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Edit helper advice for {@link SendSignalAction}, that pops up a dialog during creation + */ +public class SendSignalActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * {@inheritDoc} + */ + @Override + protected ICommand getBeforeConfigureCommand(ConfigureRequest request) { + // get the activity containing the new element + Activity parentActivity = null; + EObject parent = request.getElementToConfigure(); + while (parent != null && parentActivity == null) { + if (parent instanceof Activity) { + parentActivity = (Activity) parent; + } + parent = parent.eContainer(); + } + CreateSendSignalActionDialog dialog = new CreateSendSignalActionDialog(Display.getDefault().getActiveShell(), parentActivity, (InvocationAction) request.getElementToConfigure()); + if (IDialogConstants.OK_ID == dialog.open()) { + // initialize the invoked element (no need to use a command, since action is being created) + CompositeCommand command = new CompositeCommand("Configure created element"); + IElementEditService service = ElementEditServiceUtils.getCommandProvider(request.getElementToConfigure()); + EObject signal = dialog.getSelectedInvoked(); + if (signal instanceof Signal) { + SetRequest setSignalRequest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getSendSignalAction_Signal(), signal); + command.add(service.getEditCommand(setSignalRequest)); + // initialize the action name with the signal + SetRequest setNameRequest = new SetRequest(request.getElementToConfigure(), UMLPackage.eINSTANCE.getNamedElement_Name(), "Send".concat(((Signal) signal).getName())); + command.add(service.getEditCommand(setNameRequest)); + } + return command; + } + return null; + } + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterSetCommand(SetRequest request) { + SendSignalAction editedModelElement = (SendSignalAction) request.getElementToEdit(); + if(request.getFeature()==UMLPackage.eINSTANCE.getSendSignalAction_Signal()){ + IPinUpdater<SendSignalAction > updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement); + return new PinUpdateCommand<SendSignalAction>("Update send signal action pins", updater, editedModelElement); + }else{ + return null; + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/StartClassifierBehaviorActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/StartClassifierBehaviorActionEditHelperAdvice.java index bdd5fa0a8c3..bbef7930940 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/StartClassifierBehaviorActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/StartClassifierBehaviorActionEditHelperAdvice.java @@ -1,60 +1,60 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.uml2.uml.StartClassifierBehaviorAction;
-
-/**
- *
- * Pin of StartClassifierBehaviorAction should be create and update automatically
- * @since 3.0
- *
- */
-public class StartClassifierBehaviorActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getBeforeConfigureCommand(ConfigureRequest request) {
- // 1] get the preference for StartClassifierBehaviorAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.START_CLASSIFIER_BEHAVIOR_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 2] check preference
- if (synchronizePin) {
- StartClassifierBehaviorAction startClassifierBehaviorAction = (StartClassifierBehaviorAction) request.getElementToConfigure();
- if (startClassifierBehaviorAction != null) {
- // 3] call the command for the StartClassifierBehaviorAction
- IPinUpdater<StartClassifierBehaviorAction> updater = PinUpdaterFactory.getInstance().instantiate(startClassifierBehaviorAction);
- return new PinUpdateCommand<StartClassifierBehaviorAction>("Update pins of start classifier behavior action", //$NON-NLS-1$
- updater, startClassifierBehaviorAction);
- }
- }
- return null;
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.uml2.uml.StartClassifierBehaviorAction; + +/** + * + * Pin of StartClassifierBehaviorAction should be create and update automatically + * @since 3.0 + * + */ +public class StartClassifierBehaviorActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getBeforeConfigureCommand(ConfigureRequest request) { + // 1] get the preference for StartClassifierBehaviorAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.START_CLASSIFIER_BEHAVIOR_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 2] check preference + if (synchronizePin) { + StartClassifierBehaviorAction startClassifierBehaviorAction = (StartClassifierBehaviorAction) request.getElementToConfigure(); + if (startClassifierBehaviorAction != null) { + // 3] call the command for the StartClassifierBehaviorAction + IPinUpdater<StartClassifierBehaviorAction> updater = PinUpdaterFactory.getInstance().instantiate(startClassifierBehaviorAction); + return new PinUpdateCommand<StartClassifierBehaviorAction>("Update pins of start classifier behavior action", //$NON-NLS-1$ + updater, startClassifierBehaviorAction); + } + } + return null; + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/StartObjectBehaviorActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/StartObjectBehaviorActionEditHelperAdvice.java index d2b9d4d0cbd..d459e19ba05 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/StartObjectBehaviorActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/StartObjectBehaviorActionEditHelperAdvice.java @@ -1,83 +1,83 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- * 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:
- * (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.uml2.uml.StartObjectBehaviorAction;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- *
- * Pins of StartObjectBehaviorAction should be create and update automatically
- * @since 3.0
- *
- */
-public class StartObjectBehaviorActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected ICommand getAfterConfigureCommand(ConfigureRequest request) {
- // 1] get the preference for StartObjectBehaviorAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.START_OBJECT_BEHAVIOR_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 2] check preference
- if (synchronizePin) {
- StartObjectBehaviorAction editedModelElement = (StartObjectBehaviorAction) request.getElementToConfigure();
- if (editedModelElement != null) {
- // 3] call the command for the StartObjectBehaviorAction
- IPinUpdater<StartObjectBehaviorAction> updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement);
- return new PinUpdateCommand<StartObjectBehaviorAction>("Update start object behavior action pins", updater, editedModelElement); //$NON-NLS-1$
- }
- }
- return null;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterSetCommand(SetRequest request) {
- // 1] check if the setFeature is object
- if (request.getFeature().equals(UMLPackage.eINSTANCE.getStartObjectBehaviorAction_Object()) ||
- request.getFeature().equals(UMLPackage.eINSTANCE.getCallAction_IsSynchronous())) {
- // 2] get the preference for StartObjectBehaviorAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.START_OBJECT_BEHAVIOR_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 3] check preference
- if (synchronizePin) {
- StartObjectBehaviorAction editedModelElement = (StartObjectBehaviorAction) request.getElementToEdit();
- if (editedModelElement != null) {
- // 4] call the command for the StartObjectBehaviorAction
- IPinUpdater<StartObjectBehaviorAction> updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement);
- return new PinUpdateCommand<StartObjectBehaviorAction>("Update start object behavior action pins", updater, editedModelElement); //$NON-NLS-1$
- }
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * 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: + * (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.uml2.uml.StartObjectBehaviorAction; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * + * Pins of StartObjectBehaviorAction should be create and update automatically + * @since 3.0 + * + */ +public class StartObjectBehaviorActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * {@inheritDoc} + */ + @Override + protected ICommand getAfterConfigureCommand(ConfigureRequest request) { + // 1] get the preference for StartObjectBehaviorAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.START_OBJECT_BEHAVIOR_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 2] check preference + if (synchronizePin) { + StartObjectBehaviorAction editedModelElement = (StartObjectBehaviorAction) request.getElementToConfigure(); + if (editedModelElement != null) { + // 3] call the command for the StartObjectBehaviorAction + IPinUpdater<StartObjectBehaviorAction> updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement); + return new PinUpdateCommand<StartObjectBehaviorAction>("Update start object behavior action pins", updater, editedModelElement); //$NON-NLS-1$ + } + } + return null; + } + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterSetCommand(SetRequest request) { + // 1] check if the setFeature is object + if (request.getFeature().equals(UMLPackage.eINSTANCE.getStartObjectBehaviorAction_Object()) || + request.getFeature().equals(UMLPackage.eINSTANCE.getCallAction_IsSynchronous())) { + // 2] get the preference for StartObjectBehaviorAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.START_OBJECT_BEHAVIOR_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 3] check preference + if (synchronizePin) { + StartObjectBehaviorAction editedModelElement = (StartObjectBehaviorAction) request.getElementToEdit(); + if (editedModelElement != null) { + // 4] call the command for the StartObjectBehaviorAction + IPinUpdater<StartObjectBehaviorAction> updater = PinUpdaterFactory.getInstance().instantiate(editedModelElement); + return new PinUpdateCommand<StartObjectBehaviorAction>("Update start object behavior action pins", updater, editedModelElement); //$NON-NLS-1$ + } + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/TestIdentityActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/TestIdentityActionEditHelperAdvice.java index 3e001542bb1..ca349e1b44f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/TestIdentityActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/TestIdentityActionEditHelperAdvice.java @@ -1,81 +1,81 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- * 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:
- * Remi Schnekenburger (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.ImportUMLPrimitiveTypePackageCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.UpdaterPinUtils;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.papyrus.uml.tools.utils.PackageUtil;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Package;
-import org.eclipse.uml2.uml.TestIdentityAction;
-
-/**
- *
- * Pins of TestIdentityAction should be create automatically
- * @since 3.0
- *
- */
-public class TestIdentityActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected ICommand getAfterConfigureCommand(ConfigureRequest request) {
- // 1] get the preference for TestIdentityAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.TEST_IDENTITY_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 2] check preference
- if (synchronizePin) {
- TestIdentityAction testIdentityAction = (TestIdentityAction) request.getElementToConfigure();
- if (testIdentityAction != null) {
- // 3] call the command for the TestIdentityAction
- IPinUpdater<TestIdentityAction> updater = PinUpdaterFactory.getInstance().instantiate(testIdentityAction);
- return new PinUpdateCommand<TestIdentityAction>("Update test identity action pins", updater, testIdentityAction); //$NON-NLS-1$
- }
- }
- return null;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getBeforeConfigureCommand(ConfigureRequest request) {
- // 1] get the preference for TestIdentityAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.TEST_IDENTITY_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 2] check preference
- if (synchronizePin) {
- Package root = PackageUtil.getRootPackage((Element) request.getElementToConfigure());
- if (!UpdaterPinUtils.isPrimitiveTypeLibraryImported(root)) {
- // 3] call the command to import UML primitive types package
- return new ImportUMLPrimitiveTypePackageCommand("Import UML primitive type package", root); //$NON-NLS-1$
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * 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: + * Remi Schnekenburger (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.ImportUMLPrimitiveTypePackageCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.UpdaterPinUtils; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.papyrus.uml.tools.utils.PackageUtil; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Package; +import org.eclipse.uml2.uml.TestIdentityAction; + +/** + * + * Pins of TestIdentityAction should be create automatically + * @since 3.0 + * + */ +public class TestIdentityActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * {@inheritDoc} + */ + @Override + protected ICommand getAfterConfigureCommand(ConfigureRequest request) { + // 1] get the preference for TestIdentityAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.TEST_IDENTITY_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 2] check preference + if (synchronizePin) { + TestIdentityAction testIdentityAction = (TestIdentityAction) request.getElementToConfigure(); + if (testIdentityAction != null) { + // 3] call the command for the TestIdentityAction + IPinUpdater<TestIdentityAction> updater = PinUpdaterFactory.getInstance().instantiate(testIdentityAction); + return new PinUpdateCommand<TestIdentityAction>("Update test identity action pins", updater, testIdentityAction); //$NON-NLS-1$ + } + } + return null; + } + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getBeforeConfigureCommand(ConfigureRequest request) { + // 1] get the preference for TestIdentityAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.TEST_IDENTITY_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 2] check preference + if (synchronizePin) { + Package root = PackageUtil.getRootPackage((Element) request.getElementToConfigure()); + if (!UpdaterPinUtils.isPrimitiveTypeLibraryImported(root)) { + // 3] call the command to import UML primitive types package + return new ImportUMLPrimitiveTypePackageCommand("Import UML primitive type package", root); //$NON-NLS-1$ + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/ValueSpecificationActionEditHelperAdvice.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/ValueSpecificationActionEditHelperAdvice.java index f73f81be564..5db48559f4d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/ValueSpecificationActionEditHelperAdvice.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/advices/ValueSpecificationActionEditHelperAdvice.java @@ -1,113 +1,113 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.advices;
-
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice;
-import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.ImportUMLPrimitiveTypePackageCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.UpdaterPinUtils;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.papyrus.uml.tools.utils.PackageUtil;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Package;
-import org.eclipse.uml2.uml.UMLPackage;
-import org.eclipse.uml2.uml.ValueSpecificationAction;
-
-/**
- *
- * Pin of ValueSpecificationAction should be create and update automatically
- * @since 3.0
- *
- */
-public class ValueSpecificationActionEditHelperAdvice extends AbstractEditHelperAdvice {
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getBeforeConfigureCommand(ConfigureRequest request) {
- // 1] get the preference for ValueSpecificationAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.VALUE_SPECIFICATION_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 2] check preference
- if (synchronizePin) {
- Package root = PackageUtil.getRootPackage((Element) request.getElementToConfigure());
- if (!UpdaterPinUtils.isPrimitiveTypeLibraryImported(root)) {
- // 3] call the command to import the UML primitive types package
- return new ImportUMLPrimitiveTypePackageCommand("Import UML primitive type package", root); //$NON-NLS-1$
- }
- }
-
- return null;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterSetCommand(SetRequest request) {
- // 1] check if the setFeature is value
- if (request.getFeature().equals(UMLPackage.eINSTANCE.getValueSpecificationAction_Value())) {
- // 2] get the preference for ValueSpecificationAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.VALUE_SPECIFICATION_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 3] check preference
- if (synchronizePin) {
- ValueSpecificationAction valueSpecificationAction = (ValueSpecificationAction) request.getElementToEdit();
- if (valueSpecificationAction != null && request.getFeature() == UMLPackage.eINSTANCE.getValueSpecificationAction_Value()) {
- // 4] call the command for the ValueSpecificationAction
- IPinUpdater<ValueSpecificationAction> updater = PinUpdaterFactory.getInstance().instantiate(valueSpecificationAction);
- return new PinUpdateCommand<ValueSpecificationAction>("Update value specification action pins", updater, valueSpecificationAction); //$NON-NLS-1$
- }
- }
- }
- return null;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest)
- *
- * @param request
- * @return
- */
- @Override
- protected ICommand getAfterConfigureCommand(ConfigureRequest request) {
- // 1] get the preference for ValueSpecificationAction
- final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore();
- boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.VALUE_SPECIFICATION_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION));
- // 2] check preference
- if (synchronizePin) {
- ValueSpecificationAction valueSpecificationAction = (ValueSpecificationAction) request.getElementToConfigure();
- if (valueSpecificationAction != null) {
- // 3] call the command for the ValueSpecificationAction
- return new PinUpdateCommand<ValueSpecificationAction>("Update value specification action pins", PinUpdaterFactory.getInstance().instantiate(valueSpecificationAction), valueSpecificationAction); //$NON-NLS-1$
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.advices; + +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice; +import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.ImportUMLPrimitiveTypePackageCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.util.PinUpdateCommand; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.PinUpdaterFactory; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.UpdaterPinUtils; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.IAutomatedModelCompletionPreferencesConstants; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.papyrus.uml.tools.utils.PackageUtil; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Package; +import org.eclipse.uml2.uml.UMLPackage; +import org.eclipse.uml2.uml.ValueSpecificationAction; + +/** + * + * Pin of ValueSpecificationAction should be create and update automatically + * @since 3.0 + * + */ +public class ValueSpecificationActionEditHelperAdvice extends AbstractEditHelperAdvice { + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getBeforeSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getBeforeConfigureCommand(ConfigureRequest request) { + // 1] get the preference for ValueSpecificationAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.VALUE_SPECIFICATION_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 2] check preference + if (synchronizePin) { + Package root = PackageUtil.getRootPackage((Element) request.getElementToConfigure()); + if (!UpdaterPinUtils.isPrimitiveTypeLibraryImported(root)) { + // 3] call the command to import the UML primitive types package + return new ImportUMLPrimitiveTypePackageCommand("Import UML primitive type package", root); //$NON-NLS-1$ + } + } + + return null; + } + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterSetCommand(org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterSetCommand(SetRequest request) { + // 1] check if the setFeature is value + if (request.getFeature().equals(UMLPackage.eINSTANCE.getValueSpecificationAction_Value())) { + // 2] get the preference for ValueSpecificationAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.VALUE_SPECIFICATION_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 3] check preference + if (synchronizePin) { + ValueSpecificationAction valueSpecificationAction = (ValueSpecificationAction) request.getElementToEdit(); + if (valueSpecificationAction != null && request.getFeature() == UMLPackage.eINSTANCE.getValueSpecificationAction_Value()) { + // 4] call the command for the ValueSpecificationAction + IPinUpdater<ValueSpecificationAction> updater = PinUpdaterFactory.getInstance().instantiate(valueSpecificationAction); + return new PinUpdateCommand<ValueSpecificationAction>("Update value specification action pins", updater, valueSpecificationAction); //$NON-NLS-1$ + } + } + } + return null; + } + + /** + * @see org.eclipse.gmf.runtime.emf.type.core.edithelper.AbstractEditHelperAdvice#getAfterConfigureCommand(org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest) + * + * @param request + * @return + */ + @Override + protected ICommand getAfterConfigureCommand(ConfigureRequest request) { + // 1] get the preference for ValueSpecificationAction + final IPreferenceStore prefStore = Activator.getDefault().getPreferenceStore(); + boolean synchronizePin = (prefStore.getString(IAutomatedModelCompletionPreferencesConstants.VALUE_SPECIFICATION_ACTION).equals(AutomatedModelCompletionPreferencesInitializer.PIN_SYNCHRONIZATION)); + // 2] check preference + if (synchronizePin) { + ValueSpecificationAction valueSpecificationAction = (ValueSpecificationAction) request.getElementToConfigure(); + if (valueSpecificationAction != null) { + // 3] call the command for the ValueSpecificationAction + return new PinUpdateCommand<ValueSpecificationAction>("Update value specification action pins", PinUpdaterFactory.getInstance().instantiate(valueSpecificationAction), valueSpecificationAction); //$NON-NLS-1$ + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/ActivityNodeCreateCommand.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/ActivityNodeCreateCommand.java index 4438ebbd0f7..d7c36e9f72c 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/ActivityNodeCreateCommand.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/ActivityNodeCreateCommand.java @@ -1,58 +1,58 @@ -package org.eclipse.papyrus.uml.diagram.activity.edit.commands;
-
-import java.util.Collections;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.emf.common.command.Command;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.edit.command.CreateChildCommand;
-import org.eclipse.gmf.runtime.emf.core.util.PackageUtil;
-import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand;
-import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest;
-import org.eclipse.uml2.uml.Element;
-
-/**
- * initialize the emf command that will add the child element
- * it call the emf command written in the uml plugin. So it called specific code to add nodes into
- * an Activity
- *
- */
-public abstract class ActivityNodeCreateCommand extends EditElementCommand {
-
- protected Command emfcmd;
-
- public ActivityNodeCreateCommand(String label, EObject elementToEdit, IEditCommandRequest request) {
- super(label, elementToEdit, request);
- }
-
- /**
- * initialize the emf command that will add the child element
- *
- * @return the created child
- */
- protected Element initAndExecuteEmfCommand(Element newElement) throws ExecutionException {
- EReference containmentFeature = PackageUtil.findFeature(getElementToEdit().eClass(), newElement.eClass());
- emfcmd = new CreateChildCommand(getEditingDomain(), getElementToEdit(), containmentFeature, newElement, Collections.EMPTY_LIST);
- emfcmd.canExecute();
- emfcmd.execute();
-
- return newElement;
- }
-
- @Override
- protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- emfcmd.undo();
- return super.doUndo(monitor, info);
- }
-
- @Override
- protected IStatus doRedo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- IStatus status = super.doRedo(monitor, info);
- emfcmd.redo();
- return status;
- }
-}
+package org.eclipse.papyrus.uml.diagram.activity.edit.commands; + +import java.util.Collections; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.edit.command.CreateChildCommand; +import org.eclipse.gmf.runtime.emf.core.util.PackageUtil; +import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; +import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest; +import org.eclipse.uml2.uml.Element; + +/** + * initialize the emf command that will add the child element + * it call the emf command written in the uml plugin. So it called specific code to add nodes into + * an Activity + * + */ +public abstract class ActivityNodeCreateCommand extends EditElementCommand { + + protected Command emfcmd; + + public ActivityNodeCreateCommand(String label, EObject elementToEdit, IEditCommandRequest request) { + super(label, elementToEdit, request); + } + + /** + * initialize the emf command that will add the child element + * + * @return the created child + */ + protected Element initAndExecuteEmfCommand(Element newElement) throws ExecutionException { + EReference containmentFeature = PackageUtil.findFeature(getElementToEdit().eClass(), newElement.eClass()); + emfcmd = new CreateChildCommand(getEditingDomain(), getElementToEdit(), containmentFeature, newElement, Collections.EMPTY_LIST); + emfcmd.canExecute(); + emfcmd.execute(); + + return newElement; + } + + @Override + protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + emfcmd.undo(); + return super.doUndo(monitor, info); + } + + @Override + protected IStatus doRedo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + IStatus status = super.doRedo(monitor, info); + emfcmd.redo(); + return status; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/DeferredInterruptibleEdgeCommand.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/DeferredInterruptibleEdgeCommand.java index 0cdd6a60d9f..6e59421c35d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/DeferredInterruptibleEdgeCommand.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/DeferredInterruptibleEdgeCommand.java @@ -1,79 +1,79 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.commands;
-
-import java.util.List;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.requests.CreateConnectionViewRequest.ConnectionViewDescriptor;
-import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge;
-import org.eclipse.papyrus.uml.diagram.activity.request.InterruptibleEdgeRequest;
-import org.eclipse.uml2.uml.ActivityEdge;
-
-/**
- * Command to set an Activity Edge as an Interruptible Edge.
- * This common is deferred this mean that the command will be created and executed in the doExecuteCommand.
- * This can prevent undo however this way drag and drop works
- * In order to make this command to work the target EditPart has to implement {@link InterruptibleEdge}
- *
- * @author adaussy
- *
- */
-public class DeferredInterruptibleEdgeCommand extends AbstractTransactionalCommand {
-
- /**
- * {@link IGraphicalEditPart} of the {@link ActivityEdge} which implements {@link InterruptibleEdge}
- */
- private EditPart hostEditPart;
-
- /**
- * {@link ConnectionViewDescriptor} from creation mechanism
- */
- private ConnectionViewDescriptor descriptor;
-
- /**
- * Constructor {@link DeferredInterruptibleEdgeCommand#descriptor} and {@link DeferredInterruptibleEdgeCommand#hostEditPart}
- */
- public DeferredInterruptibleEdgeCommand(TransactionalEditingDomain domain, String label, List affectedFiles, EditPart hostEditPart, ConnectionViewDescriptor descriptor) {
- super(domain, label, affectedFiles);
- this.hostEditPart = hostEditPart;
- this.descriptor = descriptor;
- }
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- Object connectionEditPart = hostEditPart.getViewer().getEditPartRegistry().get(descriptor.getAdapter(View.class));
- if (connectionEditPart instanceof IGraphicalEditPart && connectionEditPart instanceof InterruptibleEdge) {
- InterruptibleEdgeRequest request = new InterruptibleEdgeRequest();
- request.setType(InterruptibleEdgeRequest.SET_INTERRUPTIBLE_EDGE);
- Command cmd = ((IGraphicalEditPart) connectionEditPart).getCommand(request);
- if (cmd != null && cmd.canExecute()) {
- cmd.execute();
- } else {
- return CommandResult.newErrorCommandResult("Unable to the the target Editpart as Interruptible Edge");//
- }
- }
- return CommandResult.newOKCommandResult();
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.commands; + +import java.util.List; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.commands.Command; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.requests.CreateConnectionViewRequest.ConnectionViewDescriptor; +import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge; +import org.eclipse.papyrus.uml.diagram.activity.request.InterruptibleEdgeRequest; +import org.eclipse.uml2.uml.ActivityEdge; + +/** + * Command to set an Activity Edge as an Interruptible Edge. + * This common is deferred this mean that the command will be created and executed in the doExecuteCommand. + * This can prevent undo however this way drag and drop works + * In order to make this command to work the target EditPart has to implement {@link InterruptibleEdge} + * + * @author adaussy + * + */ +public class DeferredInterruptibleEdgeCommand extends AbstractTransactionalCommand { + + /** + * {@link IGraphicalEditPart} of the {@link ActivityEdge} which implements {@link InterruptibleEdge} + */ + private EditPart hostEditPart; + + /** + * {@link ConnectionViewDescriptor} from creation mechanism + */ + private ConnectionViewDescriptor descriptor; + + /** + * Constructor {@link DeferredInterruptibleEdgeCommand#descriptor} and {@link DeferredInterruptibleEdgeCommand#hostEditPart} + */ + public DeferredInterruptibleEdgeCommand(TransactionalEditingDomain domain, String label, List affectedFiles, EditPart hostEditPart, ConnectionViewDescriptor descriptor) { + super(domain, label, affectedFiles); + this.hostEditPart = hostEditPart; + this.descriptor = descriptor; + } + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + Object connectionEditPart = hostEditPart.getViewer().getEditPartRegistry().get(descriptor.getAdapter(View.class)); + if (connectionEditPart instanceof IGraphicalEditPart && connectionEditPart instanceof InterruptibleEdge) { + InterruptibleEdgeRequest request = new InterruptibleEdgeRequest(); + request.setType(InterruptibleEdgeRequest.SET_INTERRUPTIBLE_EDGE); + Command cmd = ((IGraphicalEditPart) connectionEditPart).getCommand(request); + if (cmd != null && cmd.canExecute()) { + cmd.execute(); + } else { + return CommandResult.newErrorCommandResult("Unable to the the target Editpart as Interruptible Edge");// + } + } + return CommandResult.newOKCommandResult(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/util/CreateCommandUtil.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/util/CreateCommandUtil.java index ac634f166af..5149f6f3ea4 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/util/CreateCommandUtil.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/util/CreateCommandUtil.java @@ -1,183 +1,183 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.commands.util;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.ActivityPartition;
-import org.eclipse.uml2.uml.StructuredActivityNode;
-
-/**
- * This class provides utility methods shared by numerous create commands
- *
- * @author vhemery
- */
-public class CreateCommandUtil {
-
- /**
- * Check whether an Activity Partition can be created according to the element to edit and the node creation request
- *
- * @param request
- * request to create an Activity Partition (and not an other element)
- * @param elementToEdit
- * the element the command must edit
- * @return true id a node creation command should be executable
- */
- public static boolean canCreatePartition(IEditCommandRequest request, EObject elementToEdit) {
- // //check whether there is a model container parameter.
- // Object modelContainer = request.getParameter(GroupRequestConstants.MODEL_CONTAINERS);
- // if(modelContainer == null) {
- // // otherwise, simply take the command edited element
- // modelContainer = elementToEdit;
- // }
- // //check the container's type.
- // return modelContainer instanceof Activity || modelContainer instanceof ActivityPartition;
- return true;
- }
-
- /**
- * Check whether an Activity Node can be created according to the element to edit and the node creation request
- *
- * @param request
- * request to create an Activity Node (and not an other element)
- * @param elementToEdit
- * the element the command must edit
- * @return true id a node creation command should be executable
- */
- public static boolean canCreateNode(IEditCommandRequest request, EObject elementToEdit) {
- // //check whether there is a model container parameter.
- // Object modelContainer = request.getParameter(GroupRequestConstants.MODEL_CONTAINER);
- // if(modelContainer == null) {
- // // otherwise, simply take the command edited element
- // modelContainer = elementToEdit;
- // }
- // //check the container's type.
- // return modelContainer instanceof Activity || modelContainer instanceof StructuredActivityNode;
- return true;
- }
-
- /**
- * Set the node's parents : create in appropriate container and set extra parent reference if necessary.
- *
- * @param newElement
- * the element in creation
- * @param request
- * request to create a node
- * @param elementToEdit
- * the element the executing command edits
- * @return false if command must be cancelled
- */
- public static boolean setNodeParents(ActivityNode newElement, IEditCommandRequest request, EObject elementToEdit) {
- // simply take the command edited element
- EObject owner = elementToEdit;
- // create in appropriate model container
- if (owner instanceof Activity) {
- ((Activity) owner).getOwnedNodes().add(newElement);
- } else if (owner instanceof StructuredActivityNode) {
- ((StructuredActivityNode) owner).getNodes().add(newElement);
- } else {
- // incorrect model container
- return false;
- }
- // // add extra parent reference
- // if(elementToEdit != owner) {
- // EObject childHolder = elementToEdit;
- // if(childHolder instanceof InterruptibleActivityRegion) {
- // ((InterruptibleActivityRegion)childHolder).getNodes().add(newElement);
- // } else if(childHolder instanceof ActivityPartition) {
- // ((ActivityPartition)childHolder).getNodes().add(newElement);
- // } else {
- // // incorrect referencing parent
- // return false;
- // }
- // }
- return true;
- }
-
- /**
- * Set the structured activity node's parents : create in appropriate container and set extra parent reference if necessary.
- *
- * @param newElement
- * the element in creation
- * @param request
- * request to create a node
- * @param elementToEdit
- * the element the executing command edits
- * @return false if command must be cancelled
- */
- public static boolean setStructuredActivityNodeParents(StructuredActivityNode newElement, IEditCommandRequest request, EObject elementToEdit) {
- // check whether there is a model container parameter.
- EObject owner = elementToEdit;
- // create in appropriate model container
- if (owner instanceof Activity) {
- ((Activity) owner).getOwnedGroups().add(newElement);
- } else if (owner instanceof StructuredActivityNode) {
- ((StructuredActivityNode) owner).getNodes().add(newElement);
- } else {
- // incorrect model container
- return false;
- }
- // // add extra parent reference
- // if(elementToEdit != owner) {
- // EObject childHolder = elementToEdit;
- // if(childHolder instanceof InterruptibleActivityRegion) {
- // ((InterruptibleActivityRegion)childHolder).getNodes().add(newElement);
- // } else if(childHolder instanceof ActivityPartition) {
- // ((ActivityPartition)childHolder).getNodes().add(newElement);
- // } else {
- // // incorrect referencing parent
- // return false;
- // }
- // }
- return true;
- }
-
- /**
- * Set the activity partition's parents : create in appropriate container and set extra parent reference if necessary.
- *
- * @param newElement
- * the element in creation
- * @param request
- * request to create a node
- * @param elementToEdit
- * the element the executing command edits
- * @return false if command must be cancelled
- */
- public static boolean setActivityPartitionParents(ActivityPartition newElement, IEditCommandRequest request, EObject elementToEdit) {
- // check whether there is a model container parameter.
- EObject owner = elementToEdit;
- // create in appropriate model container
- if (owner instanceof Activity) {
- ((Activity) owner).getOwnedGroups().add(newElement);
- } else if (owner instanceof ActivityPartition) {
- ((ActivityPartition) owner).getSubpartitions().add(newElement);
- } else {
- // incorrect model container
- return false;
- }
- // // add extra parent reference
- // if(elementToEdit != owner) {
- // EObject childHolder = elementToEdit;
- // if(childHolder instanceof ActivityPartition) {
- // ((ActivityPartition)childHolder).getSubpartitions().add(newElement);
- // } else {
- // // incorrect referencing parent
- // return false;
- // }
- // }
- return true;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.commands.util; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.emf.type.core.requests.IEditCommandRequest; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.ActivityPartition; +import org.eclipse.uml2.uml.StructuredActivityNode; + +/** + * This class provides utility methods shared by numerous create commands + * + * @author vhemery + */ +public class CreateCommandUtil { + + /** + * Check whether an Activity Partition can be created according to the element to edit and the node creation request + * + * @param request + * request to create an Activity Partition (and not an other element) + * @param elementToEdit + * the element the command must edit + * @return true id a node creation command should be executable + */ + public static boolean canCreatePartition(IEditCommandRequest request, EObject elementToEdit) { + // //check whether there is a model container parameter. + // Object modelContainer = request.getParameter(GroupRequestConstants.MODEL_CONTAINERS); + // if(modelContainer == null) { + // // otherwise, simply take the command edited element + // modelContainer = elementToEdit; + // } + // //check the container's type. + // return modelContainer instanceof Activity || modelContainer instanceof ActivityPartition; + return true; + } + + /** + * Check whether an Activity Node can be created according to the element to edit and the node creation request + * + * @param request + * request to create an Activity Node (and not an other element) + * @param elementToEdit + * the element the command must edit + * @return true id a node creation command should be executable + */ + public static boolean canCreateNode(IEditCommandRequest request, EObject elementToEdit) { + // //check whether there is a model container parameter. + // Object modelContainer = request.getParameter(GroupRequestConstants.MODEL_CONTAINER); + // if(modelContainer == null) { + // // otherwise, simply take the command edited element + // modelContainer = elementToEdit; + // } + // //check the container's type. + // return modelContainer instanceof Activity || modelContainer instanceof StructuredActivityNode; + return true; + } + + /** + * Set the node's parents : create in appropriate container and set extra parent reference if necessary. + * + * @param newElement + * the element in creation + * @param request + * request to create a node + * @param elementToEdit + * the element the executing command edits + * @return false if command must be cancelled + */ + public static boolean setNodeParents(ActivityNode newElement, IEditCommandRequest request, EObject elementToEdit) { + // simply take the command edited element + EObject owner = elementToEdit; + // create in appropriate model container + if (owner instanceof Activity) { + ((Activity) owner).getOwnedNodes().add(newElement); + } else if (owner instanceof StructuredActivityNode) { + ((StructuredActivityNode) owner).getNodes().add(newElement); + } else { + // incorrect model container + return false; + } + // // add extra parent reference + // if(elementToEdit != owner) { + // EObject childHolder = elementToEdit; + // if(childHolder instanceof InterruptibleActivityRegion) { + // ((InterruptibleActivityRegion)childHolder).getNodes().add(newElement); + // } else if(childHolder instanceof ActivityPartition) { + // ((ActivityPartition)childHolder).getNodes().add(newElement); + // } else { + // // incorrect referencing parent + // return false; + // } + // } + return true; + } + + /** + * Set the structured activity node's parents : create in appropriate container and set extra parent reference if necessary. + * + * @param newElement + * the element in creation + * @param request + * request to create a node + * @param elementToEdit + * the element the executing command edits + * @return false if command must be cancelled + */ + public static boolean setStructuredActivityNodeParents(StructuredActivityNode newElement, IEditCommandRequest request, EObject elementToEdit) { + // check whether there is a model container parameter. + EObject owner = elementToEdit; + // create in appropriate model container + if (owner instanceof Activity) { + ((Activity) owner).getOwnedGroups().add(newElement); + } else if (owner instanceof StructuredActivityNode) { + ((StructuredActivityNode) owner).getNodes().add(newElement); + } else { + // incorrect model container + return false; + } + // // add extra parent reference + // if(elementToEdit != owner) { + // EObject childHolder = elementToEdit; + // if(childHolder instanceof InterruptibleActivityRegion) { + // ((InterruptibleActivityRegion)childHolder).getNodes().add(newElement); + // } else if(childHolder instanceof ActivityPartition) { + // ((ActivityPartition)childHolder).getNodes().add(newElement); + // } else { + // // incorrect referencing parent + // return false; + // } + // } + return true; + } + + /** + * Set the activity partition's parents : create in appropriate container and set extra parent reference if necessary. + * + * @param newElement + * the element in creation + * @param request + * request to create a node + * @param elementToEdit + * the element the executing command edits + * @return false if command must be cancelled + */ + public static boolean setActivityPartitionParents(ActivityPartition newElement, IEditCommandRequest request, EObject elementToEdit) { + // check whether there is a model container parameter. + EObject owner = elementToEdit; + // create in appropriate model container + if (owner instanceof Activity) { + ((Activity) owner).getOwnedGroups().add(newElement); + } else if (owner instanceof ActivityPartition) { + ((ActivityPartition) owner).getSubpartitions().add(newElement); + } else { + // incorrect model container + return false; + } + // // add extra parent reference + // if(elementToEdit != owner) { + // EObject childHolder = elementToEdit; + // if(childHolder instanceof ActivityPartition) { + // ((ActivityPartition)childHolder).getSubpartitions().add(newElement); + // } else { + // // incorrect referencing parent + // return false; + // } + // } + return true; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/util/PinUpdateCommand.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/util/PinUpdateCommand.java index a9904b8aa83..bb6633f5162 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/util/PinUpdateCommand.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/commands/util/PinUpdateCommand.java @@ -1,92 +1,92 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.commands.util;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.gmf.runtime.common.core.command.AbstractCommand;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater;
-import org.eclipse.uml2.uml.ActivityNode;
-
-public class PinUpdateCommand<NodeType extends ActivityNode> extends AbstractCommand {
-
- /**
- *
- */
- protected IPinUpdater<NodeType> updater;
-
- /**
- *
- */
- protected NodeType node;
-
- /**
- * Constructor.
- *
- * @param label
- */
- public PinUpdateCommand(String label, IPinUpdater<NodeType> updater, NodeType node) {
- super(label);
- this.updater = updater;
- this.node = node;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.common.core.command.AbstractCommand#doExecuteWithResult(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable)
- *
- * @param arg0
- * @param arg1
- * @return
- * @throws ExecutionException
- */
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor arg0, IAdaptable arg1) throws ExecutionException {
- CommandResult result = CommandResult.newOKCommandResult();
- try{
- this.updater.updatePins(this.node);
- }catch(Exception e){
- result = CommandResult.newErrorCommandResult(e);
- }
- return result;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.common.core.command.AbstractCommand#doRedoWithResult(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable)
- *
- * @param arg0
- * @param arg1
- * @return
- * @throws ExecutionException
- */
- @Override
- protected CommandResult doRedoWithResult(IProgressMonitor arg0, IAdaptable arg1) throws ExecutionException {
- return null;
- }
-
- /**
- * @see org.eclipse.gmf.runtime.common.core.command.AbstractCommand#doUndoWithResult(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable)
- *
- * @param arg0
- * @param arg1
- * @return
- * @throws ExecutionException
- */
- @Override
- protected CommandResult doUndoWithResult(IProgressMonitor arg0, IAdaptable arg1) throws ExecutionException {
- return null;
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.commands.util; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.gmf.runtime.common.core.command.AbstractCommand; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater; +import org.eclipse.uml2.uml.ActivityNode; + +public class PinUpdateCommand<NodeType extends ActivityNode> extends AbstractCommand { + + /** + * + */ + protected IPinUpdater<NodeType> updater; + + /** + * + */ + protected NodeType node; + + /** + * Constructor. + * + * @param label + */ + public PinUpdateCommand(String label, IPinUpdater<NodeType> updater, NodeType node) { + super(label); + this.updater = updater; + this.node = node; + } + + /** + * @see org.eclipse.gmf.runtime.common.core.command.AbstractCommand#doExecuteWithResult(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable) + * + * @param arg0 + * @param arg1 + * @return + * @throws ExecutionException + */ + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor arg0, IAdaptable arg1) throws ExecutionException { + CommandResult result = CommandResult.newOKCommandResult(); + try{ + this.updater.updatePins(this.node); + }catch(Exception e){ + result = CommandResult.newErrorCommandResult(e); + } + return result; + } + + /** + * @see org.eclipse.gmf.runtime.common.core.command.AbstractCommand#doRedoWithResult(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable) + * + * @param arg0 + * @param arg1 + * @return + * @throws ExecutionException + */ + @Override + protected CommandResult doRedoWithResult(IProgressMonitor arg0, IAdaptable arg1) throws ExecutionException { + return null; + } + + /** + * @see org.eclipse.gmf.runtime.common.core.command.AbstractCommand#doUndoWithResult(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable) + * + * @param arg0 + * @param arg1 + * @return + * @throws ExecutionException + */ + @Override + protected CommandResult doUndoWithResult(IProgressMonitor arg0, IAdaptable arg1) throws ExecutionException { + return null; + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/ConfirmActivityParameterNodeAndParameterSyncDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/ConfirmActivityParameterNodeAndParameterSyncDialog.java index 0ac7acf9a23..933269f7431 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/ConfirmActivityParameterNodeAndParameterSyncDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/ConfirmActivityParameterNodeAndParameterSyncDialog.java @@ -1,106 +1,106 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Collection;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.uml2.uml.NamedElement;
-
-/**
- * This class enables to open a dialog to ask the user to confirm he wants to
- * delete activity parameter node(s) with parameter
- *
- */
-public class ConfirmActivityParameterNodeAndParameterSyncDialog extends MessageDialog {
-
- /**
- * Protected constructor. Use {@link #openConfirmFromParameter(Shell)} or {@link #openConfirmFromPin(Shell)}
- *
- * @param parentShell
- * the parent shell
- * @param dialogMessage
- * the message
- */
- protected ConfirmActivityParameterNodeAndParameterSyncDialog(Shell parentShell, String dialogMessage) {
- super(parentShell, CustomMessages.ConfirmActivityParameterAndParameterSync_Title, null, dialogMessage, CONFIRM, new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0);
- }
-
- /**
- * Open a confirmation dialog for the parameter deletion
- *
- * @param parentShell
- * @param parameterNodes
- * @param labelprovider
- * @return the user confirmation
- */
- public static boolean openConfirmFromParameter(Shell parentShell, Collection<? extends NamedElement> parameterNodes, ILabelProvider labelprovider) {
- // consult preferences before opening the popup
- final IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
- boolean showPopup = prefStore.getBoolean(IActivityPreferenceConstants.PREF_CONFIRM_ACTIVITY_PARAMETER_SYNC_FROM_PARAMETER);
- if (showPopup) {
- StringBuffer parsedList = new StringBuffer();
- for (NamedElement element : parameterNodes) {
- parsedList.append(labelprovider.getText(element));
- parsedList.append(System.getProperty("line.separator"));
- }
- String message = NLS.bind(CustomMessages.ConfirmActivityParameterAndParameterSync_FromParameterMsg, parsedList.toString());
- ConfirmActivityParameterNodeAndParameterSyncDialog dialog = new ConfirmActivityParameterNodeAndParameterSyncDialog(parentShell, message);
- return dialog.open() == 0;
- } else {
- return true;
- }
- }
-
- /**
- * Create a checkbox for not displaying the popup again
- *
- * @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
- *
- * @param parent
- * parent composite
- * @return checkbox
- */
- @Override
- protected Control createCustomArea(Composite parent) {
- Button checkBox = new Button(parent, SWT.CHECK | SWT.LEFT);
- checkBox.setText(CustomMessages.DiagramsPreferencePage_disableNotification);
- checkBox.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() instanceof Button) {
- boolean doNotShow = ((Button) e.getSource()).getSelection();
- final IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
- prefStore.putValue(IActivityPreferenceConstants.PREF_CONFIRM_ACTIVITY_PARAMETER_SYNC_FROM_PARAMETER, Boolean.toString(!doNotShow));
- }
- }
- });
- return checkBox;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Collection; + +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.osgi.util.NLS; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.uml2.uml.NamedElement; + +/** + * This class enables to open a dialog to ask the user to confirm he wants to + * delete activity parameter node(s) with parameter + * + */ +public class ConfirmActivityParameterNodeAndParameterSyncDialog extends MessageDialog { + + /** + * Protected constructor. Use {@link #openConfirmFromParameter(Shell)} or {@link #openConfirmFromPin(Shell)} + * + * @param parentShell + * the parent shell + * @param dialogMessage + * the message + */ + protected ConfirmActivityParameterNodeAndParameterSyncDialog(Shell parentShell, String dialogMessage) { + super(parentShell, CustomMessages.ConfirmActivityParameterAndParameterSync_Title, null, dialogMessage, CONFIRM, new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0); + } + + /** + * Open a confirmation dialog for the parameter deletion + * + * @param parentShell + * @param parameterNodes + * @param labelprovider + * @return the user confirmation + */ + public static boolean openConfirmFromParameter(Shell parentShell, Collection<? extends NamedElement> parameterNodes, ILabelProvider labelprovider) { + // consult preferences before opening the popup + final IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + boolean showPopup = prefStore.getBoolean(IActivityPreferenceConstants.PREF_CONFIRM_ACTIVITY_PARAMETER_SYNC_FROM_PARAMETER); + if (showPopup) { + StringBuffer parsedList = new StringBuffer(); + for (NamedElement element : parameterNodes) { + parsedList.append(labelprovider.getText(element)); + parsedList.append(System.getProperty("line.separator")); + } + String message = NLS.bind(CustomMessages.ConfirmActivityParameterAndParameterSync_FromParameterMsg, parsedList.toString()); + ConfirmActivityParameterNodeAndParameterSyncDialog dialog = new ConfirmActivityParameterNodeAndParameterSyncDialog(parentShell, message); + return dialog.open() == 0; + } else { + return true; + } + } + + /** + * Create a checkbox for not displaying the popup again + * + * @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite) + * + * @param parent + * parent composite + * @return checkbox + */ + @Override + protected Control createCustomArea(Composite parent) { + Button checkBox = new Button(parent, SWT.CHECK | SWT.LEFT); + checkBox.setText(CustomMessages.DiagramsPreferencePage_disableNotification); + checkBox.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + if (e.getSource() instanceof Button) { + boolean doNotShow = ((Button) e.getSource()).getSelection(); + final IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + prefStore.putValue(IActivityPreferenceConstants.PREF_CONFIRM_ACTIVITY_PARAMETER_SYNC_FROM_PARAMETER, Boolean.toString(!doNotShow)); + } + } + }); + return checkBox; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/ConfirmPinAndParameterSyncDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/ConfirmPinAndParameterSyncDialog.java index c40938c3c8a..4b9b408d237 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/ConfirmPinAndParameterSyncDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/ConfirmPinAndParameterSyncDialog.java @@ -1,109 +1,109 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.List;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.uml2.uml.NamedElement;
-
-/**
- * This class enables to open a dialog to ask the user to confirm he wants to
- * update a Parameter and associated Pins
- *
- */
-public class ConfirmPinAndParameterSyncDialog extends MessageDialog {
-
- /**
- * Protected constructor. Use {@link #openConfirmFromParameter(Shell)} or {@link #openConfirmFromPin(Shell)}
- *
- * @param parentShell
- * the parent shell
- * @param dialogMessage
- * the message
- */
- protected ConfirmPinAndParameterSyncDialog(Shell parentShell, String dialogMessage) {
- super(parentShell, CustomMessages.ConfirmPinAndParameterSync_Title, null, dialogMessage, CONFIRM, new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0);
- }
-
- /**
- * Open a confirmation dialog for a modification from a parameter
- *
- * @param parentShell
- * the parent shell
- * @param listOfActions
- * the list of impacted actions
- * @param labelprovider
- * the label provider to read actions
- * @return the user confirmation
- */
- public static boolean openConfirmFromParameter(Shell parentShell, List<? extends NamedElement> listOfActions, ILabelProvider labelprovider) {
- // consult preferences before opening the popups
- final IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
- boolean showPopup = prefStore.getBoolean(IActivityPreferenceConstants.PREF_CONFIRM_PIN_SYNC_FROM_PARAMETER);
- if (showPopup) {
- StringBuffer parsedList = new StringBuffer();
- for (NamedElement element : listOfActions) {
- parsedList.append(labelprovider.getText(element));
- parsedList.append(System.getProperty("line.separator"));
- }
- String message = NLS.bind(CustomMessages.ConfirmPinAndParameterSync_FromParameterMsg, parsedList.toString());
- ConfirmPinAndParameterSyncDialog dialog = new ConfirmPinAndParameterSyncDialog(parentShell, message);
- return dialog.open() == 0;
- } else {
- return true;
- }
- }
-
- /**
- * Create a checkbox for not displaying the popup again
- *
- * @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
- *
- * @param parent
- * parent composite
- * @return checkbox
- */
- @Override
- protected Control createCustomArea(Composite parent) {
- Button checkBox = new Button(parent, SWT.CHECK | SWT.LEFT);
- checkBox.setText(CustomMessages.DiagramsPreferencePage_disableNotification);
- checkBox.addSelectionListener(new SelectionAdapter() {
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() instanceof Button) {
- boolean doNotShow = ((Button) e.getSource()).getSelection();
- final IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
- prefStore.putValue(IActivityPreferenceConstants.PREF_CONFIRM_PIN_SYNC_FROM_PARAMETER, Boolean.toString(!doNotShow));
- }
- }
- });
- return checkBox;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.List; + +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.osgi.util.NLS; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.uml2.uml.NamedElement; + +/** + * This class enables to open a dialog to ask the user to confirm he wants to + * update a Parameter and associated Pins + * + */ +public class ConfirmPinAndParameterSyncDialog extends MessageDialog { + + /** + * Protected constructor. Use {@link #openConfirmFromParameter(Shell)} or {@link #openConfirmFromPin(Shell)} + * + * @param parentShell + * the parent shell + * @param dialogMessage + * the message + */ + protected ConfirmPinAndParameterSyncDialog(Shell parentShell, String dialogMessage) { + super(parentShell, CustomMessages.ConfirmPinAndParameterSync_Title, null, dialogMessage, CONFIRM, new String[] { IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0); + } + + /** + * Open a confirmation dialog for a modification from a parameter + * + * @param parentShell + * the parent shell + * @param listOfActions + * the list of impacted actions + * @param labelprovider + * the label provider to read actions + * @return the user confirmation + */ + public static boolean openConfirmFromParameter(Shell parentShell, List<? extends NamedElement> listOfActions, ILabelProvider labelprovider) { + // consult preferences before opening the popups + final IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + boolean showPopup = prefStore.getBoolean(IActivityPreferenceConstants.PREF_CONFIRM_PIN_SYNC_FROM_PARAMETER); + if (showPopup) { + StringBuffer parsedList = new StringBuffer(); + for (NamedElement element : listOfActions) { + parsedList.append(labelprovider.getText(element)); + parsedList.append(System.getProperty("line.separator")); + } + String message = NLS.bind(CustomMessages.ConfirmPinAndParameterSync_FromParameterMsg, parsedList.toString()); + ConfirmPinAndParameterSyncDialog dialog = new ConfirmPinAndParameterSyncDialog(parentShell, message); + return dialog.open() == 0; + } else { + return true; + } + } + + /** + * Create a checkbox for not displaying the popup again + * + * @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite) + * + * @param parent + * parent composite + * @return checkbox + */ + @Override + protected Control createCustomArea(Composite parent) { + Button checkBox = new Button(parent, SWT.CHECK | SWT.LEFT); + checkBox.setText(CustomMessages.DiagramsPreferencePage_disableNotification); + checkBox.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + if (e.getSource() instanceof Button) { + boolean doNotShow = ((Button) e.getSource()).getSelection(); + final IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + prefStore.putValue(IActivityPreferenceConstants.PREF_CONFIRM_PIN_SYNC_FROM_PARAMETER, Boolean.toString(!doNotShow)); + } + } + }); + return checkBox; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateActivityParameterNodeDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateActivityParameterNodeDialog.java index 8a7206dca13..5eb0476b5f7 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateActivityParameterNodeDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateActivityParameterNodeDialog.java @@ -1,569 +1,569 @@ -/*****************************************************************************
- * 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:
- * Emilien Perico (Atos Origin) emilien.perico@atosorigin.com - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-import org.eclipse.emf.common.command.Command;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.edit.command.AddCommand;
-import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ComboViewer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.papyrus.infra.core.modelsetquery.ModelSetQuery;
-import org.eclipse.papyrus.infra.ui.util.EditorUtils;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.Messages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes;
-import org.eclipse.papyrus.uml.diagram.common.actions.LabelHelper;
-import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.ui.forms.FormDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ImageHyperlink;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.NamedElement;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.ParameterDirectionKind;
-import org.eclipse.uml2.uml.Type;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * DialogBox in order to link a parameter with the new ActivityParameterNode
- * that will be created
- *
- */
-public class CreateActivityParameterNodeDialog extends FormDialog {
-
- private Button creationRadio;
-
- private Button selectionRadio;
-
- private Text selectionText;
-
- private Button selectionButton;
-
- private Text creationNameText;
-
- private Text creationTypeText;
-
- private Button creationTypeButton;
-
- private Parameter selectedParameter = null;
-
- private EObject selectedType = null;
-
- private Activity activityOwner;
-
- private String selectedName = null;
-
- private ParameterDirectionKind selectedDirection = null;
-
- private ComboViewer directionComboViewer = null;
-
- private Combo creationDirectionCombo = null;
-
- private ILabelProvider labelProvider;
-
- /**
- * Create a new dialog to initialize an ActivityParameterNode.
- *
- * @param shell
- * parent shell
- * @param owner
- * the activity that owns the action
- */
- public CreateActivityParameterNodeDialog(Shell shell, Activity owner) {
- super(shell);
- activityOwner = owner;
- labelProvider = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory());
- }
-
- /**
- * Create the form to :
- *
- * - ask the user to choose or create an existing element.
- *
- * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm)
- */
- @Override
- protected void createFormContent(IManagedForm pForm) {
- pForm.getForm().setText(CustomMessages.CreateActivityParameterNodeDialog_DialogTitle);
- ScrolledForm scrolledForm = pForm.getForm();
- FormToolkit toolkit = pForm.getToolkit();
- Composite parent = scrolledForm.getBody();
- parent.setLayout(new GridLayout());
- createInvocationCreationSection(scrolledForm.getBody(), toolkit);
- createInvocationSelectionSection(scrolledForm.getBody(), toolkit);
- refreshSectionsEnable(false);
- hookListeners();
- // invoked name is set after listeners, since we count on listener to
- // update it properly
- setInvokedName(null);
- scrolledForm.reflow(true);
- }
-
- /**
- * Adds buttons to this dialog's button bar.
- *
- * @param parent
- * the button bar composite
- */
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- super.createButtonsForButtonBar(parent);
- refreshOkButton();
- }
-
- /**
- * Create the section to ask the user to choose an existing element.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- private void createInvocationSelectionSection(Composite pParent, FormToolkit pToolkit) {
- // create the section
- String lSectionTitle = CustomMessages.CreateActivityParameterNodeDialog_ParameterSelectionTitle;
- Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR);
- lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (lSectionTitle != null) {
- lSection.setText(lSectionTitle);
- }
- ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreateActivityParameterNodeDialog_ParameterSelectionHelp);
- lSection.setTextClient(componentHelp);
- ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection);
- lInsideScrolledForm.setExpandHorizontal(true);
- lInsideScrolledForm.setExpandVertical(true);
- Composite lBody = lInsideScrolledForm.getBody();
- GridLayout lLayout = new GridLayout();
- lLayout.numColumns = 3;
- lBody.setLayout(lLayout);
- // content of the section
- selectionRadio = pToolkit.createButton(lBody, CustomMessages.CreateActivityParameterNodeDialog_ParameterSelectionLabel, SWT.RADIO);
- selectionRadio.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
- // manage parameter selection
- pToolkit.createLabel(lBody, getParameterFeature().getEReferenceType().getName() + ":", SWT.NONE);
- selectionText = pToolkit.createText(lBody, "", SWT.BORDER | SWT.READ_ONLY);
- selectionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- selectionButton = pToolkit.createButton(lBody, "...", SWT.FLAT);
- Image image = UMLElementTypes.getImage(getParameterFeature());
- selectionButton.setImage(image);
- selectionButton.setLayoutData(new GridData(SWT.NONE));
- lInsideScrolledForm.reflow(true);
- lSection.setClient(lInsideScrolledForm);
- }
-
- /**
- * Create the section to ask the user to create an invoked element.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- private void createInvocationCreationSection(Composite pParent, FormToolkit pToolkit) {
- // create the section
- String lSectionTitle = CustomMessages.CreateActivityParameterNodeDialog_ParameterCreationTitle;
- Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR);
- lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (lSectionTitle != null) {
- lSection.setText(lSectionTitle);
- }
- ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreateActivityParameterNodeDialog_ParameterCreationHelp);
- lSection.setTextClient(componentHelp);
- ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection);
- lInsideScrolledForm.setExpandHorizontal(true);
- lInsideScrolledForm.setExpandVertical(true);
- Composite lBody = lInsideScrolledForm.getBody();
- GridLayout lLayout = new GridLayout();
- lLayout.numColumns = 3;
- lBody.setLayout(lLayout);
- // content of the section
- creationRadio = pToolkit.createButton(lBody, CustomMessages.CreateActivityParameterNodeDialog_ParameterCreationLabel, SWT.RADIO);
- creationRadio.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
- pToolkit.createLabel(lBody, CustomMessages.CreateActivityParameterNodeDialog_NameLabel, SWT.NONE);
- creationNameText = pToolkit.createText(lBody, "", SWT.BORDER);
- creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- creationNameText.setFocus();
- // manage type selection
- pToolkit.createLabel(lBody, CustomMessages.CreateActivityParameterNodeDialog_TypeLabel, SWT.NONE);
- creationTypeText = pToolkit.createText(lBody, labelProvider.getText(selectedType), SWT.BORDER | SWT.READ_ONLY);
- creationTypeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- creationTypeButton = pToolkit.createButton(lBody, "...", SWT.FLAT);
- Image image = UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage_PackagedElement());
- creationTypeButton.setImage(image);
- creationTypeButton.setLayoutData(new GridData(SWT.NONE));
- // manage direction selection
- pToolkit.createLabel(lBody, CustomMessages.CreateActivityParameterNodeDialog_DirectionLabel, SWT.NONE);
- creationDirectionCombo = new Combo(lBody, SWT.DROP_DOWN | SWT.READ_ONLY);
- directionComboViewer = new ComboViewer(creationDirectionCombo);
- pToolkit.adapt(creationDirectionCombo);
- creationDirectionCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- directionComboViewer.setLabelProvider(labelProvider);
- directionComboViewer.add(getDirections());
- // initialize selection
- directionComboViewer.setSelection(new StructuredSelection(getDirections()[0]));
- selectedDirection = ParameterDirectionKind.getByName(getDirections()[0]);
- lInsideScrolledForm.reflow(true);
- lSection.setClient(lInsideScrolledForm);
- }
-
- /**
- * Set correctly the invoked object, by creating it if needed. Then,
- * notifies that the ok button of this dialog has been pressed.
- *
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- *
- */
- @Override
- protected void okPressed() {
- boolean isSelectionSelected = selectionRadio.getSelection();
- // create element if needed
- if (!isSelectionSelected) {
- selectedParameter = UMLFactory.eINSTANCE.createParameter();
- selectedParameter.setName(selectedName);
- selectedParameter.setType((Type) selectedType);
- selectedParameter.setDirection(selectedDirection);
- addParameter(selectedParameter);
- }
- super.okPressed();
- }
-
- /**
- * Get the invoked object that have been selected or created.
- *
- * @return the invoked object to use.
- */
- public EObject getSelectedInvoked() {
- return selectedParameter;
- }
-
- /**
- * Add listeners to widgets
- */
- private void hookListeners() {
- // listener to choose active section
- SelectionListener selectCreateListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (creationRadio.equals(e.getSource())) {
- refreshSectionsEnable(false);
- } else {
- refreshSectionsEnable(true);
- }
- refreshOkButton();
- }
- };
- selectionRadio.addSelectionListener(selectCreateListener);
- creationRadio.addSelectionListener(selectCreateListener);
- // listener to select existing element
- SelectionListener selectBtnListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleChooseParameter();
- refreshOkButton();
- }
- };
- selectionButton.addSelectionListener(selectBtnListener);
- if (creationDirectionCombo != null && directionComboViewer != null) {
- // listener to select direction
- ModifyListener lTypeListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- ISelection sel = directionComboViewer.getSelection();
- if (sel instanceof StructuredSelection) {
- String firstElement = ((StructuredSelection) sel).getFirstElement().toString();
- selectedDirection = ParameterDirectionKind.getByName(firstElement);
- } else {
- selectedDirection = null;
- }
- // reset name
- setInvokedName(null);
- refreshOkButton();
- }
- };
- creationDirectionCombo.addModifyListener(lTypeListener);
- }
- // listener to element name
- ModifyListener lNameListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- setInvokedName(creationNameText.getText());
- }
- };
- creationNameText.addModifyListener(lNameListener);
- // listener to select new element type
- SelectionListener selectTypeBtnListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleChooseType();
- // reset name if not set
- if (selectedName == null) {
- setInvokedName(null);
- }
- refreshOkButton();
- }
- };
- creationTypeButton.addSelectionListener(selectTypeBtnListener);
- }
-
- /**
- * Set the name chosen for the invoked element
- *
- * @param text
- * the text string or null for auto-initialization
- */
- private void setInvokedName(String text) {
- String name = text;
- if (text == null) {
- name = LabelHelper.INSTANCE.findName(activityOwner, UMLPackage.eINSTANCE.getParameter());
- // the name assignment will be performed by listener's call
- creationNameText.setText(name);
- } else if (name != null && !"".equals(name.trim())) {
- selectedName = name.trim();
- Color black = creationNameText.getDisplay().getSystemColor(SWT.COLOR_BLACK);
- creationNameText.setForeground(black);
- refreshOkButton();
- } else {
- selectedName = null;
- Color red = creationNameText.getDisplay().getSystemColor(SWT.COLOR_RED);
- creationNameText.setForeground(red);
- refreshOkButton();
- }
- }
-
- /**
- * Open the dialog to choose the existing parameter to select
- *
- */
- private void handleChooseParameter() {
- Collection<EObject> elements = ModelSetQuery.getObjectsOfType(activityOwner, getParameterFeature().getEType());
- // only keep parameter that are children of the activity
- for (Iterator<EObject> it = elements.iterator(); it.hasNext();) {
- EObject eObject = it.next();
- if (!(activityOwner.equals(((Parameter) eObject).getOwner()))) {
- it.remove();
- }
- }
- ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
- dialog.setMessage(Messages.UMLModelingAssistantProviderMessage);
- dialog.setTitle(Messages.UMLModelingAssistantProviderTitle);
- dialog.setFilter("*");
- dialog.setMultipleSelection(false);
- dialog.setElements(elements.toArray(new EObject[elements.size()]));
- if (dialog.open() == Window.OK) {
- setParameterSelection((EObject) dialog.getFirstResult());
- }
- }
-
- /**
- * Define the parameter that will be set for the parameter node (if
- * selection mode is chosen)
- *
- * @param invokedElement
- * the selected element
- */
- private void setParameterSelection(EObject invokedElement) {
- if (invokedElement instanceof Parameter) {
- selectedParameter = (Parameter) invokedElement;
- selectionText.setText(labelProvider.getText(selectedParameter));
- } else {
- selectionText.setText("");
- }
- }
-
- /**
- * Open the dialog to choose the type of element to create
- *
- */
- private void handleChooseType() {
- Set<Object> types = getAvailableTypes();
- ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
- dialog.setFilter("*");
- dialog.setMessage(Messages.UMLModelingAssistantProviderMessage);
- dialog.setTitle(Messages.UMLModelingAssistantProviderTitle);
- dialog.setMultipleSelection(false);
- dialog.setElements(types.toArray());
- if (dialog.open() == Window.OK) {
- Object firstResult = dialog.getFirstResult();
- if (firstResult instanceof EObject) {
- setSelectedType((EObject) dialog.getFirstResult());
- } else {
- setSelectedType(null);
- }
- }
- }
-
- /**
- * Define the type of the object that will be created (if creation mode is
- * chosen)
- *
- * @param the
- * selected parent
- */
- private void setSelectedType(EObject invokedType) {
- selectedType = invokedType;
- if (selectedType instanceof NamedElement) {
- creationTypeText.setText(labelProvider.getText(selectedType));
- } else {
- creationTypeText.setText("");
- }
- }
-
- /**
- * Refresh the enabled and disabled elements in various sections
- *
- * @param isSelectionSelected
- * true if we choose to select an existing element, false if we
- * choose to create an element
- */
- private void refreshSectionsEnable(boolean isSelectionSelected) {
- // handle radio button value
- if (isSelectionSelected) {
- creationRadio.setSelection(false);
- if (!selectionRadio.getSelection()) {
- selectionRadio.setSelection(true);
- }
- } else {
- selectionRadio.setSelection(false);
- if (!creationRadio.getSelection()) {
- creationRadio.setSelection(true);
- }
- }
- // handle disabled section
- selectionText.setEnabled(isSelectionSelected);
- selectionButton.setEnabled(isSelectionSelected);
- if (creationDirectionCombo != null) {
- creationDirectionCombo.setEnabled(!isSelectionSelected);
- }
- creationNameText.setEnabled(!isSelectionSelected);
- creationNameText.setFocus();
- creationTypeText.setEnabled(!isSelectionSelected);
- creationTypeButton.setEnabled(!isSelectionSelected);
- }
-
- /**
- * Refresh the OK button activation
- */
- private void refreshOkButton() {
- boolean isSelectionSelected = selectionRadio.getSelection();
- if (getButton(IDialogConstants.OK_ID) != null && !getButton(IDialogConstants.OK_ID).isDisposed()) {
- if (isSelectionSelected) {
- getButton(IDialogConstants.OK_ID).setEnabled(selectedParameter != null);
- } else {
- getButton(IDialogConstants.OK_ID).setEnabled(selectedDirection != null && selectedName != null);
- }
- }
- }
-
- /**
- * Gets the parameter feature.
- *
- * @return the parameter feature
- */
- private EReference getParameterFeature() {
- return UMLPackage.eINSTANCE.getBehavior_OwnedParameter();
- }
-
- /**
- * Create the new Parameter
- */
- protected void addParameter(EObject newEObject) {
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- // Let the command find the relation on its own.
- Command addCmd = AddCommand.create(editingdomain, activityOwner, null, Collections.singleton(newEObject));
- addCmd.execute();
- }
-
- /**
- * Gets the available types for the parameter
- *
- * @return the available types
- */
- private Set<Object> getAvailableTypes() {
- Collection<EObject> types = ModelSetQuery.getObjectsOfType(activityOwner, UMLPackage.eINSTANCE.getTypedElement_Type().getEType());
- Set<Object> result = new HashSet<Object>();
- result.add("");
- result.addAll(types);
- return result;
- }
-
- /**
- * Gets the possible directions.
- *
- * @return the possible directions
- */
- private String[] getDirections() {
- List<ParameterDirectionKind> values = ParameterDirectionKind.VALUES;
- String[] ret = new String[values.size()];
- for (int i = 0; i < values.size(); i++) {
- ret[i] = values.get(i).getName();
- }
- return ret;
- }
-}
+/***************************************************************************** + * 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: + * Emilien Perico (Atos Origin) emilien.perico@atosorigin.com - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.edit.command.AddCommand; +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.viewers.ComboViewer; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.papyrus.infra.core.modelsetquery.ModelSetQuery; +import org.eclipse.papyrus.infra.ui.util.EditorUtils; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.Messages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes; +import org.eclipse.papyrus.uml.diagram.common.actions.LabelHelper; +import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.dialogs.ElementListSelectionDialog; +import org.eclipse.ui.forms.FormDialog; +import org.eclipse.ui.forms.IManagedForm; +import org.eclipse.ui.forms.widgets.ExpandableComposite; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.ui.forms.widgets.ImageHyperlink; +import org.eclipse.ui.forms.widgets.ScrolledForm; +import org.eclipse.ui.forms.widgets.Section; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.ParameterDirectionKind; +import org.eclipse.uml2.uml.Type; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * DialogBox in order to link a parameter with the new ActivityParameterNode + * that will be created + * + */ +public class CreateActivityParameterNodeDialog extends FormDialog { + + private Button creationRadio; + + private Button selectionRadio; + + private Text selectionText; + + private Button selectionButton; + + private Text creationNameText; + + private Text creationTypeText; + + private Button creationTypeButton; + + private Parameter selectedParameter = null; + + private EObject selectedType = null; + + private Activity activityOwner; + + private String selectedName = null; + + private ParameterDirectionKind selectedDirection = null; + + private ComboViewer directionComboViewer = null; + + private Combo creationDirectionCombo = null; + + private ILabelProvider labelProvider; + + /** + * Create a new dialog to initialize an ActivityParameterNode. + * + * @param shell + * parent shell + * @param owner + * the activity that owns the action + */ + public CreateActivityParameterNodeDialog(Shell shell, Activity owner) { + super(shell); + activityOwner = owner; + labelProvider = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()); + } + + /** + * Create the form to : + * + * - ask the user to choose or create an existing element. + * + * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm) + */ + @Override + protected void createFormContent(IManagedForm pForm) { + pForm.getForm().setText(CustomMessages.CreateActivityParameterNodeDialog_DialogTitle); + ScrolledForm scrolledForm = pForm.getForm(); + FormToolkit toolkit = pForm.getToolkit(); + Composite parent = scrolledForm.getBody(); + parent.setLayout(new GridLayout()); + createInvocationCreationSection(scrolledForm.getBody(), toolkit); + createInvocationSelectionSection(scrolledForm.getBody(), toolkit); + refreshSectionsEnable(false); + hookListeners(); + // invoked name is set after listeners, since we count on listener to + // update it properly + setInvokedName(null); + scrolledForm.reflow(true); + } + + /** + * Adds buttons to this dialog's button bar. + * + * @param parent + * the button bar composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + super.createButtonsForButtonBar(parent); + refreshOkButton(); + } + + /** + * Create the section to ask the user to choose an existing element. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + private void createInvocationSelectionSection(Composite pParent, FormToolkit pToolkit) { + // create the section + String lSectionTitle = CustomMessages.CreateActivityParameterNodeDialog_ParameterSelectionTitle; + Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); + lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + if (lSectionTitle != null) { + lSection.setText(lSectionTitle); + } + ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreateActivityParameterNodeDialog_ParameterSelectionHelp); + lSection.setTextClient(componentHelp); + ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection); + lInsideScrolledForm.setExpandHorizontal(true); + lInsideScrolledForm.setExpandVertical(true); + Composite lBody = lInsideScrolledForm.getBody(); + GridLayout lLayout = new GridLayout(); + lLayout.numColumns = 3; + lBody.setLayout(lLayout); + // content of the section + selectionRadio = pToolkit.createButton(lBody, CustomMessages.CreateActivityParameterNodeDialog_ParameterSelectionLabel, SWT.RADIO); + selectionRadio.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); + // manage parameter selection + pToolkit.createLabel(lBody, getParameterFeature().getEReferenceType().getName() + ":", SWT.NONE); + selectionText = pToolkit.createText(lBody, "", SWT.BORDER | SWT.READ_ONLY); + selectionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + selectionButton = pToolkit.createButton(lBody, "...", SWT.FLAT); + Image image = UMLElementTypes.getImage(getParameterFeature()); + selectionButton.setImage(image); + selectionButton.setLayoutData(new GridData(SWT.NONE)); + lInsideScrolledForm.reflow(true); + lSection.setClient(lInsideScrolledForm); + } + + /** + * Create the section to ask the user to create an invoked element. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + private void createInvocationCreationSection(Composite pParent, FormToolkit pToolkit) { + // create the section + String lSectionTitle = CustomMessages.CreateActivityParameterNodeDialog_ParameterCreationTitle; + Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); + lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + if (lSectionTitle != null) { + lSection.setText(lSectionTitle); + } + ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreateActivityParameterNodeDialog_ParameterCreationHelp); + lSection.setTextClient(componentHelp); + ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection); + lInsideScrolledForm.setExpandHorizontal(true); + lInsideScrolledForm.setExpandVertical(true); + Composite lBody = lInsideScrolledForm.getBody(); + GridLayout lLayout = new GridLayout(); + lLayout.numColumns = 3; + lBody.setLayout(lLayout); + // content of the section + creationRadio = pToolkit.createButton(lBody, CustomMessages.CreateActivityParameterNodeDialog_ParameterCreationLabel, SWT.RADIO); + creationRadio.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); + pToolkit.createLabel(lBody, CustomMessages.CreateActivityParameterNodeDialog_NameLabel, SWT.NONE); + creationNameText = pToolkit.createText(lBody, "", SWT.BORDER); + creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + creationNameText.setFocus(); + // manage type selection + pToolkit.createLabel(lBody, CustomMessages.CreateActivityParameterNodeDialog_TypeLabel, SWT.NONE); + creationTypeText = pToolkit.createText(lBody, labelProvider.getText(selectedType), SWT.BORDER | SWT.READ_ONLY); + creationTypeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + creationTypeButton = pToolkit.createButton(lBody, "...", SWT.FLAT); + Image image = UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage_PackagedElement()); + creationTypeButton.setImage(image); + creationTypeButton.setLayoutData(new GridData(SWT.NONE)); + // manage direction selection + pToolkit.createLabel(lBody, CustomMessages.CreateActivityParameterNodeDialog_DirectionLabel, SWT.NONE); + creationDirectionCombo = new Combo(lBody, SWT.DROP_DOWN | SWT.READ_ONLY); + directionComboViewer = new ComboViewer(creationDirectionCombo); + pToolkit.adapt(creationDirectionCombo); + creationDirectionCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + directionComboViewer.setLabelProvider(labelProvider); + directionComboViewer.add(getDirections()); + // initialize selection + directionComboViewer.setSelection(new StructuredSelection(getDirections()[0])); + selectedDirection = ParameterDirectionKind.getByName(getDirections()[0]); + lInsideScrolledForm.reflow(true); + lSection.setClient(lInsideScrolledForm); + } + + /** + * Set correctly the invoked object, by creating it if needed. Then, + * notifies that the ok button of this dialog has been pressed. + * + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + * + */ + @Override + protected void okPressed() { + boolean isSelectionSelected = selectionRadio.getSelection(); + // create element if needed + if (!isSelectionSelected) { + selectedParameter = UMLFactory.eINSTANCE.createParameter(); + selectedParameter.setName(selectedName); + selectedParameter.setType((Type) selectedType); + selectedParameter.setDirection(selectedDirection); + addParameter(selectedParameter); + } + super.okPressed(); + } + + /** + * Get the invoked object that have been selected or created. + * + * @return the invoked object to use. + */ + public EObject getSelectedInvoked() { + return selectedParameter; + } + + /** + * Add listeners to widgets + */ + private void hookListeners() { + // listener to choose active section + SelectionListener selectCreateListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + if (creationRadio.equals(e.getSource())) { + refreshSectionsEnable(false); + } else { + refreshSectionsEnable(true); + } + refreshOkButton(); + } + }; + selectionRadio.addSelectionListener(selectCreateListener); + creationRadio.addSelectionListener(selectCreateListener); + // listener to select existing element + SelectionListener selectBtnListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + handleChooseParameter(); + refreshOkButton(); + } + }; + selectionButton.addSelectionListener(selectBtnListener); + if (creationDirectionCombo != null && directionComboViewer != null) { + // listener to select direction + ModifyListener lTypeListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + ISelection sel = directionComboViewer.getSelection(); + if (sel instanceof StructuredSelection) { + String firstElement = ((StructuredSelection) sel).getFirstElement().toString(); + selectedDirection = ParameterDirectionKind.getByName(firstElement); + } else { + selectedDirection = null; + } + // reset name + setInvokedName(null); + refreshOkButton(); + } + }; + creationDirectionCombo.addModifyListener(lTypeListener); + } + // listener to element name + ModifyListener lNameListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + setInvokedName(creationNameText.getText()); + } + }; + creationNameText.addModifyListener(lNameListener); + // listener to select new element type + SelectionListener selectTypeBtnListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + handleChooseType(); + // reset name if not set + if (selectedName == null) { + setInvokedName(null); + } + refreshOkButton(); + } + }; + creationTypeButton.addSelectionListener(selectTypeBtnListener); + } + + /** + * Set the name chosen for the invoked element + * + * @param text + * the text string or null for auto-initialization + */ + private void setInvokedName(String text) { + String name = text; + if (text == null) { + name = LabelHelper.INSTANCE.findName(activityOwner, UMLPackage.eINSTANCE.getParameter()); + // the name assignment will be performed by listener's call + creationNameText.setText(name); + } else if (name != null && !"".equals(name.trim())) { + selectedName = name.trim(); + Color black = creationNameText.getDisplay().getSystemColor(SWT.COLOR_BLACK); + creationNameText.setForeground(black); + refreshOkButton(); + } else { + selectedName = null; + Color red = creationNameText.getDisplay().getSystemColor(SWT.COLOR_RED); + creationNameText.setForeground(red); + refreshOkButton(); + } + } + + /** + * Open the dialog to choose the existing parameter to select + * + */ + private void handleChooseParameter() { + Collection<EObject> elements = ModelSetQuery.getObjectsOfType(activityOwner, getParameterFeature().getEType()); + // only keep parameter that are children of the activity + for (Iterator<EObject> it = elements.iterator(); it.hasNext();) { + EObject eObject = it.next(); + if (!(activityOwner.equals(((Parameter) eObject).getOwner()))) { + it.remove(); + } + } + ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider); + dialog.setMessage(Messages.UMLModelingAssistantProviderMessage); + dialog.setTitle(Messages.UMLModelingAssistantProviderTitle); + dialog.setFilter("*"); + dialog.setMultipleSelection(false); + dialog.setElements(elements.toArray(new EObject[elements.size()])); + if (dialog.open() == Window.OK) { + setParameterSelection((EObject) dialog.getFirstResult()); + } + } + + /** + * Define the parameter that will be set for the parameter node (if + * selection mode is chosen) + * + * @param invokedElement + * the selected element + */ + private void setParameterSelection(EObject invokedElement) { + if (invokedElement instanceof Parameter) { + selectedParameter = (Parameter) invokedElement; + selectionText.setText(labelProvider.getText(selectedParameter)); + } else { + selectionText.setText(""); + } + } + + /** + * Open the dialog to choose the type of element to create + * + */ + private void handleChooseType() { + Set<Object> types = getAvailableTypes(); + ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider); + dialog.setFilter("*"); + dialog.setMessage(Messages.UMLModelingAssistantProviderMessage); + dialog.setTitle(Messages.UMLModelingAssistantProviderTitle); + dialog.setMultipleSelection(false); + dialog.setElements(types.toArray()); + if (dialog.open() == Window.OK) { + Object firstResult = dialog.getFirstResult(); + if (firstResult instanceof EObject) { + setSelectedType((EObject) dialog.getFirstResult()); + } else { + setSelectedType(null); + } + } + } + + /** + * Define the type of the object that will be created (if creation mode is + * chosen) + * + * @param the + * selected parent + */ + private void setSelectedType(EObject invokedType) { + selectedType = invokedType; + if (selectedType instanceof NamedElement) { + creationTypeText.setText(labelProvider.getText(selectedType)); + } else { + creationTypeText.setText(""); + } + } + + /** + * Refresh the enabled and disabled elements in various sections + * + * @param isSelectionSelected + * true if we choose to select an existing element, false if we + * choose to create an element + */ + private void refreshSectionsEnable(boolean isSelectionSelected) { + // handle radio button value + if (isSelectionSelected) { + creationRadio.setSelection(false); + if (!selectionRadio.getSelection()) { + selectionRadio.setSelection(true); + } + } else { + selectionRadio.setSelection(false); + if (!creationRadio.getSelection()) { + creationRadio.setSelection(true); + } + } + // handle disabled section + selectionText.setEnabled(isSelectionSelected); + selectionButton.setEnabled(isSelectionSelected); + if (creationDirectionCombo != null) { + creationDirectionCombo.setEnabled(!isSelectionSelected); + } + creationNameText.setEnabled(!isSelectionSelected); + creationNameText.setFocus(); + creationTypeText.setEnabled(!isSelectionSelected); + creationTypeButton.setEnabled(!isSelectionSelected); + } + + /** + * Refresh the OK button activation + */ + private void refreshOkButton() { + boolean isSelectionSelected = selectionRadio.getSelection(); + if (getButton(IDialogConstants.OK_ID) != null && !getButton(IDialogConstants.OK_ID).isDisposed()) { + if (isSelectionSelected) { + getButton(IDialogConstants.OK_ID).setEnabled(selectedParameter != null); + } else { + getButton(IDialogConstants.OK_ID).setEnabled(selectedDirection != null && selectedName != null); + } + } + } + + /** + * Gets the parameter feature. + * + * @return the parameter feature + */ + private EReference getParameterFeature() { + return UMLPackage.eINSTANCE.getBehavior_OwnedParameter(); + } + + /** + * Create the new Parameter + */ + protected void addParameter(EObject newEObject) { + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + // Let the command find the relation on its own. + Command addCmd = AddCommand.create(editingdomain, activityOwner, null, Collections.singleton(newEObject)); + addCmd.execute(); + } + + /** + * Gets the available types for the parameter + * + * @return the available types + */ + private Set<Object> getAvailableTypes() { + Collection<EObject> types = ModelSetQuery.getObjectsOfType(activityOwner, UMLPackage.eINSTANCE.getTypedElement_Type().getEType()); + Set<Object> result = new HashSet<Object>(); + result.add(""); + result.addAll(types); + return result; + } + + /** + * Gets the possible directions. + * + * @return the possible directions + */ + private String[] getDirections() { + List<ParameterDirectionKind> values = ParameterDirectionKind.VALUES; + String[] ret = new String[values.size()]; + for (int i = 0; i < values.size(); i++) { + ret[i] = values.get(i).getName(); + } + return ret; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateAttributeDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateAttributeDialog.java index bd39c08de2f..90849905a3d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateAttributeDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateAttributeDialog.java @@ -1,436 +1,436 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.emf.common.command.Command;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.edit.command.AddCommand;
-import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ComboViewer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.papyrus.infra.core.modelsetquery.ModelSetQuery;
-import org.eclipse.papyrus.infra.ui.util.EditorUtils;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.Messages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes;
-import org.eclipse.papyrus.uml.diagram.common.actions.LabelHelper;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.ui.forms.FormDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.uml2.uml.NamedElement;
-import org.eclipse.uml2.uml.Property;
-import org.eclipse.uml2.uml.Type;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * DialogBox in order to link a parameter with the new ActivityParameterNode
- * that will be created
- *
- */
-public class CreateAttributeDialog extends FormDialog {
-
- private Text creationNameText;
-
- private Text creationTypeText;
-
- private Button creationTypeButton;
-
- private Property createdProperty = null;
-
- private EObject selectedType = null;
-
- private NamedElement attributeOwner;
-
- private String selectedName = null;
-
- private EClass selectedEClass = null;
-
- private ComboViewer eClassComboViewer = null;
-
- private Combo creationEClassCombo = null;
-
- private ILabelProvider labelProvider;
-
- /**
- * Create a new dialog to initialize an ActivityParameterNode.
- *
- * @param shell
- * parent shell
- * @param owner
- * the activity that owns the action
- */
- public CreateAttributeDialog(Shell shell, NamedElement owner) {
- super(shell);
- attributeOwner = owner;
- labelProvider = getCustomLabelProvider();
- }
-
- /**
- * Create the form to :
- *
- * - ask the user to choose or create an existing element.
- *
- * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm)
- */
- @Override
- protected void createFormContent(IManagedForm pForm) {
- pForm.getForm().setText(getTitle());
- ScrolledForm scrolledForm = pForm.getForm();
- FormToolkit toolkit = pForm.getToolkit();
- Composite parent = scrolledForm.getBody();
- parent.setLayout(new GridLayout());
- createAttributeSection(scrolledForm.getBody(), toolkit);
- hookListeners();
- // invoked name is set after listeners, since we count on listener to
- // update it properly
- setInvokedName(null);
- scrolledForm.reflow(true);
- }
-
- /**
- * Adds buttons to this dialog's button bar.
- *
- * @param parent
- * the button bar composite
- */
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- super.createButtonsForButtonBar(parent);
- refreshOkButton();
- }
-
- /**
- * Create the section to ask the user to create an attribute.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- protected void createAttributeSection(Composite pParent, FormToolkit pToolkit) {
- // create the section
- String lSectionTitle = getCreationTitle();
- Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR);
- lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (lSectionTitle != null) {
- lSection.setText(lSectionTitle);
- }
- ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection);
- lInsideScrolledForm.setExpandHorizontal(true);
- lInsideScrolledForm.setExpandVertical(true);
- Composite lBody = lInsideScrolledForm.getBody();
- GridLayout lLayout = new GridLayout();
- lLayout.numColumns = 3;
- lBody.setLayout(lLayout);
- // content of the section
- // eclass
- pToolkit.createLabel(lBody, getEClassLabel(), SWT.NONE);
- creationEClassCombo = new Combo(lBody, SWT.DROP_DOWN | SWT.READ_ONLY);
- eClassComboViewer = new ComboViewer(creationEClassCombo);
- pToolkit.adapt(creationEClassCombo);
- creationEClassCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- eClassComboViewer.setLabelProvider(labelProvider);
- eClassComboViewer.add(getPossibleAttributes());
- if (getPossibleAttributes().length > 1) {
- // initialize selection
- eClassComboViewer.setSelection(new StructuredSelection(getPossibleAttributes()[0]));
- selectedEClass = getPossibleAttributes()[0];
- }
- // name
- pToolkit.createLabel(lBody, getNameLabel(), SWT.NONE);
- creationNameText = pToolkit.createText(lBody, "", SWT.BORDER);
- creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- creationNameText.setFocus();
- // manage type selection
- pToolkit.createLabel(lBody, getTypeLabel(), SWT.NONE);
- creationTypeText = pToolkit.createText(lBody, labelProvider.getText(selectedType), SWT.BORDER | SWT.READ_ONLY);
- creationTypeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- creationTypeButton = pToolkit.createButton(lBody, "...", SWT.FLAT);
- Image image = getTypeImage();
- creationTypeButton.setImage(image);
- creationTypeButton.setLayoutData(new GridData(SWT.NONE));
- lInsideScrolledForm.reflow(true);
- lSection.setClient(lInsideScrolledForm);
- }
-
- /**
- * Set correctly the object, by creating it if needed. Then, notifies that
- * the ok button of this dialog has been pressed.
- *
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- *
- */
- @Override
- protected void okPressed() {
- // create element
- createdProperty = (Property) UMLFactory.eINSTANCE.create(selectedEClass);
- createdProperty.setName(selectedName);
- createdProperty.setType((Type) selectedType);
- addAttribute(createdProperty);
- super.okPressed();
- }
-
- /**
- * Get the invoked object that have been selected or created.
- *
- * @return the invoked object to use.
- */
- public Property getCreatedAttribute() {
- return createdProperty;
- }
-
- /**
- * Add listeners to widgets
- */
- private void hookListeners() {
- if (creationEClassCombo != null && eClassComboViewer != null) {
- // listener to select invocation eclass
- ModifyListener lTypeListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- ISelection sel = eClassComboViewer.getSelection();
- if (sel instanceof StructuredSelection) {
- Object type = ((StructuredSelection) sel).getFirstElement();
- if (type instanceof EClass) {
- selectedEClass = (EClass) type;
- } else {
- selectedEClass = null;
- }
- // reset name
- setInvokedName(null);
- refreshOkButton();
- }
- }
- };
- creationEClassCombo.addModifyListener(lTypeListener);
- }
- // listener to invocation element name
- ModifyListener lNameListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- setInvokedName(creationNameText.getText());
- }
- };
- creationNameText.addModifyListener(lNameListener);
- // listener to select new element parent
- SelectionListener selectParentBtnListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleChooseType();
- // reset name if not set
- if (selectedName == null) {
- setInvokedName(null);
- }
- refreshOkButton();
- }
- };
- creationTypeButton.addSelectionListener(selectParentBtnListener);
- }
-
- /**
- * Set the name chosen for the invoked element
- *
- * @param text
- * the text string or null for auto-initialization
- */
- private void setInvokedName(String text) {
- String name = text;
- if (text == null && selectedEClass != null) {
- name = LabelHelper.INSTANCE.findName(attributeOwner, selectedEClass);
- // the name assignment will be performed by listener's call
- creationNameText.setText(name);
- } else if (name != null && !"".equals(name.trim())) {
- selectedName = name.trim();
- Color black = creationNameText.getDisplay().getSystemColor(SWT.COLOR_BLACK);
- creationNameText.setForeground(black);
- refreshOkButton();
- } else {
- selectedName = null;
- Color red = creationNameText.getDisplay().getSystemColor(SWT.COLOR_RED);
- creationNameText.setForeground(red);
- refreshOkButton();
- }
- }
-
- /**
- * Open the dialog to choose the type of element to create
- *
- */
- private void handleChooseType() {
- Set<Object> types = getPossibleTypes();
- ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
- dialog.setMessage(Messages.UMLModelingAssistantProviderMessage);
- dialog.setTitle(Messages.UMLModelingAssistantProviderTitle);
- dialog.setMultipleSelection(false);
- dialog.setElements(types.toArray());
- if (dialog.open() == Window.OK) {
- Object firstResult = dialog.getFirstResult();
- if (firstResult instanceof EObject) {
- setType((EObject) dialog.getFirstResult());
- } else {
- setType(null);
- }
- }
- }
-
- /**
- * Define the type of the object that will be created
- *
- * @param type
- * the selected type
- */
- private void setType(EObject type) {
- selectedType = type;
- if (selectedType instanceof NamedElement) {
- creationTypeText.setText(labelProvider.getText(selectedType));
- } else {
- creationTypeText.setText("");
- }
- }
-
- /**
- * Refresh the OK button activation
- */
- private void refreshOkButton() {
- if (getButton(IDialogConstants.OK_ID) != null && !getButton(IDialogConstants.OK_ID).isDisposed()) {
- getButton(IDialogConstants.OK_ID).setEnabled(selectedEClass != null && selectedName != null);
- }
- }
-
- /**
- * Add the created invoked object to its selected parent
- */
- protected void addAttribute(Property createdAttribute) {
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- // Let the command find the relation on its own.
- Command addCmd = AddCommand.create(editingdomain, attributeOwner, null, Collections.singleton(createdAttribute));
- addCmd.execute();
- }
-
- /**
- * Gets the possible types for the parameter
- *
- * @return the possible types
- */
- private Set<Object> getPossibleTypes() {
- Collection<EObject> types = ModelSetQuery.getObjectsOfType(attributeOwner, UMLPackage.eINSTANCE.getTypedElement_Type().getEType());
- Set<Object> result = new HashSet<Object>();
- result.add("");
- result.addAll(types);
- return result;
- }
-
- /**
- * Gets the custom label provider that parses label for EClass
- *
- * @return the custom label provider
- */
- private ILabelProvider getCustomLabelProvider() {
- AdapterFactoryLabelProvider adapterFactory = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()) {
-
- /**
- * Override label provider for EClass
- *
- * @see org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider#getText(java.lang.Object)
- */
- @Override
- public String getText(Object object) {
- String text = super.getText(object);
- if (object instanceof EClass) {
- return text.substring(0, text.indexOf("[") - 1);
- } else {
- return text;
- }
- }
- };
- return adapterFactory;
- }
-
- /**
- * Get possible classes to create an attribute
- *
- * @return classes inheriting {@link Property}
- */
- protected EClass[] getPossibleAttributes() {
- return new EClass[] { UMLPackage.eINSTANCE.getProperty(), UMLPackage.eINSTANCE.getExtensionEnd(), UMLPackage.eINSTANCE.getPort() };
- }
-
- private Image getTypeImage() {
- return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage_PackagedElement());
- }
-
- private String getTitle() {
- return CustomMessages.CreateAttributeDialog_DialogTitle;
- }
-
- private String getCreationTitle() {
- return CustomMessages.CreateAttributeDialog_CreationTitle;
- }
-
- private String getNameLabel() {
- return CustomMessages.CreateAttributeDialog_NameLabel;
- }
-
- private String getEClassLabel() {
- return CustomMessages.CreateAttributeDialog_EClassLabel;
- }
-
- private String getTypeLabel() {
- return CustomMessages.CreateAttributeDialog_TypeLabel;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.edit.command.AddCommand; +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.viewers.ComboViewer; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.papyrus.infra.core.modelsetquery.ModelSetQuery; +import org.eclipse.papyrus.infra.ui.util.EditorUtils; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.Messages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes; +import org.eclipse.papyrus.uml.diagram.common.actions.LabelHelper; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.dialogs.ElementListSelectionDialog; +import org.eclipse.ui.forms.FormDialog; +import org.eclipse.ui.forms.IManagedForm; +import org.eclipse.ui.forms.widgets.ExpandableComposite; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.ui.forms.widgets.ScrolledForm; +import org.eclipse.ui.forms.widgets.Section; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.Property; +import org.eclipse.uml2.uml.Type; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * DialogBox in order to link a parameter with the new ActivityParameterNode + * that will be created + * + */ +public class CreateAttributeDialog extends FormDialog { + + private Text creationNameText; + + private Text creationTypeText; + + private Button creationTypeButton; + + private Property createdProperty = null; + + private EObject selectedType = null; + + private NamedElement attributeOwner; + + private String selectedName = null; + + private EClass selectedEClass = null; + + private ComboViewer eClassComboViewer = null; + + private Combo creationEClassCombo = null; + + private ILabelProvider labelProvider; + + /** + * Create a new dialog to initialize an ActivityParameterNode. + * + * @param shell + * parent shell + * @param owner + * the activity that owns the action + */ + public CreateAttributeDialog(Shell shell, NamedElement owner) { + super(shell); + attributeOwner = owner; + labelProvider = getCustomLabelProvider(); + } + + /** + * Create the form to : + * + * - ask the user to choose or create an existing element. + * + * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm) + */ + @Override + protected void createFormContent(IManagedForm pForm) { + pForm.getForm().setText(getTitle()); + ScrolledForm scrolledForm = pForm.getForm(); + FormToolkit toolkit = pForm.getToolkit(); + Composite parent = scrolledForm.getBody(); + parent.setLayout(new GridLayout()); + createAttributeSection(scrolledForm.getBody(), toolkit); + hookListeners(); + // invoked name is set after listeners, since we count on listener to + // update it properly + setInvokedName(null); + scrolledForm.reflow(true); + } + + /** + * Adds buttons to this dialog's button bar. + * + * @param parent + * the button bar composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + super.createButtonsForButtonBar(parent); + refreshOkButton(); + } + + /** + * Create the section to ask the user to create an attribute. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + protected void createAttributeSection(Composite pParent, FormToolkit pToolkit) { + // create the section + String lSectionTitle = getCreationTitle(); + Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); + lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + if (lSectionTitle != null) { + lSection.setText(lSectionTitle); + } + ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection); + lInsideScrolledForm.setExpandHorizontal(true); + lInsideScrolledForm.setExpandVertical(true); + Composite lBody = lInsideScrolledForm.getBody(); + GridLayout lLayout = new GridLayout(); + lLayout.numColumns = 3; + lBody.setLayout(lLayout); + // content of the section + // eclass + pToolkit.createLabel(lBody, getEClassLabel(), SWT.NONE); + creationEClassCombo = new Combo(lBody, SWT.DROP_DOWN | SWT.READ_ONLY); + eClassComboViewer = new ComboViewer(creationEClassCombo); + pToolkit.adapt(creationEClassCombo); + creationEClassCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + eClassComboViewer.setLabelProvider(labelProvider); + eClassComboViewer.add(getPossibleAttributes()); + if (getPossibleAttributes().length > 1) { + // initialize selection + eClassComboViewer.setSelection(new StructuredSelection(getPossibleAttributes()[0])); + selectedEClass = getPossibleAttributes()[0]; + } + // name + pToolkit.createLabel(lBody, getNameLabel(), SWT.NONE); + creationNameText = pToolkit.createText(lBody, "", SWT.BORDER); + creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + creationNameText.setFocus(); + // manage type selection + pToolkit.createLabel(lBody, getTypeLabel(), SWT.NONE); + creationTypeText = pToolkit.createText(lBody, labelProvider.getText(selectedType), SWT.BORDER | SWT.READ_ONLY); + creationTypeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + creationTypeButton = pToolkit.createButton(lBody, "...", SWT.FLAT); + Image image = getTypeImage(); + creationTypeButton.setImage(image); + creationTypeButton.setLayoutData(new GridData(SWT.NONE)); + lInsideScrolledForm.reflow(true); + lSection.setClient(lInsideScrolledForm); + } + + /** + * Set correctly the object, by creating it if needed. Then, notifies that + * the ok button of this dialog has been pressed. + * + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + * + */ + @Override + protected void okPressed() { + // create element + createdProperty = (Property) UMLFactory.eINSTANCE.create(selectedEClass); + createdProperty.setName(selectedName); + createdProperty.setType((Type) selectedType); + addAttribute(createdProperty); + super.okPressed(); + } + + /** + * Get the invoked object that have been selected or created. + * + * @return the invoked object to use. + */ + public Property getCreatedAttribute() { + return createdProperty; + } + + /** + * Add listeners to widgets + */ + private void hookListeners() { + if (creationEClassCombo != null && eClassComboViewer != null) { + // listener to select invocation eclass + ModifyListener lTypeListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + ISelection sel = eClassComboViewer.getSelection(); + if (sel instanceof StructuredSelection) { + Object type = ((StructuredSelection) sel).getFirstElement(); + if (type instanceof EClass) { + selectedEClass = (EClass) type; + } else { + selectedEClass = null; + } + // reset name + setInvokedName(null); + refreshOkButton(); + } + } + }; + creationEClassCombo.addModifyListener(lTypeListener); + } + // listener to invocation element name + ModifyListener lNameListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + setInvokedName(creationNameText.getText()); + } + }; + creationNameText.addModifyListener(lNameListener); + // listener to select new element parent + SelectionListener selectParentBtnListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + handleChooseType(); + // reset name if not set + if (selectedName == null) { + setInvokedName(null); + } + refreshOkButton(); + } + }; + creationTypeButton.addSelectionListener(selectParentBtnListener); + } + + /** + * Set the name chosen for the invoked element + * + * @param text + * the text string or null for auto-initialization + */ + private void setInvokedName(String text) { + String name = text; + if (text == null && selectedEClass != null) { + name = LabelHelper.INSTANCE.findName(attributeOwner, selectedEClass); + // the name assignment will be performed by listener's call + creationNameText.setText(name); + } else if (name != null && !"".equals(name.trim())) { + selectedName = name.trim(); + Color black = creationNameText.getDisplay().getSystemColor(SWT.COLOR_BLACK); + creationNameText.setForeground(black); + refreshOkButton(); + } else { + selectedName = null; + Color red = creationNameText.getDisplay().getSystemColor(SWT.COLOR_RED); + creationNameText.setForeground(red); + refreshOkButton(); + } + } + + /** + * Open the dialog to choose the type of element to create + * + */ + private void handleChooseType() { + Set<Object> types = getPossibleTypes(); + ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider); + dialog.setMessage(Messages.UMLModelingAssistantProviderMessage); + dialog.setTitle(Messages.UMLModelingAssistantProviderTitle); + dialog.setMultipleSelection(false); + dialog.setElements(types.toArray()); + if (dialog.open() == Window.OK) { + Object firstResult = dialog.getFirstResult(); + if (firstResult instanceof EObject) { + setType((EObject) dialog.getFirstResult()); + } else { + setType(null); + } + } + } + + /** + * Define the type of the object that will be created + * + * @param type + * the selected type + */ + private void setType(EObject type) { + selectedType = type; + if (selectedType instanceof NamedElement) { + creationTypeText.setText(labelProvider.getText(selectedType)); + } else { + creationTypeText.setText(""); + } + } + + /** + * Refresh the OK button activation + */ + private void refreshOkButton() { + if (getButton(IDialogConstants.OK_ID) != null && !getButton(IDialogConstants.OK_ID).isDisposed()) { + getButton(IDialogConstants.OK_ID).setEnabled(selectedEClass != null && selectedName != null); + } + } + + /** + * Add the created invoked object to its selected parent + */ + protected void addAttribute(Property createdAttribute) { + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + // Let the command find the relation on its own. + Command addCmd = AddCommand.create(editingdomain, attributeOwner, null, Collections.singleton(createdAttribute)); + addCmd.execute(); + } + + /** + * Gets the possible types for the parameter + * + * @return the possible types + */ + private Set<Object> getPossibleTypes() { + Collection<EObject> types = ModelSetQuery.getObjectsOfType(attributeOwner, UMLPackage.eINSTANCE.getTypedElement_Type().getEType()); + Set<Object> result = new HashSet<Object>(); + result.add(""); + result.addAll(types); + return result; + } + + /** + * Gets the custom label provider that parses label for EClass + * + * @return the custom label provider + */ + private ILabelProvider getCustomLabelProvider() { + AdapterFactoryLabelProvider adapterFactory = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()) { + + /** + * Override label provider for EClass + * + * @see org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider#getText(java.lang.Object) + */ + @Override + public String getText(Object object) { + String text = super.getText(object); + if (object instanceof EClass) { + return text.substring(0, text.indexOf("[") - 1); + } else { + return text; + } + } + }; + return adapterFactory; + } + + /** + * Get possible classes to create an attribute + * + * @return classes inheriting {@link Property} + */ + protected EClass[] getPossibleAttributes() { + return new EClass[] { UMLPackage.eINSTANCE.getProperty(), UMLPackage.eINSTANCE.getExtensionEnd(), UMLPackage.eINSTANCE.getPort() }; + } + + private Image getTypeImage() { + return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage_PackagedElement()); + } + + private String getTitle() { + return CustomMessages.CreateAttributeDialog_DialogTitle; + } + + private String getCreationTitle() { + return CustomMessages.CreateAttributeDialog_CreationTitle; + } + + private String getNameLabel() { + return CustomMessages.CreateAttributeDialog_NameLabel; + } + + private String getEClassLabel() { + return CustomMessages.CreateAttributeDialog_EClassLabel; + } + + private String getTypeLabel() { + return CustomMessages.CreateAttributeDialog_TypeLabel; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallActionDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallActionDialog.java index 1e9cded2d62..dcd068f11ef 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallActionDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallActionDialog.java @@ -1,185 +1,185 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ImageHyperlink;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.InvocationAction;
-
-/**
- * This class provides a dialog to initialize a CallAction at its creation.
- */
-public abstract class CreateCallActionDialog extends CreateInvocationActionDialog {
-
- private Button isSynchronousButton;
-
- private boolean synchronous = false;
-
- /**
- * Create a new dialog to initialize a CallAction.
- *
- * @param shell
- * parent shell
- * @param owner
- * the activity that owns the action
- */
- public CreateCallActionDialog(Shell shell, Activity owner, InvocationAction newAction) {
- super(shell, owner, newAction);
- }
-
- /**
- * Create the IsSynchronous section.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- @Override
- protected void createExtraSections(Composite pParent, FormToolkit pToolkit) {
- createIsSynchronousSection(pParent, pToolkit);
- }
-
- /**
- * Refresh the enabled and disabled elements in various sections
- *
- * @param isSelectionSelected
- * true if we choose to select an existing element, false if we
- * choose to create an element
- */
- @Override
- protected void refreshSectionsEnable(boolean isSelectionSelected) {
- super.refreshSectionsEnable(isSelectionSelected);
- // handle synchronization constraint
- if (isSelectionSelected) {
- updateSynchronous(getSelectedInvoked());
- } else {
- updateSynchronous(null);
- }
- }
-
- /**
- * Define the object that will be invoked by the action (if selection mode
- * is chosen)
- *
- * @param invokedElement
- * the selected element
- */
- @Override
- protected void setInvokedSelection(EObject invokedElement) {
- super.setInvokedSelection(invokedElement);
- updateSynchronous(invokedElement);
- }
-
- /**
- * Create the section to ask whether the action must be synchronous.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- private void createIsSynchronousSection(Composite pParent, FormToolkit pToolkit) {
- // create the section
- String lSectionTitle = getIsSynchronousSectionTitle();
- Section lSection = pToolkit.createSection(pParent, ExpandableComposite.TWISTIE | ExpandableComposite.TITLE_BAR);
- lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (lSectionTitle != null) {
- lSection.setText(lSectionTitle);
- }
- ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreateCallActionDialog_IsSynchronousHelp, true);
- lSection.setTextClient(componentHelp);
- ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection);
- lInsideScrolledForm.setExpandHorizontal(true);
- lInsideScrolledForm.setExpandVertical(true);
- Composite lBody = lInsideScrolledForm.getBody();
- GridLayout lLayout = new GridLayout();
- lLayout.numColumns = 1;
- lBody.setLayout(lLayout);
- // content of the section
- isSynchronousButton = pToolkit.createButton(lBody, CustomMessages.CreateCallActionDialog_IsSynchronous, SWT.CHECK | SWT.WRAP);
- isSynchronousButton.setSelection(true);
- lInsideScrolledForm.reflow(true);
- lSection.setClient(lInsideScrolledForm);
- }
-
- /**
- * Set correctly the invoked object, by creating it if needed. Then,
- * notifies that the ok button of this dialog has been pressed.
- *
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- *
- */
- @Override
- protected void okPressed() {
- // register synchronous
- synchronous = isSynchronousButton.getSelection();
- super.okPressed();
- }
-
- /**
- * Get whether the CallAction must be synchronous.
- *
- * @return the invoked object to use.
- */
- public boolean getIsSynchronous() {
- return synchronous;
- }
-
- /**
- * Test is the invoked object has parameters which will generate output pins
- *
- * @param invokedObject
- * the object whose parameters must be inspected
- * @return true if there are parameters which will be mapped with output
- * pins
- */
- abstract protected boolean hasOutParameters(EObject invokedObject);
-
- /**
- *
- * @param selectedInvoked
- * the invoked object selected
- */
- private void updateSynchronous(EObject selectedInvoked) {
- if (hasOutParameters(selectedInvoked)) {
- isSynchronousButton.setSelection(true);
- isSynchronousButton.setEnabled(false);
- } else {
- isSynchronousButton.setEnabled(true);
- }
- }
-
- /**
- * Get the title of the is synchronous section
- *
- * @return section title
- */
- protected String getIsSynchronousSectionTitle() {
- return CustomMessages.CreateCallActionDialog_IsSynchronousTitle;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.forms.widgets.ExpandableComposite; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.ui.forms.widgets.ImageHyperlink; +import org.eclipse.ui.forms.widgets.ScrolledForm; +import org.eclipse.ui.forms.widgets.Section; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.InvocationAction; + +/** + * This class provides a dialog to initialize a CallAction at its creation. + */ +public abstract class CreateCallActionDialog extends CreateInvocationActionDialog { + + private Button isSynchronousButton; + + private boolean synchronous = false; + + /** + * Create a new dialog to initialize a CallAction. + * + * @param shell + * parent shell + * @param owner + * the activity that owns the action + */ + public CreateCallActionDialog(Shell shell, Activity owner, InvocationAction newAction) { + super(shell, owner, newAction); + } + + /** + * Create the IsSynchronous section. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + @Override + protected void createExtraSections(Composite pParent, FormToolkit pToolkit) { + createIsSynchronousSection(pParent, pToolkit); + } + + /** + * Refresh the enabled and disabled elements in various sections + * + * @param isSelectionSelected + * true if we choose to select an existing element, false if we + * choose to create an element + */ + @Override + protected void refreshSectionsEnable(boolean isSelectionSelected) { + super.refreshSectionsEnable(isSelectionSelected); + // handle synchronization constraint + if (isSelectionSelected) { + updateSynchronous(getSelectedInvoked()); + } else { + updateSynchronous(null); + } + } + + /** + * Define the object that will be invoked by the action (if selection mode + * is chosen) + * + * @param invokedElement + * the selected element + */ + @Override + protected void setInvokedSelection(EObject invokedElement) { + super.setInvokedSelection(invokedElement); + updateSynchronous(invokedElement); + } + + /** + * Create the section to ask whether the action must be synchronous. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + private void createIsSynchronousSection(Composite pParent, FormToolkit pToolkit) { + // create the section + String lSectionTitle = getIsSynchronousSectionTitle(); + Section lSection = pToolkit.createSection(pParent, ExpandableComposite.TWISTIE | ExpandableComposite.TITLE_BAR); + lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + if (lSectionTitle != null) { + lSection.setText(lSectionTitle); + } + ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreateCallActionDialog_IsSynchronousHelp, true); + lSection.setTextClient(componentHelp); + ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection); + lInsideScrolledForm.setExpandHorizontal(true); + lInsideScrolledForm.setExpandVertical(true); + Composite lBody = lInsideScrolledForm.getBody(); + GridLayout lLayout = new GridLayout(); + lLayout.numColumns = 1; + lBody.setLayout(lLayout); + // content of the section + isSynchronousButton = pToolkit.createButton(lBody, CustomMessages.CreateCallActionDialog_IsSynchronous, SWT.CHECK | SWT.WRAP); + isSynchronousButton.setSelection(true); + lInsideScrolledForm.reflow(true); + lSection.setClient(lInsideScrolledForm); + } + + /** + * Set correctly the invoked object, by creating it if needed. Then, + * notifies that the ok button of this dialog has been pressed. + * + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + * + */ + @Override + protected void okPressed() { + // register synchronous + synchronous = isSynchronousButton.getSelection(); + super.okPressed(); + } + + /** + * Get whether the CallAction must be synchronous. + * + * @return the invoked object to use. + */ + public boolean getIsSynchronous() { + return synchronous; + } + + /** + * Test is the invoked object has parameters which will generate output pins + * + * @param invokedObject + * the object whose parameters must be inspected + * @return true if there are parameters which will be mapped with output + * pins + */ + abstract protected boolean hasOutParameters(EObject invokedObject); + + /** + * + * @param selectedInvoked + * the invoked object selected + */ + private void updateSynchronous(EObject selectedInvoked) { + if (hasOutParameters(selectedInvoked)) { + isSynchronousButton.setSelection(true); + isSynchronousButton.setEnabled(false); + } else { + isSynchronousButton.setEnabled(true); + } + } + + /** + * Get the title of the is synchronous section + * + * @return section title + */ + protected String getIsSynchronousSectionTitle() { + return CustomMessages.CreateCallActionDialog_IsSynchronousTitle; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallBehaviorActionDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallBehaviorActionDialog.java index 50ae2431d3c..d7c41293419 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallBehaviorActionDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallBehaviorActionDialog.java @@ -1,198 +1,198 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Set;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EClassifier;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.Behavior;
-import org.eclipse.uml2.uml.BehavioredClassifier;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.Package;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.ParameterDirectionKind;
-import org.eclipse.uml2.uml.UMLPackage;
-
-import com.google.common.collect.Sets;
-
-/**
- * This class provides a dialog to initialize a CallBehaviorAction at its
- * creation.
- */
-public class CreateCallBehaviorActionDialog extends CreateCallActionDialog {
-
- /**
- * Create a new dialog to initialize a CallBehaviorAction.
- *
- * @param shell
- * parent shell
- * @param owner
- * the activity that owns the action
- */
- public CreateCallBehaviorActionDialog(Shell shell, Activity owner, InvocationAction newAction) {
- super(shell, owner, newAction);
- }
-
- /**
- * Get the id of the preference storing whether selection is the default
- * choice.
- *
- * @return preference id
- */
- @Override
- protected String getSelectionIsDefaultPreference() {
- return IActivityPreferenceConstants.PREF_NEW_CALL_BEHAVIOR_ACTION_SELECT_AS_DEFAULT;
- }
-
- /**
- * Get the id of the preference storing the last selected owner.
- *
- * @return preference id
- */
- @Override
- protected String getCreationDefaultOwnerPreference() {
- return IActivityPreferenceConstants.PREF_NEW_CALL_BEHAVIOR_ACTION_CREATION_OWNER;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionTitle()
- */
- @Override
- protected String getInvocationCreationSectionTitle() {
- return CustomMessages.CreateCallActionDialog_BehaviorInvocationCreationTitle;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionHelp()
- */
- @Override
- protected String getInvocationCreationSectionHelp() {
- return CustomMessages.CreateCallActionDialog_BehaviorInvocationCreationHelp;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationSelectionSectionTitle()
- */
- @Override
- protected String getInvocationSelectionSectionTitle() {
- return CustomMessages.CreateCallActionDialog_BehaviorInvocationSelectionTitle;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getTitle()
- */
- @Override
- protected String getTitle() {
- return CustomMessages.CreateCallActionDialog_BehaviorTitle;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getInvocationFeature()
- */
- @Override
- protected EReference getInvocationFeature() {
- return UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#hasOutParameters(org.eclipse.emf.ecore.EObject)
- */
- @Override
- protected boolean hasOutParameters(EObject invokedObject) {
- if (invokedObject instanceof Behavior) {
- for (Parameter param : ((Behavior) invokedObject).getOwnedParameters()) {
- if (ParameterDirectionKind.INOUT_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.OUT_LITERAL.equals(param.getDirection())) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedParents()
- */
- @Override
- protected Set<? extends EClassifier> getPossibleInvokedParents(EObject actionParent) {
- return Sets.newHashSet(UMLPackage.Literals.PACKAGE, UMLPackage.Literals.BEHAVIORED_CLASSIFIER);
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#isPossibleInvokedParent(org.eclipse.emf.ecore.EObject)
- */
- @Override
- protected boolean isPossibleInvokedParent(EObject parent) {
- return parent instanceof Package || parent instanceof BehavioredClassifier;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedTypes()
- */
- @Override
- protected EClass[] getPossibleInvokedTypes() {
- return new EClass[] { UMLPackage.eINSTANCE.getActivity(), UMLPackage.eINSTANCE.getInteraction(), UMLPackage.eINSTANCE.getOpaqueBehavior(), UMLPackage.eINSTANCE.getFunctionBehavior(), UMLPackage.eINSTANCE.getStateMachine(),
- UMLPackage.eINSTANCE.getProtocolStateMachine() };
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getCreationLabel()
- */
- @Override
- protected String getCreationLabel() {
- return CustomMessages.CreateCallActionDialog_CreateBehavior;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getSelectionLabel()
- */
- @Override
- protected String getSelectionLabel() {
- return CustomMessages.CreateCallActionDialog_SelectBehavior;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getParentImage()
- */
- @Override
- protected Image getParentImage() {
- return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage());
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Set; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.Behavior; +import org.eclipse.uml2.uml.BehavioredClassifier; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.Package; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.ParameterDirectionKind; +import org.eclipse.uml2.uml.UMLPackage; + +import com.google.common.collect.Sets; + +/** + * This class provides a dialog to initialize a CallBehaviorAction at its + * creation. + */ +public class CreateCallBehaviorActionDialog extends CreateCallActionDialog { + + /** + * Create a new dialog to initialize a CallBehaviorAction. + * + * @param shell + * parent shell + * @param owner + * the activity that owns the action + */ + public CreateCallBehaviorActionDialog(Shell shell, Activity owner, InvocationAction newAction) { + super(shell, owner, newAction); + } + + /** + * Get the id of the preference storing whether selection is the default + * choice. + * + * @return preference id + */ + @Override + protected String getSelectionIsDefaultPreference() { + return IActivityPreferenceConstants.PREF_NEW_CALL_BEHAVIOR_ACTION_SELECT_AS_DEFAULT; + } + + /** + * Get the id of the preference storing the last selected owner. + * + * @return preference id + */ + @Override + protected String getCreationDefaultOwnerPreference() { + return IActivityPreferenceConstants.PREF_NEW_CALL_BEHAVIOR_ACTION_CREATION_OWNER; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionTitle() + */ + @Override + protected String getInvocationCreationSectionTitle() { + return CustomMessages.CreateCallActionDialog_BehaviorInvocationCreationTitle; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionHelp() + */ + @Override + protected String getInvocationCreationSectionHelp() { + return CustomMessages.CreateCallActionDialog_BehaviorInvocationCreationHelp; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationSelectionSectionTitle() + */ + @Override + protected String getInvocationSelectionSectionTitle() { + return CustomMessages.CreateCallActionDialog_BehaviorInvocationSelectionTitle; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getTitle() + */ + @Override + protected String getTitle() { + return CustomMessages.CreateCallActionDialog_BehaviorTitle; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getInvocationFeature() + */ + @Override + protected EReference getInvocationFeature() { + return UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior(); + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#hasOutParameters(org.eclipse.emf.ecore.EObject) + */ + @Override + protected boolean hasOutParameters(EObject invokedObject) { + if (invokedObject instanceof Behavior) { + for (Parameter param : ((Behavior) invokedObject).getOwnedParameters()) { + if (ParameterDirectionKind.INOUT_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.OUT_LITERAL.equals(param.getDirection())) { + return true; + } + } + } + return false; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedParents() + */ + @Override + protected Set<? extends EClassifier> getPossibleInvokedParents(EObject actionParent) { + return Sets.newHashSet(UMLPackage.Literals.PACKAGE, UMLPackage.Literals.BEHAVIORED_CLASSIFIER); + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#isPossibleInvokedParent(org.eclipse.emf.ecore.EObject) + */ + @Override + protected boolean isPossibleInvokedParent(EObject parent) { + return parent instanceof Package || parent instanceof BehavioredClassifier; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedTypes() + */ + @Override + protected EClass[] getPossibleInvokedTypes() { + return new EClass[] { UMLPackage.eINSTANCE.getActivity(), UMLPackage.eINSTANCE.getInteraction(), UMLPackage.eINSTANCE.getOpaqueBehavior(), UMLPackage.eINSTANCE.getFunctionBehavior(), UMLPackage.eINSTANCE.getStateMachine(), + UMLPackage.eINSTANCE.getProtocolStateMachine() }; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getCreationLabel() + */ + @Override + protected String getCreationLabel() { + return CustomMessages.CreateCallActionDialog_CreateBehavior; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getSelectionLabel() + */ + @Override + protected String getSelectionLabel() { + return CustomMessages.CreateCallActionDialog_SelectBehavior; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getParentImage() + */ + @Override + protected Image getParentImage() { + return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage()); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallOperationActionDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallOperationActionDialog.java index 29fafe771c9..89f715c3f4f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallOperationActionDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateCallOperationActionDialog.java @@ -1,196 +1,196 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Set;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EClassifier;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.Class;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.Operation;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.ParameterDirectionKind;
-import org.eclipse.uml2.uml.UMLPackage;
-
-import com.google.common.collect.Sets;
-
-/**
- * This class provides a dialog to initialize a CallOperationAction at its
- * creation.
- */
-public class CreateCallOperationActionDialog extends CreateCallActionDialog {
-
- /**
- * Create a new dialog to initialize a CallOperationAction.
- *
- * @param shell
- * parent shell
- * @param owner
- * the activity that owns the action
- */
- public CreateCallOperationActionDialog(Shell shell, Activity owner, InvocationAction newAction) {
- super(shell, owner, newAction);
- }
-
- /**
- * Get the id of the preference storing whether selection is the default
- * choice.
- *
- * @return preference id
- */
- @Override
- protected String getSelectionIsDefaultPreference() {
- return IActivityPreferenceConstants.PREF_NEW_CALL_OPERATION_ACTION_SELECT_AS_DEFAULT;
- }
-
- /**
- * Get the id of the preference storing the last selected owner.
- *
- * @return preference id
- */
- @Override
- protected String getCreationDefaultOwnerPreference() {
- return IActivityPreferenceConstants.PREF_NEW_CALL_OPERATION_ACTION_CREATION_OWNER;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getInvocationFeature()
- */
- @Override
- protected EReference getInvocationFeature() {
- return UMLPackage.eINSTANCE.getCallOperationAction_Operation();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedTypes()
- */
- @Override
- protected EClass[] getPossibleInvokedTypes() {
- return new EClass[] { UMLPackage.eINSTANCE.getOperation() };
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#hasOutParameters(org.eclipse.emf.ecore.EObject)
- */
- @Override
- protected boolean hasOutParameters(EObject invokedObject) {
- if (invokedObject instanceof Operation) {
- for (Parameter param : ((Operation) invokedObject).getOwnedParameters()) {
- if (ParameterDirectionKind.INOUT_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.OUT_LITERAL.equals(param.getDirection())) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedParents()
- */
- @Override
- protected Set<? extends EClassifier> getPossibleInvokedParents(EObject actionParent) {
- return Sets.newHashSet(UMLPackage.Literals.CLASS);
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#isPossibleInvokedParent(org.eclipse.emf.ecore.EObject)
- */
- @Override
- protected boolean isPossibleInvokedParent(EObject parent) {
- return parent instanceof Class;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionTitle()
- */
- @Override
- protected String getInvocationCreationSectionTitle() {
- return CustomMessages.CreateCallActionDialog_OperationInvocationCreationTitle;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionHelp()
- */
- @Override
- protected String getInvocationCreationSectionHelp() {
- return CustomMessages.CreateCallActionDialog_OperationInvocationCreationHelp;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationSelectionSectionTitle()
- */
- @Override
- protected String getInvocationSelectionSectionTitle() {
- return CustomMessages.CreateCallActionDialog_OperationInvocationSelectionTitle;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getTitle()
- */
- @Override
- protected String getTitle() {
- return CustomMessages.CreateCallActionDialog_OperationTitle;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getCreationLabel()
- */
- @Override
- protected String getCreationLabel() {
- return CustomMessages.CreateCallActionDialog_CreateOperation;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getSelectionLabel()
- */
- @Override
- protected String getSelectionLabel() {
- return CustomMessages.CreateCallActionDialog_SelectOperation;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getParentImage()
- */
- @Override
- protected Image getParentImage() {
- return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getClass_());
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Set; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.Class; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.Operation; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.ParameterDirectionKind; +import org.eclipse.uml2.uml.UMLPackage; + +import com.google.common.collect.Sets; + +/** + * This class provides a dialog to initialize a CallOperationAction at its + * creation. + */ +public class CreateCallOperationActionDialog extends CreateCallActionDialog { + + /** + * Create a new dialog to initialize a CallOperationAction. + * + * @param shell + * parent shell + * @param owner + * the activity that owns the action + */ + public CreateCallOperationActionDialog(Shell shell, Activity owner, InvocationAction newAction) { + super(shell, owner, newAction); + } + + /** + * Get the id of the preference storing whether selection is the default + * choice. + * + * @return preference id + */ + @Override + protected String getSelectionIsDefaultPreference() { + return IActivityPreferenceConstants.PREF_NEW_CALL_OPERATION_ACTION_SELECT_AS_DEFAULT; + } + + /** + * Get the id of the preference storing the last selected owner. + * + * @return preference id + */ + @Override + protected String getCreationDefaultOwnerPreference() { + return IActivityPreferenceConstants.PREF_NEW_CALL_OPERATION_ACTION_CREATION_OWNER; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getInvocationFeature() + */ + @Override + protected EReference getInvocationFeature() { + return UMLPackage.eINSTANCE.getCallOperationAction_Operation(); + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedTypes() + */ + @Override + protected EClass[] getPossibleInvokedTypes() { + return new EClass[] { UMLPackage.eINSTANCE.getOperation() }; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#hasOutParameters(org.eclipse.emf.ecore.EObject) + */ + @Override + protected boolean hasOutParameters(EObject invokedObject) { + if (invokedObject instanceof Operation) { + for (Parameter param : ((Operation) invokedObject).getOwnedParameters()) { + if (ParameterDirectionKind.INOUT_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.OUT_LITERAL.equals(param.getDirection())) { + return true; + } + } + } + return false; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedParents() + */ + @Override + protected Set<? extends EClassifier> getPossibleInvokedParents(EObject actionParent) { + return Sets.newHashSet(UMLPackage.Literals.CLASS); + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#isPossibleInvokedParent(org.eclipse.emf.ecore.EObject) + */ + @Override + protected boolean isPossibleInvokedParent(EObject parent) { + return parent instanceof Class; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionTitle() + */ + @Override + protected String getInvocationCreationSectionTitle() { + return CustomMessages.CreateCallActionDialog_OperationInvocationCreationTitle; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionHelp() + */ + @Override + protected String getInvocationCreationSectionHelp() { + return CustomMessages.CreateCallActionDialog_OperationInvocationCreationHelp; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationSelectionSectionTitle() + */ + @Override + protected String getInvocationSelectionSectionTitle() { + return CustomMessages.CreateCallActionDialog_OperationInvocationSelectionTitle; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getTitle() + */ + @Override + protected String getTitle() { + return CustomMessages.CreateCallActionDialog_OperationTitle; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getCreationLabel() + */ + @Override + protected String getCreationLabel() { + return CustomMessages.CreateCallActionDialog_CreateOperation; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getSelectionLabel() + */ + @Override + protected String getSelectionLabel() { + return CustomMessages.CreateCallActionDialog_SelectOperation; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getParentImage() + */ + @Override + protected Image getParentImage() { + return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getClass_()); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateInvocationActionDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateInvocationActionDialog.java index 6daab642466..659fb22aac1 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateInvocationActionDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateInvocationActionDialog.java @@ -1,791 +1,791 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Collections;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.eclipse.emf.common.command.Command;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EClassifier;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.edit.command.AddCommand;
-import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.ComboViewer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.papyrus.infra.core.services.ServiceException;
-import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForEObject;
-import org.eclipse.papyrus.infra.services.labelprovider.service.LabelProviderService;
-import org.eclipse.papyrus.infra.ui.util.EditorUtils;
-import org.eclipse.papyrus.infra.widgets.editors.TreeSelectorDialog;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.Messages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes;
-import org.eclipse.papyrus.uml.diagram.common.actions.LabelHelper;
-import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory;
-import org.eclipse.papyrus.uml.tools.providers.UMLContentProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.FormDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ImageHyperlink;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.NamedElement;
-import org.eclipse.uml2.uml.UMLFactory;
-
-/**
- * This class provides a dialog to initialize a CallAction at its creation.
- */
-public abstract class CreateInvocationActionDialog extends FormDialog {
-
- protected static final String MAP_FORMAT = "%s|%s";
-
- private static final Pattern MAP_PATTERN = Pattern.compile("(.*?)\\|(.*)");
-
- private Button creationRadio;
-
- protected Button selectionRadio;
-
- private Text selectionText;
-
- private Button selectionButton;
-
- private Text creationNameText;
-
- private Text creationParentText;
-
- private Button creationParentButton;
-
- protected EObject selectedInvoked = null;
-
- protected EObject selectedParent = null;
-
- private Activity actionParent;
-
- protected EClass selectedType = null;
-
- protected String selectedName = null;
-
- private ComboViewer typeComboViewer = null;
-
- private Combo creationTypeCombo = null;
-
- private ILabelProvider labelProvider;
-
- /**
- * New Object about to be created
- */
- private InvocationAction invocationAction;
-
-
- /**
- * Create a new dialog to initialize a CallAction.
- *
- * @param shell
- * parent shell
- * @param owner
- * the activity that owns the action
- */
- public CreateInvocationActionDialog(Shell shell, Activity owner, InvocationAction newAction) {
- super(shell);
- actionParent = owner;
- selectedParent = getDefaultParent(owner);
- labelProvider = getCustomLabelProvider();
- this.invocationAction = newAction;
- try {
- LabelProviderService labelProviderService = ServiceUtilsForEObject.getInstance().getServiceRegistry(owner).getService(LabelProviderService.class);
- labelProvider = labelProviderService.getLabelProvider(owner);
- } catch (ServiceException e) {
- e.printStackTrace();
- }
- }
-
-
-
-
- /**
- * Invocation action about to be created
- *
- * @return
- */
- public InvocationAction getInvocationAction() {
- return invocationAction;
- }
-
-
-
- /**
- * Get the parent to propose as default choice for the element creation
- *
- * @param owner
- * the invocation action's owner
- * @return default parent to select
- */
- private EObject getDefaultParent(Activity owner) {
- // try recovering last user choice from preferences
- IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
- String ownerString = prefStore.getString(getCreationDefaultOwnerPreference());
- if (ownerString != null && !"".equals(ownerString)) {
- Matcher match = MAP_PATTERN.matcher(ownerString);
- if (match.matches() && match.groupCount() >= 2) {
- String ressURI = match.group(1);
- String parentURI = match.group(2);
- if (owner.eResource().getURI().toString().equals(ressURI)) {
- EObject parent = owner.eResource().getEObject(parentURI);
- if (parent != null) {
- return parent;
- }
- }
- }
- }
- // recover default choice from the action's owner
- EObject parent = owner;
- while (!isPossibleInvokedParent(parent)) {
- parent = parent.eContainer();
- }
- return parent;
- }
-
- /**
- * Create the form to :
- *
- * - ask the user to choose or create an invoked element.
- *
- * - decide whether the action is synchronous.
- *
- * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm)
- */
- @Override
- protected void createFormContent(IManagedForm pForm) {
- pForm.getForm().setText(getTitle());
- ScrolledForm scrolledForm = pForm.getForm();
- FormToolkit toolkit = pForm.getToolkit();
- Composite parent = scrolledForm.getBody();
- parent.setLayout(new GridLayout());
- createInvocationCreationSection(scrolledForm.getBody(), toolkit);
- createInvocationSelectionSection(scrolledForm.getBody(), toolkit);
- createExtraSections(scrolledForm.getBody(), toolkit);
- refreshSectionsEnable(isSelectionDefault());
- hookListeners();
- // invoked name is set after listeners, since we count on listener to
- // update it properly
- setInvokedName(null);
- scrolledForm.reflow(true);
- }
-
- /**
- * Get whether the selection of an existing element is the default
- *
- * @return true if selection by default
- */
- protected boolean isSelectionDefault() {
- IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
- return prefStore.getBoolean(getSelectionIsDefaultPreference());
- }
-
- /**
- * Get the id of the preference storing whether selection is the default
- * choice.
- *
- * @return preference id
- */
- abstract protected String getSelectionIsDefaultPreference();
-
- /**
- * Get the id of the preference storing the last selected owner.
- *
- * @return preference id
- */
- abstract protected String getCreationDefaultOwnerPreference();
-
- /**
- * Create the other needed sections. Subclasses can override this method.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- protected void createExtraSections(Composite pParent, FormToolkit pToolkit) {
- // do nothing
- }
-
- /**
- * Adds buttons to this dialog's button bar.
- *
- * @param parent
- * the button bar composite
- */
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- super.createButtonsForButtonBar(parent);
- refreshOkButton();
- }
-
- /**
- * Create the section to ask the user to choose or create an invoked
- * element.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- private void createInvocationSelectionSection(Composite pParent, FormToolkit pToolkit) {
- // create the section
- String lSectionTitle = getInvocationSelectionSectionTitle();
- Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR);
- lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (lSectionTitle != null) {
- lSection.setText(lSectionTitle);
- }
- ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection);
- lInsideScrolledForm.setExpandHorizontal(true);
- lInsideScrolledForm.setExpandVertical(true);
- Composite lBody = lInsideScrolledForm.getBody();
- GridLayout lLayout = new GridLayout();
- lLayout.numColumns = 3;
- lBody.setLayout(lLayout);
- // content of the section
- selectionRadio = pToolkit.createButton(lBody, getSelectionLabel(), SWT.RADIO);
- // selectionRadio.setSelection(false);
- selectionRadio.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
- pToolkit.createLabel(lBody, getInvokedObjectLabel(), SWT.NONE);
- selectionText = pToolkit.createText(lBody, "", SWT.BORDER | SWT.READ_ONLY);
- selectionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- selectionButton = pToolkit.createButton(lBody, "...", SWT.FLAT);
- Image image = UMLElementTypes.getImage(getInvocationFeature());
- selectionButton.setImage(image);
- selectionButton.setLayoutData(new GridData(SWT.NONE));
- lInsideScrolledForm.reflow(true);
- lSection.setClient(lInsideScrolledForm);
- }
-
- /**
- * Create the section to ask the user to choose or create an invoked
- * element.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- private void createInvocationCreationSection(Composite pParent, FormToolkit pToolkit) {
- // create the section
- String lSectionTitle = getInvocationCreationSectionTitle();
- Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR);
- lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (lSectionTitle != null) {
- lSection.setText(lSectionTitle);
- }
- ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, getInvocationCreationSectionHelp(), true);
- lSection.setTextClient(componentHelp);
- ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection);
- lInsideScrolledForm.setExpandHorizontal(true);
- lInsideScrolledForm.setExpandVertical(true);
- Composite lBody = lInsideScrolledForm.getBody();
- GridLayout lLayout = new GridLayout();
- lLayout.numColumns = 3;
- lBody.setLayout(lLayout);
- // content of the section
- creationRadio = pToolkit.createButton(lBody, getCreationLabel(), SWT.RADIO);
- // creationRadio.setSelection(true);
- creationRadio.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1));
- if (getPossibleInvokedTypes().length == 1) {
- selectedType = getPossibleInvokedTypes()[0];
- } else {
- pToolkit.createLabel(lBody, getInvokedTypeLabel(), SWT.NONE);
- creationTypeCombo = new Combo(lBody, SWT.DROP_DOWN | SWT.READ_ONLY);
- typeComboViewer = new ComboViewer(creationTypeCombo);
- pToolkit.adapt(creationTypeCombo);
- creationTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- typeComboViewer.setLabelProvider(labelProvider);
- typeComboViewer.add(getPossibleInvokedTypes());
- if (getPossibleInvokedTypes().length > 1) {
- // initialize selection
- typeComboViewer.setSelection(new StructuredSelection(getPossibleInvokedTypes()[0]));
- selectedType = getPossibleInvokedTypes()[0];
- }
- }
- pToolkit.createLabel(lBody, getInvokedNameLabel(), SWT.NONE);
- creationNameText = pToolkit.createText(lBody, "", SWT.BORDER);
- creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- creationNameText.setFocus();
- pToolkit.createLabel(lBody, getInvokedParentLabel(), SWT.NONE);
- creationParentText = pToolkit.createText(lBody, labelProvider.getText(selectedParent), SWT.BORDER | SWT.READ_ONLY);
- creationParentText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- creationParentButton = pToolkit.createButton(lBody, "...", SWT.FLAT);
- Image image = getParentImage();
- creationParentButton.setImage(image);
- creationParentButton.setLayoutData(new GridData(SWT.NONE));
- lInsideScrolledForm.reflow(true);
- lSection.setClient(lInsideScrolledForm);
- }
-
- /**
- * Set correctly the invoked object, by creating it if needed. Then,
- * notifies that the ok button of this dialog has been pressed.
- *
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- *
- */
- @Override
- protected void okPressed() {
- boolean isSelectionSelected = selectionRadio.getSelection();
- // create element if needed
- if (!isSelectionSelected) {
- selectedInvoked = UMLFactory.eINSTANCE.create(selectedType);
- if (selectedInvoked instanceof NamedElement) {
- ((NamedElement) selectedInvoked).setName(selectedName);
- }
- addInvokedInParent(selectedParent, selectedInvoked);
- }
- // store user choices in preference
- IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
- // store choice between selection and creation
- prefStore.setValue(getSelectionIsDefaultPreference(), isSelectionSelected);
- if (!isSelectionSelected) {
- // store the owner choice
- String ressUri = selectedParent.eResource().getURI().toString();
- String parentURI = selectedParent.eResource().getURIFragment(selectedParent);
- String prefValue = String.format(MAP_FORMAT, ressUri, parentURI);
- prefStore.setValue(getCreationDefaultOwnerPreference(), prefValue);
- }
- super.okPressed();
- }
-
- /**
- * Get the invoked object that have been selected or created.
- *
- * @return the invoked object to use.
- */
- public EObject getSelectedInvoked() {
- return selectedInvoked;
- }
-
- /**
- * Add listeners to widgets
- */
- private void hookListeners() {
- // listener to choose active section
- SelectionListener selectCreateListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (creationRadio.equals(e.getSource())) {
- refreshSectionsEnable(false);
- } else {
- refreshSectionsEnable(true);
- }
- refreshOkButton();
- }
- };
- selectionRadio.addSelectionListener(selectCreateListener);
- creationRadio.addSelectionListener(selectCreateListener);
- // listener to select existing element
- SelectionListener selectBtnListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleChooseInvoked();
- refreshOkButton();
- }
- };
- selectionButton.addSelectionListener(selectBtnListener);
- if (creationTypeCombo != null && typeComboViewer != null) {
- // listener to select invocation type
- ModifyListener lTypeListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- ISelection sel = typeComboViewer.getSelection();
- if (sel instanceof StructuredSelection) {
- Object type = ((StructuredSelection) sel).getFirstElement();
- if (type instanceof EClass) {
- selectedType = (EClass) type;
- } else {
- selectedType = null;
- }
- // reset name
- setInvokedName(null);
- refreshOkButton();
- }
- }
- };
- creationTypeCombo.addModifyListener(lTypeListener);
- }
- // listener to invocation element name
- ModifyListener lNameListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- setInvokedName(creationNameText.getText());
- }
- };
- creationNameText.addModifyListener(lNameListener);
- // listener to select new element parent
- SelectionListener selectParentBtnListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleChooseParent();
- // reset name if not set
- if (selectedName == null) {
- setInvokedName(null);
- }
- refreshOkButton();
- }
- };
- creationParentButton.addSelectionListener(selectParentBtnListener);
- }
-
- /**
- * Set the name chosen for the invoked element
- *
- * @param text
- * the text string or null for auto-initialization
- */
- private void setInvokedName(String text) {
- String name = text;
- if (text == null && selectedParent != null && selectedType != null) {
- name = LabelHelper.INSTANCE.findName(selectedParent, selectedType);
- // the name assignment will be performed by listener's call
- creationNameText.setText(name);
- } else if (name != null && !"".equals(name.trim())) {
- selectedName = name.trim();
- Color black = creationNameText.getDisplay().getSystemColor(SWT.COLOR_BLACK);
- creationNameText.setForeground(black);
- refreshOkButton();
- } else {
- selectedName = null;
- Color red = creationNameText.getDisplay().getSystemColor(SWT.COLOR_RED);
- creationNameText.setForeground(red);
- refreshOkButton();
- }
- }
-
- /**
- * Open the dialog to choose the existing element to select
- *
- */
- protected void handleChooseInvoked() {
-
-
- TreeSelectorDialog dialog = new TreeSelectorDialog(Display.getDefault().getActiveShell());
- dialog.setContentProvider(new UMLContentProvider(getInvocationAction(), getInvocationFeature()));
-
- dialog.setLabelProvider(labelProvider);
- // UMLMultiEClassifierTreeSelectorDialog dialog = new UMLMultiEClassifierTreeSelectorDialog(getShell(), actionParent, Collections.singleton(getInvocationFeature().getEType()));
- dialog.setMessage(Messages.UMLModelingAssistantProviderMessage);
- dialog.setTitle(Messages.UMLModelingAssistantProviderTitle);
- if (dialog.open() == org.eclipse.jface.window.Window.OK) {
- Object[] result = dialog.getResult();
- if (result != null && result.length > 0 && result[0] instanceof EObject) {
- setInvokedSelection((EObject) result[0]);
- }
- }
- }
-
- /**
- * Define the object that will be invoked by the action (if selection mode
- * is chosen)
- *
- * @param invokedElement
- * the selected element
- */
- protected void setInvokedSelection(EObject invokedElement) {
- selectedInvoked = invokedElement;
- if (selectedInvoked instanceof NamedElement) {
- selectionText.setText(labelProvider.getText(selectedInvoked));
- } else {
- selectionText.setText("");
- }
- }
-
- /**
- * Open the dialog to choose the parent of element to create
- *
- */
- private void handleChooseParent() {
- GetObjectsOfTypeListSelectionDialog dialog = new GetObjectsOfTypeListSelectionDialog(getParentShell(), labelProvider, actionParent, false);
- for (EClassifier type : getPossibleInvokedParents(actionParent)) {
- dialog.addElementsOfType(type);
- }
- if (dialog.open() == Window.OK) {
- Object firstResult = dialog.getFirstResult();
- if (firstResult instanceof EObject) {
- setInvokedParent((EObject) dialog.getFirstResult());
- }
- }
- }
-
- /**
- * Define the object in which invoked object will be created (if creation
- * mode is chosen)
- *
- * @param invokedParent
- * the selected parent
- */
- private void setInvokedParent(EObject invokedParent) {
- selectedParent = invokedParent;
- if (selectedParent instanceof NamedElement) {
- creationParentText.setText(labelProvider.getText(selectedParent));
- } else {
- creationParentText.setText("");
- }
- }
-
- /**
- * Refresh the enabled and disabled elements in various sections
- *
- * @param isSelectionSelected
- * true if we choose to select an existing element, false if we
- * choose to create an element
- */
- protected void refreshSectionsEnable(boolean isSelectionSelected) {
- // handle radio button value
- if (isSelectionSelected) {
- creationRadio.setSelection(false);
- if (!selectionRadio.getSelection()) {
- selectionRadio.setSelection(true);
- }
- } else {
- selectionRadio.setSelection(false);
- if (!creationRadio.getSelection()) {
- creationRadio.setSelection(true);
- }
- }
- // handle disabled section
- selectionText.setEnabled(isSelectionSelected);
- selectionButton.setEnabled(isSelectionSelected);
- if (creationTypeCombo != null) {
- creationTypeCombo.setEnabled(!isSelectionSelected);
- }
- creationNameText.setEnabled(!isSelectionSelected);
- creationNameText.setFocus();
- creationParentText.setEnabled(!isSelectionSelected);
- creationParentButton.setEnabled(!isSelectionSelected);
- }
-
- /**
- * Refresh the OK button activation
- */
- private void refreshOkButton() {
- boolean isSelectionSelected = selectionRadio.getSelection();
- if (getButton(IDialogConstants.OK_ID) != null && !getButton(IDialogConstants.OK_ID).isDisposed()) {
- if (isSelectionSelected) {
- getButton(IDialogConstants.OK_ID).setEnabled(selectedInvoked != null);
- } else {
- getButton(IDialogConstants.OK_ID).setEnabled(selectedParent != null && selectedType != null && selectedName != null);
- }
- }
- }
-
- /**
- * Add the created invoked object to its selected parent
- */
- protected void addInvokedInParent(EObject selectedParent, EObject createdInvoked) {
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- // Let the command find the relation on its own.
- Command addCmd = AddCommand.create(editingdomain, selectedParent, null, Collections.singleton(createdInvoked));
- addCmd.execute();
- }
-
- /**
- * Gets the custom label provider that parses label for EClass
- *
- * @return the custom label provider
- */
- private ILabelProvider getCustomLabelProvider() {
- AdapterFactoryLabelProvider adapterFactory = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()) {
-
- /**
- * Override label provider for EClass
- *
- * @see org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider#getText(java.lang.Object)
- */
- @Override
- public String getText(Object object) {
- String text = super.getText(object);
- if (object instanceof EClass) {
- return text.substring(0, text.indexOf("[") - 1);
- } else {
- return text;
- }
- }
- };
- return adapterFactory;
- }
-
- /**
- * Get the possible types for creating a new invoked element
- *
- * @return array of EClasses
- */
- abstract protected EClass[] getPossibleInvokedTypes();
-
- /**
- * Get the possible parents of the new invoked element
- *
- * @param actionParent
- * the parent of the action
- * @return collection of EObject possible owners
- */
- abstract protected Set<? extends EClassifier> getPossibleInvokedParents(EObject actionParent);
-
- /**
- * Whether element can be parent of the new invoked element
- *
- * @param parent
- * the parent to test
- * @return true if parent is of an appropriate eclass
- */
- abstract protected boolean isPossibleInvokedParent(EObject parent);
-
- /**
- * Get feature referencing the invoked object
- *
- * @return invocation feature
- */
- abstract protected EReference getInvocationFeature();
-
- /**
- * Get the image for the parent selection button
- *
- * @return image
- */
- abstract protected Image getParentImage();
-
- /**
- * Get the label to present the name of the invoked object
- *
- * @return label
- */
- protected String getInvokedNameLabel() {
- return CustomMessages.CreateCallActionDialog_NameLabel;
- }
-
- /**
- * Get the label to present the type of the invoked object
- *
- * @return label
- */
- protected String getInvokedTypeLabel() {
- return CustomMessages.CreateCallActionDialog_TypeLabel;
- }
-
- /**
- * Get the label to present parent of the invoked object
- *
- * @return label
- */
- protected String getInvokedParentLabel() {
- return CustomMessages.CreateCallActionDialog_ParentLabel;
- }
-
- /**
- * Get the label to present the invoked object
- *
- * @return label
- */
- protected String getInvokedObjectLabel() {
- return getInvocationFeature().getEReferenceType().getName() + ":";
- }
-
- /**
- * Get the title of the dialog
- *
- * @return dialog title
- */
- abstract protected String getTitle();
-
- /**
- * Get the title of the invocation creation section
- *
- * @return section title
- */
- abstract protected String getInvocationCreationSectionTitle();
-
- /**
- * Get the help description of the invocation creation section
- *
- * @return section title
- */
- abstract protected String getInvocationCreationSectionHelp();
-
- /**
- * Get the title of the invocation selection section
- *
- * @return section title
- */
- abstract protected String getInvocationSelectionSectionTitle();
-
- /**
- * Get the label to choose to select an existing element
- *
- * @return label
- */
- abstract protected String getSelectionLabel();
-
- /**
- * Get the label to choose to create a new element
- *
- * @return label
- */
- abstract protected String getCreationLabel();
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Collections; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.edit.command.AddCommand; +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.viewers.ComboViewer; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.papyrus.infra.core.services.ServiceException; +import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForEObject; +import org.eclipse.papyrus.infra.services.labelprovider.service.LabelProviderService; +import org.eclipse.papyrus.infra.ui.util.EditorUtils; +import org.eclipse.papyrus.infra.widgets.editors.TreeSelectorDialog; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.Messages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes; +import org.eclipse.papyrus.uml.diagram.common.actions.LabelHelper; +import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory; +import org.eclipse.papyrus.uml.tools.providers.UMLContentProvider; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.forms.FormDialog; +import org.eclipse.ui.forms.IManagedForm; +import org.eclipse.ui.forms.widgets.ExpandableComposite; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.ui.forms.widgets.ImageHyperlink; +import org.eclipse.ui.forms.widgets.ScrolledForm; +import org.eclipse.ui.forms.widgets.Section; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.UMLFactory; + +/** + * This class provides a dialog to initialize a CallAction at its creation. + */ +public abstract class CreateInvocationActionDialog extends FormDialog { + + protected static final String MAP_FORMAT = "%s|%s"; + + private static final Pattern MAP_PATTERN = Pattern.compile("(.*?)\\|(.*)"); + + private Button creationRadio; + + protected Button selectionRadio; + + private Text selectionText; + + private Button selectionButton; + + private Text creationNameText; + + private Text creationParentText; + + private Button creationParentButton; + + protected EObject selectedInvoked = null; + + protected EObject selectedParent = null; + + private Activity actionParent; + + protected EClass selectedType = null; + + protected String selectedName = null; + + private ComboViewer typeComboViewer = null; + + private Combo creationTypeCombo = null; + + private ILabelProvider labelProvider; + + /** + * New Object about to be created + */ + private InvocationAction invocationAction; + + + /** + * Create a new dialog to initialize a CallAction. + * + * @param shell + * parent shell + * @param owner + * the activity that owns the action + */ + public CreateInvocationActionDialog(Shell shell, Activity owner, InvocationAction newAction) { + super(shell); + actionParent = owner; + selectedParent = getDefaultParent(owner); + labelProvider = getCustomLabelProvider(); + this.invocationAction = newAction; + try { + LabelProviderService labelProviderService = ServiceUtilsForEObject.getInstance().getServiceRegistry(owner).getService(LabelProviderService.class); + labelProvider = labelProviderService.getLabelProvider(owner); + } catch (ServiceException e) { + e.printStackTrace(); + } + } + + + + + /** + * Invocation action about to be created + * + * @return + */ + public InvocationAction getInvocationAction() { + return invocationAction; + } + + + + /** + * Get the parent to propose as default choice for the element creation + * + * @param owner + * the invocation action's owner + * @return default parent to select + */ + private EObject getDefaultParent(Activity owner) { + // try recovering last user choice from preferences + IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + String ownerString = prefStore.getString(getCreationDefaultOwnerPreference()); + if (ownerString != null && !"".equals(ownerString)) { + Matcher match = MAP_PATTERN.matcher(ownerString); + if (match.matches() && match.groupCount() >= 2) { + String ressURI = match.group(1); + String parentURI = match.group(2); + if (owner.eResource().getURI().toString().equals(ressURI)) { + EObject parent = owner.eResource().getEObject(parentURI); + if (parent != null) { + return parent; + } + } + } + } + // recover default choice from the action's owner + EObject parent = owner; + while (!isPossibleInvokedParent(parent)) { + parent = parent.eContainer(); + } + return parent; + } + + /** + * Create the form to : + * + * - ask the user to choose or create an invoked element. + * + * - decide whether the action is synchronous. + * + * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm) + */ + @Override + protected void createFormContent(IManagedForm pForm) { + pForm.getForm().setText(getTitle()); + ScrolledForm scrolledForm = pForm.getForm(); + FormToolkit toolkit = pForm.getToolkit(); + Composite parent = scrolledForm.getBody(); + parent.setLayout(new GridLayout()); + createInvocationCreationSection(scrolledForm.getBody(), toolkit); + createInvocationSelectionSection(scrolledForm.getBody(), toolkit); + createExtraSections(scrolledForm.getBody(), toolkit); + refreshSectionsEnable(isSelectionDefault()); + hookListeners(); + // invoked name is set after listeners, since we count on listener to + // update it properly + setInvokedName(null); + scrolledForm.reflow(true); + } + + /** + * Get whether the selection of an existing element is the default + * + * @return true if selection by default + */ + protected boolean isSelectionDefault() { + IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + return prefStore.getBoolean(getSelectionIsDefaultPreference()); + } + + /** + * Get the id of the preference storing whether selection is the default + * choice. + * + * @return preference id + */ + abstract protected String getSelectionIsDefaultPreference(); + + /** + * Get the id of the preference storing the last selected owner. + * + * @return preference id + */ + abstract protected String getCreationDefaultOwnerPreference(); + + /** + * Create the other needed sections. Subclasses can override this method. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + protected void createExtraSections(Composite pParent, FormToolkit pToolkit) { + // do nothing + } + + /** + * Adds buttons to this dialog's button bar. + * + * @param parent + * the button bar composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + super.createButtonsForButtonBar(parent); + refreshOkButton(); + } + + /** + * Create the section to ask the user to choose or create an invoked + * element. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + private void createInvocationSelectionSection(Composite pParent, FormToolkit pToolkit) { + // create the section + String lSectionTitle = getInvocationSelectionSectionTitle(); + Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); + lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + if (lSectionTitle != null) { + lSection.setText(lSectionTitle); + } + ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection); + lInsideScrolledForm.setExpandHorizontal(true); + lInsideScrolledForm.setExpandVertical(true); + Composite lBody = lInsideScrolledForm.getBody(); + GridLayout lLayout = new GridLayout(); + lLayout.numColumns = 3; + lBody.setLayout(lLayout); + // content of the section + selectionRadio = pToolkit.createButton(lBody, getSelectionLabel(), SWT.RADIO); + // selectionRadio.setSelection(false); + selectionRadio.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); + pToolkit.createLabel(lBody, getInvokedObjectLabel(), SWT.NONE); + selectionText = pToolkit.createText(lBody, "", SWT.BORDER | SWT.READ_ONLY); + selectionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + selectionButton = pToolkit.createButton(lBody, "...", SWT.FLAT); + Image image = UMLElementTypes.getImage(getInvocationFeature()); + selectionButton.setImage(image); + selectionButton.setLayoutData(new GridData(SWT.NONE)); + lInsideScrolledForm.reflow(true); + lSection.setClient(lInsideScrolledForm); + } + + /** + * Create the section to ask the user to choose or create an invoked + * element. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + private void createInvocationCreationSection(Composite pParent, FormToolkit pToolkit) { + // create the section + String lSectionTitle = getInvocationCreationSectionTitle(); + Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); + lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + if (lSectionTitle != null) { + lSection.setText(lSectionTitle); + } + ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, getInvocationCreationSectionHelp(), true); + lSection.setTextClient(componentHelp); + ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection); + lInsideScrolledForm.setExpandHorizontal(true); + lInsideScrolledForm.setExpandVertical(true); + Composite lBody = lInsideScrolledForm.getBody(); + GridLayout lLayout = new GridLayout(); + lLayout.numColumns = 3; + lBody.setLayout(lLayout); + // content of the section + creationRadio = pToolkit.createButton(lBody, getCreationLabel(), SWT.RADIO); + // creationRadio.setSelection(true); + creationRadio.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); + if (getPossibleInvokedTypes().length == 1) { + selectedType = getPossibleInvokedTypes()[0]; + } else { + pToolkit.createLabel(lBody, getInvokedTypeLabel(), SWT.NONE); + creationTypeCombo = new Combo(lBody, SWT.DROP_DOWN | SWT.READ_ONLY); + typeComboViewer = new ComboViewer(creationTypeCombo); + pToolkit.adapt(creationTypeCombo); + creationTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + typeComboViewer.setLabelProvider(labelProvider); + typeComboViewer.add(getPossibleInvokedTypes()); + if (getPossibleInvokedTypes().length > 1) { + // initialize selection + typeComboViewer.setSelection(new StructuredSelection(getPossibleInvokedTypes()[0])); + selectedType = getPossibleInvokedTypes()[0]; + } + } + pToolkit.createLabel(lBody, getInvokedNameLabel(), SWT.NONE); + creationNameText = pToolkit.createText(lBody, "", SWT.BORDER); + creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + creationNameText.setFocus(); + pToolkit.createLabel(lBody, getInvokedParentLabel(), SWT.NONE); + creationParentText = pToolkit.createText(lBody, labelProvider.getText(selectedParent), SWT.BORDER | SWT.READ_ONLY); + creationParentText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + creationParentButton = pToolkit.createButton(lBody, "...", SWT.FLAT); + Image image = getParentImage(); + creationParentButton.setImage(image); + creationParentButton.setLayoutData(new GridData(SWT.NONE)); + lInsideScrolledForm.reflow(true); + lSection.setClient(lInsideScrolledForm); + } + + /** + * Set correctly the invoked object, by creating it if needed. Then, + * notifies that the ok button of this dialog has been pressed. + * + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + * + */ + @Override + protected void okPressed() { + boolean isSelectionSelected = selectionRadio.getSelection(); + // create element if needed + if (!isSelectionSelected) { + selectedInvoked = UMLFactory.eINSTANCE.create(selectedType); + if (selectedInvoked instanceof NamedElement) { + ((NamedElement) selectedInvoked).setName(selectedName); + } + addInvokedInParent(selectedParent, selectedInvoked); + } + // store user choices in preference + IPreferenceStore prefStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + // store choice between selection and creation + prefStore.setValue(getSelectionIsDefaultPreference(), isSelectionSelected); + if (!isSelectionSelected) { + // store the owner choice + String ressUri = selectedParent.eResource().getURI().toString(); + String parentURI = selectedParent.eResource().getURIFragment(selectedParent); + String prefValue = String.format(MAP_FORMAT, ressUri, parentURI); + prefStore.setValue(getCreationDefaultOwnerPreference(), prefValue); + } + super.okPressed(); + } + + /** + * Get the invoked object that have been selected or created. + * + * @return the invoked object to use. + */ + public EObject getSelectedInvoked() { + return selectedInvoked; + } + + /** + * Add listeners to widgets + */ + private void hookListeners() { + // listener to choose active section + SelectionListener selectCreateListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + if (creationRadio.equals(e.getSource())) { + refreshSectionsEnable(false); + } else { + refreshSectionsEnable(true); + } + refreshOkButton(); + } + }; + selectionRadio.addSelectionListener(selectCreateListener); + creationRadio.addSelectionListener(selectCreateListener); + // listener to select existing element + SelectionListener selectBtnListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + handleChooseInvoked(); + refreshOkButton(); + } + }; + selectionButton.addSelectionListener(selectBtnListener); + if (creationTypeCombo != null && typeComboViewer != null) { + // listener to select invocation type + ModifyListener lTypeListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + ISelection sel = typeComboViewer.getSelection(); + if (sel instanceof StructuredSelection) { + Object type = ((StructuredSelection) sel).getFirstElement(); + if (type instanceof EClass) { + selectedType = (EClass) type; + } else { + selectedType = null; + } + // reset name + setInvokedName(null); + refreshOkButton(); + } + } + }; + creationTypeCombo.addModifyListener(lTypeListener); + } + // listener to invocation element name + ModifyListener lNameListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + setInvokedName(creationNameText.getText()); + } + }; + creationNameText.addModifyListener(lNameListener); + // listener to select new element parent + SelectionListener selectParentBtnListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + handleChooseParent(); + // reset name if not set + if (selectedName == null) { + setInvokedName(null); + } + refreshOkButton(); + } + }; + creationParentButton.addSelectionListener(selectParentBtnListener); + } + + /** + * Set the name chosen for the invoked element + * + * @param text + * the text string or null for auto-initialization + */ + private void setInvokedName(String text) { + String name = text; + if (text == null && selectedParent != null && selectedType != null) { + name = LabelHelper.INSTANCE.findName(selectedParent, selectedType); + // the name assignment will be performed by listener's call + creationNameText.setText(name); + } else if (name != null && !"".equals(name.trim())) { + selectedName = name.trim(); + Color black = creationNameText.getDisplay().getSystemColor(SWT.COLOR_BLACK); + creationNameText.setForeground(black); + refreshOkButton(); + } else { + selectedName = null; + Color red = creationNameText.getDisplay().getSystemColor(SWT.COLOR_RED); + creationNameText.setForeground(red); + refreshOkButton(); + } + } + + /** + * Open the dialog to choose the existing element to select + * + */ + protected void handleChooseInvoked() { + + + TreeSelectorDialog dialog = new TreeSelectorDialog(Display.getDefault().getActiveShell()); + dialog.setContentProvider(new UMLContentProvider(getInvocationAction(), getInvocationFeature())); + + dialog.setLabelProvider(labelProvider); + // UMLMultiEClassifierTreeSelectorDialog dialog = new UMLMultiEClassifierTreeSelectorDialog(getShell(), actionParent, Collections.singleton(getInvocationFeature().getEType())); + dialog.setMessage(Messages.UMLModelingAssistantProviderMessage); + dialog.setTitle(Messages.UMLModelingAssistantProviderTitle); + if (dialog.open() == org.eclipse.jface.window.Window.OK) { + Object[] result = dialog.getResult(); + if (result != null && result.length > 0 && result[0] instanceof EObject) { + setInvokedSelection((EObject) result[0]); + } + } + } + + /** + * Define the object that will be invoked by the action (if selection mode + * is chosen) + * + * @param invokedElement + * the selected element + */ + protected void setInvokedSelection(EObject invokedElement) { + selectedInvoked = invokedElement; + if (selectedInvoked instanceof NamedElement) { + selectionText.setText(labelProvider.getText(selectedInvoked)); + } else { + selectionText.setText(""); + } + } + + /** + * Open the dialog to choose the parent of element to create + * + */ + private void handleChooseParent() { + GetObjectsOfTypeListSelectionDialog dialog = new GetObjectsOfTypeListSelectionDialog(getParentShell(), labelProvider, actionParent, false); + for (EClassifier type : getPossibleInvokedParents(actionParent)) { + dialog.addElementsOfType(type); + } + if (dialog.open() == Window.OK) { + Object firstResult = dialog.getFirstResult(); + if (firstResult instanceof EObject) { + setInvokedParent((EObject) dialog.getFirstResult()); + } + } + } + + /** + * Define the object in which invoked object will be created (if creation + * mode is chosen) + * + * @param invokedParent + * the selected parent + */ + private void setInvokedParent(EObject invokedParent) { + selectedParent = invokedParent; + if (selectedParent instanceof NamedElement) { + creationParentText.setText(labelProvider.getText(selectedParent)); + } else { + creationParentText.setText(""); + } + } + + /** + * Refresh the enabled and disabled elements in various sections + * + * @param isSelectionSelected + * true if we choose to select an existing element, false if we + * choose to create an element + */ + protected void refreshSectionsEnable(boolean isSelectionSelected) { + // handle radio button value + if (isSelectionSelected) { + creationRadio.setSelection(false); + if (!selectionRadio.getSelection()) { + selectionRadio.setSelection(true); + } + } else { + selectionRadio.setSelection(false); + if (!creationRadio.getSelection()) { + creationRadio.setSelection(true); + } + } + // handle disabled section + selectionText.setEnabled(isSelectionSelected); + selectionButton.setEnabled(isSelectionSelected); + if (creationTypeCombo != null) { + creationTypeCombo.setEnabled(!isSelectionSelected); + } + creationNameText.setEnabled(!isSelectionSelected); + creationNameText.setFocus(); + creationParentText.setEnabled(!isSelectionSelected); + creationParentButton.setEnabled(!isSelectionSelected); + } + + /** + * Refresh the OK button activation + */ + private void refreshOkButton() { + boolean isSelectionSelected = selectionRadio.getSelection(); + if (getButton(IDialogConstants.OK_ID) != null && !getButton(IDialogConstants.OK_ID).isDisposed()) { + if (isSelectionSelected) { + getButton(IDialogConstants.OK_ID).setEnabled(selectedInvoked != null); + } else { + getButton(IDialogConstants.OK_ID).setEnabled(selectedParent != null && selectedType != null && selectedName != null); + } + } + } + + /** + * Add the created invoked object to its selected parent + */ + protected void addInvokedInParent(EObject selectedParent, EObject createdInvoked) { + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + // Let the command find the relation on its own. + Command addCmd = AddCommand.create(editingdomain, selectedParent, null, Collections.singleton(createdInvoked)); + addCmd.execute(); + } + + /** + * Gets the custom label provider that parses label for EClass + * + * @return the custom label provider + */ + private ILabelProvider getCustomLabelProvider() { + AdapterFactoryLabelProvider adapterFactory = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()) { + + /** + * Override label provider for EClass + * + * @see org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider#getText(java.lang.Object) + */ + @Override + public String getText(Object object) { + String text = super.getText(object); + if (object instanceof EClass) { + return text.substring(0, text.indexOf("[") - 1); + } else { + return text; + } + } + }; + return adapterFactory; + } + + /** + * Get the possible types for creating a new invoked element + * + * @return array of EClasses + */ + abstract protected EClass[] getPossibleInvokedTypes(); + + /** + * Get the possible parents of the new invoked element + * + * @param actionParent + * the parent of the action + * @return collection of EObject possible owners + */ + abstract protected Set<? extends EClassifier> getPossibleInvokedParents(EObject actionParent); + + /** + * Whether element can be parent of the new invoked element + * + * @param parent + * the parent to test + * @return true if parent is of an appropriate eclass + */ + abstract protected boolean isPossibleInvokedParent(EObject parent); + + /** + * Get feature referencing the invoked object + * + * @return invocation feature + */ + abstract protected EReference getInvocationFeature(); + + /** + * Get the image for the parent selection button + * + * @return image + */ + abstract protected Image getParentImage(); + + /** + * Get the label to present the name of the invoked object + * + * @return label + */ + protected String getInvokedNameLabel() { + return CustomMessages.CreateCallActionDialog_NameLabel; + } + + /** + * Get the label to present the type of the invoked object + * + * @return label + */ + protected String getInvokedTypeLabel() { + return CustomMessages.CreateCallActionDialog_TypeLabel; + } + + /** + * Get the label to present parent of the invoked object + * + * @return label + */ + protected String getInvokedParentLabel() { + return CustomMessages.CreateCallActionDialog_ParentLabel; + } + + /** + * Get the label to present the invoked object + * + * @return label + */ + protected String getInvokedObjectLabel() { + return getInvocationFeature().getEReferenceType().getName() + ":"; + } + + /** + * Get the title of the dialog + * + * @return dialog title + */ + abstract protected String getTitle(); + + /** + * Get the title of the invocation creation section + * + * @return section title + */ + abstract protected String getInvocationCreationSectionTitle(); + + /** + * Get the help description of the invocation creation section + * + * @return section title + */ + abstract protected String getInvocationCreationSectionHelp(); + + /** + * Get the title of the invocation selection section + * + * @return section title + */ + abstract protected String getInvocationSelectionSectionTitle(); + + /** + * Get the label to choose to select an existing element + * + * @return label + */ + abstract protected String getSelectionLabel(); + + /** + * Get the label to choose to create a new element + * + * @return label + */ + abstract protected String getCreationLabel(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateParameterDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateParameterDialog.java index 0fd7e231f68..d5a3cabe7f6 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateParameterDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateParameterDialog.java @@ -1,411 +1,411 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.emf.common.command.Command;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.edit.command.AddCommand;
-import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ComboViewer;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.papyrus.infra.ui.util.EditorUtils;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes;
-import org.eclipse.papyrus.uml.diagram.common.actions.LabelHelper;
-import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.FormDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ImageHyperlink;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.uml2.uml.NamedElement;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.ParameterDirectionKind;
-import org.eclipse.uml2.uml.Type;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * DialogBox in order to link a parameter with the new ActivityParameterNode
- * that will be created
- *
- */
-public class CreateParameterDialog extends FormDialog {
-
- private Text creationNameText;
-
- private Text creationTypeText;
-
- private Button creationTypeButton;
-
- private Parameter createdParameter = null;
-
- private EObject selectedType = null;
-
- private NamedElement parameterOwner;
-
- private String selectedName = null;
-
- private ParameterDirectionKind selectedDirection = null;
-
- private ComboViewer directionComboViewer = null;
-
- private Combo creationDirectionCombo = null;
-
- private ILabelProvider labelProvider;
-
- private ParameterDirectionKind defaultDirection = null;
-
- /**
- * Create a new dialog to initialize an ActivityParameterNode.
- *
- * @param shell
- * parent shell
- * @param owner
- * the activity that owns the action
- * @param defaultDirectionKind
- * the parameter direction kind to select by default (or null)
- */
- public CreateParameterDialog(Shell shell, NamedElement owner, ParameterDirectionKind defaultDirectionKind) {
- super(shell);
- parameterOwner = owner;
- labelProvider = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory());
- defaultDirection = defaultDirectionKind;
- }
-
- /**
- * Create the form to :
- *
- * - ask the user to choose or create an existing element.
- *
- * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm)
- */
- @Override
- protected void createFormContent(IManagedForm pForm) {
- pForm.getForm().setText(getTitle());
- ScrolledForm scrolledForm = pForm.getForm();
- FormToolkit toolkit = pForm.getToolkit();
- Composite parent = scrolledForm.getBody();
- parent.setLayout(new GridLayout());
- createParameterSection(scrolledForm.getBody(), toolkit);
- hookListeners();
- // invoked name is set after listeners, since we count on listener to
- // update it properly
- setInvokedName(null);
- scrolledForm.reflow(true);
- }
-
- /**
- * Adds buttons to this dialog's button bar.
- *
- * @param parent
- * the button bar composite
- */
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- super.createButtonsForButtonBar(parent);
- refreshOkButton();
- }
-
- /**
- * Create the section to ask the user to create a parameter.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- protected void createParameterSection(Composite pParent, FormToolkit pToolkit) {
- // create the section
- String lSectionTitle = getCreationTitle();
- Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR);
- lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (lSectionTitle != null) {
- lSection.setText(lSectionTitle);
- }
- ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreateParameterDialog_ParameterCreationHelp, true);
- lSection.setTextClient(componentHelp);
- ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection);
- lInsideScrolledForm.setExpandHorizontal(true);
- lInsideScrolledForm.setExpandVertical(true);
- Composite lBody = lInsideScrolledForm.getBody();
- GridLayout lLayout = new GridLayout();
- lLayout.numColumns = 3;
- lBody.setLayout(lLayout);
- // content of the section
- pToolkit.createLabel(lBody, getNameLabel(), SWT.NONE);
- creationNameText = pToolkit.createText(lBody, "", SWT.BORDER);
- creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- creationNameText.setFocus();
- // manage type selection
- pToolkit.createLabel(lBody, getTypeLabel(), SWT.NONE);
- creationTypeText = pToolkit.createText(lBody, labelProvider.getText(selectedType), SWT.BORDER | SWT.READ_ONLY);
- creationTypeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- creationTypeButton = pToolkit.createButton(lBody, "...", SWT.FLAT);
- Image image = getTypeImage();
- creationTypeButton.setImage(image);
- creationTypeButton.setLayoutData(new GridData(SWT.NONE));
- // manage direction selection
- pToolkit.createLabel(lBody, getDirectionLabel(), SWT.NONE);
- creationDirectionCombo = new Combo(lBody, SWT.DROP_DOWN | SWT.READ_ONLY);
- directionComboViewer = new ComboViewer(creationDirectionCombo);
- pToolkit.adapt(creationDirectionCombo);
- creationDirectionCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- directionComboViewer.setLabelProvider(labelProvider);
- directionComboViewer.add(getPossibleDirections());
- // initialize selection
- directionComboViewer.setSelection(new StructuredSelection(getDefaultDirection()));
- selectedDirection = ParameterDirectionKind.getByName(getDefaultDirection());
- lInsideScrolledForm.reflow(true);
- lSection.setClient(lInsideScrolledForm);
- }
-
- /**
- * Set correctly the invoked object, by creating it if needed. Then,
- * notifies that the ok button of this dialog has been pressed.
- *
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- *
- */
- @Override
- protected void okPressed() {
- // create element
- createdParameter = UMLFactory.eINSTANCE.createParameter();
- createdParameter.setName(selectedName);
- createdParameter.setType((Type) selectedType);
- createdParameter.setDirection(selectedDirection);
- addParameter(createdParameter);
- super.okPressed();
- }
-
- /**
- * Get the invoked object that have been selected or created.
- *
- * @return the invoked object to use.
- */
- public Parameter getCreatedParameter() {
- return createdParameter;
- }
-
- /**
- * Add listeners to widgets
- */
- private void hookListeners() {
- if (creationDirectionCombo != null && directionComboViewer != null) {
- // listener to select invocation type
- ModifyListener lTypeListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- ISelection sel = directionComboViewer.getSelection();
- if (sel instanceof StructuredSelection) {
- String firstElement = ((StructuredSelection) sel).getFirstElement().toString();
- selectedDirection = ParameterDirectionKind.getByName(firstElement);
- } else {
- selectedDirection = null;
- }
- // reset name
- setInvokedName(null);
- refreshOkButton();
- }
- };
- creationDirectionCombo.addModifyListener(lTypeListener);
- }
- // listener to invocation element name
- ModifyListener lNameListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- setInvokedName(creationNameText.getText());
- }
- };
- creationNameText.addModifyListener(lNameListener);
- // listener to select new element parent
- SelectionListener selectParentBtnListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleChooseType();
- // reset name if not set
- if (selectedName == null) {
- setInvokedName(null);
- }
- refreshOkButton();
- }
- };
- creationTypeButton.addSelectionListener(selectParentBtnListener);
- }
-
- /**
- * Set the name chosen for the invoked element
- *
- * @param text
- * the text string or null for auto-initialization
- */
- private void setInvokedName(String text) {
- String name = text;
- if (text == null) {
- name = LabelHelper.INSTANCE.findName(parameterOwner, UMLPackage.eINSTANCE.getParameter());
- // the name assignment will be performed by listener's call
- creationNameText.setText(name);
- } else if (name != null && !"".equals(name.trim())) {
- selectedName = name.trim();
- Color black = creationNameText.getDisplay().getSystemColor(SWT.COLOR_BLACK);
- creationNameText.setForeground(black);
- refreshOkButton();
- } else {
- selectedName = null;
- Color red = creationNameText.getDisplay().getSystemColor(SWT.COLOR_RED);
- creationNameText.setForeground(red);
- refreshOkButton();
- }
- }
-
- /**
- * Open the dialog to choose the type of element to create
- *
- */
- private void handleChooseType() {
- GetObjectsOfTypeListSelectionDialog dialog = new GetObjectsOfTypeListSelectionDialog(getShell(), labelProvider, parameterOwner, true);
- dialog.addElementsOfType(UMLPackage.eINSTANCE.getTypedElement_Type().getEType());
- if (dialog.open() == Window.OK) {
- Object firstResult = dialog.getFirstResult();
- if (firstResult instanceof EObject) {
- setType((EObject) dialog.getFirstResult());
- } else {
- setType(null);
- }
- }
- }
-
- /**
- * Define the type of the object that will be created
- *
- * @param type
- * the selected type
- */
- private void setType(EObject type) {
- selectedType = type;
- if (selectedType instanceof NamedElement) {
- creationTypeText.setText(labelProvider.getText(selectedType));
- } else {
- creationTypeText.setText("");
- }
- }
-
- /**
- * Refresh the OK button activation
- */
- private void refreshOkButton() {
- if (getButton(IDialogConstants.OK_ID) != null && !getButton(IDialogConstants.OK_ID).isDisposed()) {
- getButton(IDialogConstants.OK_ID).setEnabled(selectedDirection != null && selectedName != null);
- }
- }
-
- /**
- * Add the created invoked object to its selected parent
- */
- protected void addParameter(Parameter createdParameter) {
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- // Let the command find the relation on its own.
- Command addCmd = AddCommand.create(editingdomain, parameterOwner, null, Collections.singleton(createdParameter));
- addCmd.execute();
- }
-
- /**
- * Gets the possible directions.
- *
- * @return the possible directions
- */
- private String[] getPossibleDirections() {
- List<ParameterDirectionKind> values = ParameterDirectionKind.VALUES;
- String[] ret = new String[values.size()];
- for (int i = 0; i < values.size(); i++) {
- ret[i] = values.get(i).getName();
- }
- return ret;
- }
-
- /**
- * Gets the direction which is selected by default.
- *
- * @return the default direction
- */
- private String getDefaultDirection() {
- if (defaultDirection != null) {
- return defaultDirection.getName();
- } else {
- return getPossibleDirections()[0];
- }
- }
-
- private Image getTypeImage() {
- return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage_PackagedElement());
- }
-
- private String getTitle() {
- return CustomMessages.CreateParameterDialog_DialogTitle;
- }
-
- private String getCreationTitle() {
- return CustomMessages.CreateParameterDialog_ParameterCreationTitle;
- }
-
- private String getNameLabel() {
- return CustomMessages.CreateParameterDialog_NameLabel;
- }
-
- private String getTypeLabel() {
- return CustomMessages.CreateParameterDialog_TypeLabel;
- }
-
- private String getDirectionLabel() {
- return CustomMessages.CreateParameterDialog_DirectionLabel;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Collections; +import java.util.List; + +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.edit.command.AddCommand; +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.viewers.ComboViewer; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.papyrus.infra.ui.util.EditorUtils; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes; +import org.eclipse.papyrus.uml.diagram.common.actions.LabelHelper; +import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.forms.FormDialog; +import org.eclipse.ui.forms.IManagedForm; +import org.eclipse.ui.forms.widgets.ExpandableComposite; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.ui.forms.widgets.ImageHyperlink; +import org.eclipse.ui.forms.widgets.ScrolledForm; +import org.eclipse.ui.forms.widgets.Section; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.ParameterDirectionKind; +import org.eclipse.uml2.uml.Type; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * DialogBox in order to link a parameter with the new ActivityParameterNode + * that will be created + * + */ +public class CreateParameterDialog extends FormDialog { + + private Text creationNameText; + + private Text creationTypeText; + + private Button creationTypeButton; + + private Parameter createdParameter = null; + + private EObject selectedType = null; + + private NamedElement parameterOwner; + + private String selectedName = null; + + private ParameterDirectionKind selectedDirection = null; + + private ComboViewer directionComboViewer = null; + + private Combo creationDirectionCombo = null; + + private ILabelProvider labelProvider; + + private ParameterDirectionKind defaultDirection = null; + + /** + * Create a new dialog to initialize an ActivityParameterNode. + * + * @param shell + * parent shell + * @param owner + * the activity that owns the action + * @param defaultDirectionKind + * the parameter direction kind to select by default (or null) + */ + public CreateParameterDialog(Shell shell, NamedElement owner, ParameterDirectionKind defaultDirectionKind) { + super(shell); + parameterOwner = owner; + labelProvider = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()); + defaultDirection = defaultDirectionKind; + } + + /** + * Create the form to : + * + * - ask the user to choose or create an existing element. + * + * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm) + */ + @Override + protected void createFormContent(IManagedForm pForm) { + pForm.getForm().setText(getTitle()); + ScrolledForm scrolledForm = pForm.getForm(); + FormToolkit toolkit = pForm.getToolkit(); + Composite parent = scrolledForm.getBody(); + parent.setLayout(new GridLayout()); + createParameterSection(scrolledForm.getBody(), toolkit); + hookListeners(); + // invoked name is set after listeners, since we count on listener to + // update it properly + setInvokedName(null); + scrolledForm.reflow(true); + } + + /** + * Adds buttons to this dialog's button bar. + * + * @param parent + * the button bar composite + */ + @Override + protected void createButtonsForButtonBar(Composite parent) { + super.createButtonsForButtonBar(parent); + refreshOkButton(); + } + + /** + * Create the section to ask the user to create a parameter. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + protected void createParameterSection(Composite pParent, FormToolkit pToolkit) { + // create the section + String lSectionTitle = getCreationTitle(); + Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); + lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + if (lSectionTitle != null) { + lSection.setText(lSectionTitle); + } + ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreateParameterDialog_ParameterCreationHelp, true); + lSection.setTextClient(componentHelp); + ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection); + lInsideScrolledForm.setExpandHorizontal(true); + lInsideScrolledForm.setExpandVertical(true); + Composite lBody = lInsideScrolledForm.getBody(); + GridLayout lLayout = new GridLayout(); + lLayout.numColumns = 3; + lBody.setLayout(lLayout); + // content of the section + pToolkit.createLabel(lBody, getNameLabel(), SWT.NONE); + creationNameText = pToolkit.createText(lBody, "", SWT.BORDER); + creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + creationNameText.setFocus(); + // manage type selection + pToolkit.createLabel(lBody, getTypeLabel(), SWT.NONE); + creationTypeText = pToolkit.createText(lBody, labelProvider.getText(selectedType), SWT.BORDER | SWT.READ_ONLY); + creationTypeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + creationTypeButton = pToolkit.createButton(lBody, "...", SWT.FLAT); + Image image = getTypeImage(); + creationTypeButton.setImage(image); + creationTypeButton.setLayoutData(new GridData(SWT.NONE)); + // manage direction selection + pToolkit.createLabel(lBody, getDirectionLabel(), SWT.NONE); + creationDirectionCombo = new Combo(lBody, SWT.DROP_DOWN | SWT.READ_ONLY); + directionComboViewer = new ComboViewer(creationDirectionCombo); + pToolkit.adapt(creationDirectionCombo); + creationDirectionCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + directionComboViewer.setLabelProvider(labelProvider); + directionComboViewer.add(getPossibleDirections()); + // initialize selection + directionComboViewer.setSelection(new StructuredSelection(getDefaultDirection())); + selectedDirection = ParameterDirectionKind.getByName(getDefaultDirection()); + lInsideScrolledForm.reflow(true); + lSection.setClient(lInsideScrolledForm); + } + + /** + * Set correctly the invoked object, by creating it if needed. Then, + * notifies that the ok button of this dialog has been pressed. + * + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + * + */ + @Override + protected void okPressed() { + // create element + createdParameter = UMLFactory.eINSTANCE.createParameter(); + createdParameter.setName(selectedName); + createdParameter.setType((Type) selectedType); + createdParameter.setDirection(selectedDirection); + addParameter(createdParameter); + super.okPressed(); + } + + /** + * Get the invoked object that have been selected or created. + * + * @return the invoked object to use. + */ + public Parameter getCreatedParameter() { + return createdParameter; + } + + /** + * Add listeners to widgets + */ + private void hookListeners() { + if (creationDirectionCombo != null && directionComboViewer != null) { + // listener to select invocation type + ModifyListener lTypeListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + ISelection sel = directionComboViewer.getSelection(); + if (sel instanceof StructuredSelection) { + String firstElement = ((StructuredSelection) sel).getFirstElement().toString(); + selectedDirection = ParameterDirectionKind.getByName(firstElement); + } else { + selectedDirection = null; + } + // reset name + setInvokedName(null); + refreshOkButton(); + } + }; + creationDirectionCombo.addModifyListener(lTypeListener); + } + // listener to invocation element name + ModifyListener lNameListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + setInvokedName(creationNameText.getText()); + } + }; + creationNameText.addModifyListener(lNameListener); + // listener to select new element parent + SelectionListener selectParentBtnListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + handleChooseType(); + // reset name if not set + if (selectedName == null) { + setInvokedName(null); + } + refreshOkButton(); + } + }; + creationTypeButton.addSelectionListener(selectParentBtnListener); + } + + /** + * Set the name chosen for the invoked element + * + * @param text + * the text string or null for auto-initialization + */ + private void setInvokedName(String text) { + String name = text; + if (text == null) { + name = LabelHelper.INSTANCE.findName(parameterOwner, UMLPackage.eINSTANCE.getParameter()); + // the name assignment will be performed by listener's call + creationNameText.setText(name); + } else if (name != null && !"".equals(name.trim())) { + selectedName = name.trim(); + Color black = creationNameText.getDisplay().getSystemColor(SWT.COLOR_BLACK); + creationNameText.setForeground(black); + refreshOkButton(); + } else { + selectedName = null; + Color red = creationNameText.getDisplay().getSystemColor(SWT.COLOR_RED); + creationNameText.setForeground(red); + refreshOkButton(); + } + } + + /** + * Open the dialog to choose the type of element to create + * + */ + private void handleChooseType() { + GetObjectsOfTypeListSelectionDialog dialog = new GetObjectsOfTypeListSelectionDialog(getShell(), labelProvider, parameterOwner, true); + dialog.addElementsOfType(UMLPackage.eINSTANCE.getTypedElement_Type().getEType()); + if (dialog.open() == Window.OK) { + Object firstResult = dialog.getFirstResult(); + if (firstResult instanceof EObject) { + setType((EObject) dialog.getFirstResult()); + } else { + setType(null); + } + } + } + + /** + * Define the type of the object that will be created + * + * @param type + * the selected type + */ + private void setType(EObject type) { + selectedType = type; + if (selectedType instanceof NamedElement) { + creationTypeText.setText(labelProvider.getText(selectedType)); + } else { + creationTypeText.setText(""); + } + } + + /** + * Refresh the OK button activation + */ + private void refreshOkButton() { + if (getButton(IDialogConstants.OK_ID) != null && !getButton(IDialogConstants.OK_ID).isDisposed()) { + getButton(IDialogConstants.OK_ID).setEnabled(selectedDirection != null && selectedName != null); + } + } + + /** + * Add the created invoked object to its selected parent + */ + protected void addParameter(Parameter createdParameter) { + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + // Let the command find the relation on its own. + Command addCmd = AddCommand.create(editingdomain, parameterOwner, null, Collections.singleton(createdParameter)); + addCmd.execute(); + } + + /** + * Gets the possible directions. + * + * @return the possible directions + */ + private String[] getPossibleDirections() { + List<ParameterDirectionKind> values = ParameterDirectionKind.VALUES; + String[] ret = new String[values.size()]; + for (int i = 0; i < values.size(); i++) { + ret[i] = values.get(i).getName(); + } + return ret; + } + + /** + * Gets the direction which is selected by default. + * + * @return the default direction + */ + private String getDefaultDirection() { + if (defaultDirection != null) { + return defaultDirection.getName(); + } else { + return getPossibleDirections()[0]; + } + } + + private Image getTypeImage() { + return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage_PackagedElement()); + } + + private String getTitle() { + return CustomMessages.CreateParameterDialog_DialogTitle; + } + + private String getCreationTitle() { + return CustomMessages.CreateParameterDialog_ParameterCreationTitle; + } + + private String getNameLabel() { + return CustomMessages.CreateParameterDialog_NameLabel; + } + + private String getTypeLabel() { + return CustomMessages.CreateParameterDialog_TypeLabel; + } + + private String getDirectionLabel() { + return CustomMessages.CreateParameterDialog_DirectionLabel; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreatePinsForObjectFlowDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreatePinsForObjectFlowDialog.java index 4248f33691a..d275007b426 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreatePinsForObjectFlowDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreatePinsForObjectFlowDialog.java @@ -1,357 +1,357 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import org.eclipse.papyrus.uml.diagram.activity.helper.CustomObjectFlowEditHelper;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes;
-import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.FormDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.ExpandableComposite;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ImageHyperlink;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.uml2.uml.Action;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.InputPin;
-import org.eclipse.uml2.uml.OpaqueAction;
-import org.eclipse.uml2.uml.OutputPin;
-import org.eclipse.uml2.uml.Pin;
-import org.eclipse.uml2.uml.Type;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * This class provides a dialog to initialize a CallBehaviorAction at its
- * creation.
- */
-public class CreatePinsForObjectFlowDialog extends FormDialog {
-
- private static final String TITLE = CustomMessages.CreatePinsForObjectFlowDialog_Title;
-
- private static final String PIN_CREATION_SECTION_TITLE = CustomMessages.CreatePinsForObjectFlowDialog_PinCreationTitle;
-
- private static final String NAME_LABEL = CustomMessages.CreatePinsForObjectFlowDialog_Name;
-
- private static final String TYPE_LABEL = CustomMessages.CreatePinsForObjectFlowDialog_Type;
-
- /** The initial value for pins name */
- private static final String NAME_INITIAL_VALUE = "data";
-
- /** The user chosen source node */
- private ActivityNode initialSource = null;
-
- /** The user chosen target node */
- private ActivityNode initialTarget = null;
-
- /** The object to use as object flow source */
- private ActivityNode newSource = null;
-
- /** The object to use as object flow target */
- private ActivityNode newTarget = null;
-
- private Text creationNameText = null;
-
- private String creationName = NAME_INITIAL_VALUE;
-
- private Text creationTypeText = null;
-
- private Button creationTypeButton = null;
-
- private Type creationType = null;
-
- /**
- * Create a new dialog to initialize a CallBehaviorAction.
- *
- * @param shell
- * parent shell
- * @param source
- * the chosen source of the object flow
- * @param target
- * the chosen target of the object flow
- */
- public CreatePinsForObjectFlowDialog(Shell shell, ActivityNode source, ActivityNode target) {
- super(shell);
- initialSource = source;
- initialTarget = target;
- }
-
- @Override
- public int open() {
- if (CustomObjectFlowEditHelper.insertPinForStartingNewObjectFlow(initialSource) && CustomObjectFlowEditHelper.insertPinForEndingNewObjectFlow(initialTarget)) {
- // create an object flow between actions : both pins must be created
- return super.open();
- } else {
- boolean needInformation = false;
- // use correct extremities or configure new one
- if (CustomObjectFlowEditHelper.insertPinForStartingNewObjectFlow(initialSource)) {
- newSource = createSource((Action) initialSource, initialTarget);
- if (newSource == null) {
- // ask for missing information
- needInformation = true;
- }
- } else {
- newSource = initialSource;
- }
- if (CustomObjectFlowEditHelper.insertPinForEndingNewObjectFlow(initialTarget)) {
- newTarget = createTarget((Action) initialTarget, initialSource);
- if (newTarget == null) {
- // ask for missing information
- needInformation = true;
- }
- } else {
- newTarget = initialTarget;
- }
- if (needInformation) {
- return super.open();
- }
- return OK;
- }
- }
-
- /**
- * Create a pin to use as target if all information is available
- *
- * @param parentAction
- * the action containing the pin
- * @param objectFlowSource
- * the source of the object flow
- * @return the created pin or null if information is missing
- */
- private InputPin createTarget(Action parentAction, ActivityNode objectFlowSource) {
- if (objectFlowSource instanceof Pin) {
- return createInputPin(parentAction, objectFlowSource.getName(), ((Pin) objectFlowSource).getType());
- } else {
- // Source is not a pin, probably a control node. Ask for information
- return null;
- }
- }
-
- /**
- * Create a pin to use as source if all information is available
- *
- * @param parentAction
- * the action containing the pin
- * @param objectFlowTarget
- * the target of the object flow
- * @return the created pin or null if information is missing
- */
- private OutputPin createSource(Action parentAction, ActivityNode objectFlowTarget) {
- if (objectFlowTarget instanceof Pin) {
- return createOutputPin(parentAction, objectFlowTarget.getName(), ((Pin) objectFlowTarget).getType());
- } else {
- // Source is not a pin, probably a control node. Ask for information
- return null;
- }
- }
-
- /**
- * Create an input pin
- *
- * @param parentAction
- * the action containing this pin
- * @param name
- * pin name
- * @param type
- * pin type
- * @return created pin
- */
- private InputPin createInputPin(Action parentAction, String name, Type type) {
- InputPin result = UMLFactory.eINSTANCE.createInputPin();
- result.setName(name);
- result.setType(type);
- CustomObjectFlowEditHelper.insertInputPin(parentAction, result);
- return result;
- }
-
- /**
- * Create an output pin
- *
- * @param parentAction
- * the action containing this pin
- * @param name
- * pin name
- * @param type
- * pin type
- * @return created pin
- */
- private OutputPin createOutputPin(Action parentAction, String name, Type type) {
- OutputPin result = UMLFactory.eINSTANCE.createOutputPin();
- result.setName(name);
- result.setType(type);
- CustomObjectFlowEditHelper.insertOutputPin(parentAction, result);
- return result;
- }
-
- /**
- * Create the form to :
- *
- * - ask the user the name of pins to create.
- *
- * - ask the user the type of pins to create.
- *
- * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm)
- */
- @Override
- protected void createFormContent(IManagedForm pForm) {
- pForm.getForm().setText(TITLE);
- ScrolledForm scrolledForm = pForm.getForm();
- FormToolkit toolkit = pForm.getToolkit();
- Composite parent = scrolledForm.getBody();
- parent.setLayout(new GridLayout());
- createPinCreationSection(scrolledForm.getBody(), toolkit);
- hookListeners();
- scrolledForm.reflow(true);
- }
-
- /**
- * Create the section to ask the user to parameterize the pin.
- *
- * @param pParent
- * the section's parent widget
- * @param pToolkit
- * the form toolkit
- */
- private void createPinCreationSection(Composite pParent, FormToolkit pToolkit) {
- // create the section
- String lSectionTitle = PIN_CREATION_SECTION_TITLE;
- Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR);
- lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (lSectionTitle != null) {
- lSection.setText(lSectionTitle);
- }
- ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreatePinsForObjectFlowDialog_PinCreationHelp, true);
- lSection.setTextClient(componentHelp);
- ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection);
- lInsideScrolledForm.setExpandHorizontal(true);
- lInsideScrolledForm.setExpandVertical(true);
- Composite lBody = lInsideScrolledForm.getBody();
- GridLayout lLayout = new GridLayout();
- lLayout.numColumns = 3;
- lBody.setLayout(lLayout);
- // content of the section
- pToolkit.createLabel(lBody, NAME_LABEL, SWT.NONE);
- creationNameText = pToolkit.createText(lBody, NAME_INITIAL_VALUE, SWT.BORDER);
- creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- creationNameText.setFocus();
- pToolkit.createLabel(lBody, TYPE_LABEL, SWT.NONE);
- creationTypeText = pToolkit.createText(lBody, "", SWT.BORDER | SWT.READ_ONLY);
- creationTypeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- creationTypeButton = pToolkit.createButton(lBody, "...", SWT.FLAT);
- Image image = UMLElementTypes.getImage(UMLPackage.eINSTANCE.getClass_());
- creationTypeButton.setImage(image);
- creationTypeButton.setLayoutData(new GridData(SWT.NONE));
- lInsideScrolledForm.reflow(true);
- lSection.setClient(lInsideScrolledForm);
- }
-
- /**
- * Add listeners to widgets
- */
- private void hookListeners() {
- // listener to new pin name
- ModifyListener lNameListener = new ModifyListener() {
-
- /**
- * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
- */
- @Override
- public void modifyText(ModifyEvent e) {
- creationName = creationNameText.getText();
- }
- };
- creationNameText.addModifyListener(lNameListener);
- // listener to select new pin type
- SelectionListener selectTypeBtnListener = new SelectionAdapter() {
-
- /**
- * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleChooseType();
- }
- };
- creationTypeButton.addSelectionListener(selectTypeBtnListener);
- }
-
- /**
- * Open the dialog to choose the type of the pin(s) to create
- *
- */
- private void handleChooseType() {
- /*
- * TODO Backport
- */
- // UMLMultiEClassifierTreeSelectorDialog dialog = new UMLMultiEClassifierTreeSelectorDialog(getShell(),initialSource, Sets.newHashSet(UMLPackage.Literals.TYPE));
- // dialog.setMessage(CustomMessages.UMLModelingAssistantProviderMessage);
- // dialog.setTitle(CustomMessages.UMLModelingAssistantProviderTitle);
- // if(dialog.open() == Window.OK) {
- // creationType = (Type)dialog.getTheResult();
- // creationTypeText.setText(dialog.getText(creationType));
- // }
- }
-
- /**
- * Set correctly the invoked object, by creating it if needed. Then,
- * notifies that the ok button of this dialog has been pressed.
- *
- * @see org.eclipse.jface.dialogs.Dialog#okPressed()
- *
- */
- @Override
- protected void okPressed() {
- // create pins if needed
- if (newSource == null) {
- newSource = createOutputPin((OpaqueAction) initialSource, creationName, creationType);
- }
- if (newTarget == null) {
- newTarget = createInputPin((OpaqueAction) initialTarget, creationName, creationType);
- }
- super.okPressed();
- }
-
- /**
- * Get the node to use as object flow source
- *
- * @return new source
- */
- public ActivityNode getSource() {
- return newSource;
- }
-
- /**
- * Get the node to use as object flow target
- *
- * @return new target
- */
- public ActivityNode getTarget() {
- return newTarget;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import org.eclipse.papyrus.uml.diagram.activity.helper.CustomObjectFlowEditHelper; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes; +import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.forms.FormDialog; +import org.eclipse.ui.forms.IManagedForm; +import org.eclipse.ui.forms.widgets.ExpandableComposite; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.ui.forms.widgets.ImageHyperlink; +import org.eclipse.ui.forms.widgets.ScrolledForm; +import org.eclipse.ui.forms.widgets.Section; +import org.eclipse.uml2.uml.Action; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.InputPin; +import org.eclipse.uml2.uml.OpaqueAction; +import org.eclipse.uml2.uml.OutputPin; +import org.eclipse.uml2.uml.Pin; +import org.eclipse.uml2.uml.Type; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * This class provides a dialog to initialize a CallBehaviorAction at its + * creation. + */ +public class CreatePinsForObjectFlowDialog extends FormDialog { + + private static final String TITLE = CustomMessages.CreatePinsForObjectFlowDialog_Title; + + private static final String PIN_CREATION_SECTION_TITLE = CustomMessages.CreatePinsForObjectFlowDialog_PinCreationTitle; + + private static final String NAME_LABEL = CustomMessages.CreatePinsForObjectFlowDialog_Name; + + private static final String TYPE_LABEL = CustomMessages.CreatePinsForObjectFlowDialog_Type; + + /** The initial value for pins name */ + private static final String NAME_INITIAL_VALUE = "data"; + + /** The user chosen source node */ + private ActivityNode initialSource = null; + + /** The user chosen target node */ + private ActivityNode initialTarget = null; + + /** The object to use as object flow source */ + private ActivityNode newSource = null; + + /** The object to use as object flow target */ + private ActivityNode newTarget = null; + + private Text creationNameText = null; + + private String creationName = NAME_INITIAL_VALUE; + + private Text creationTypeText = null; + + private Button creationTypeButton = null; + + private Type creationType = null; + + /** + * Create a new dialog to initialize a CallBehaviorAction. + * + * @param shell + * parent shell + * @param source + * the chosen source of the object flow + * @param target + * the chosen target of the object flow + */ + public CreatePinsForObjectFlowDialog(Shell shell, ActivityNode source, ActivityNode target) { + super(shell); + initialSource = source; + initialTarget = target; + } + + @Override + public int open() { + if (CustomObjectFlowEditHelper.insertPinForStartingNewObjectFlow(initialSource) && CustomObjectFlowEditHelper.insertPinForEndingNewObjectFlow(initialTarget)) { + // create an object flow between actions : both pins must be created + return super.open(); + } else { + boolean needInformation = false; + // use correct extremities or configure new one + if (CustomObjectFlowEditHelper.insertPinForStartingNewObjectFlow(initialSource)) { + newSource = createSource((Action) initialSource, initialTarget); + if (newSource == null) { + // ask for missing information + needInformation = true; + } + } else { + newSource = initialSource; + } + if (CustomObjectFlowEditHelper.insertPinForEndingNewObjectFlow(initialTarget)) { + newTarget = createTarget((Action) initialTarget, initialSource); + if (newTarget == null) { + // ask for missing information + needInformation = true; + } + } else { + newTarget = initialTarget; + } + if (needInformation) { + return super.open(); + } + return OK; + } + } + + /** + * Create a pin to use as target if all information is available + * + * @param parentAction + * the action containing the pin + * @param objectFlowSource + * the source of the object flow + * @return the created pin or null if information is missing + */ + private InputPin createTarget(Action parentAction, ActivityNode objectFlowSource) { + if (objectFlowSource instanceof Pin) { + return createInputPin(parentAction, objectFlowSource.getName(), ((Pin) objectFlowSource).getType()); + } else { + // Source is not a pin, probably a control node. Ask for information + return null; + } + } + + /** + * Create a pin to use as source if all information is available + * + * @param parentAction + * the action containing the pin + * @param objectFlowTarget + * the target of the object flow + * @return the created pin or null if information is missing + */ + private OutputPin createSource(Action parentAction, ActivityNode objectFlowTarget) { + if (objectFlowTarget instanceof Pin) { + return createOutputPin(parentAction, objectFlowTarget.getName(), ((Pin) objectFlowTarget).getType()); + } else { + // Source is not a pin, probably a control node. Ask for information + return null; + } + } + + /** + * Create an input pin + * + * @param parentAction + * the action containing this pin + * @param name + * pin name + * @param type + * pin type + * @return created pin + */ + private InputPin createInputPin(Action parentAction, String name, Type type) { + InputPin result = UMLFactory.eINSTANCE.createInputPin(); + result.setName(name); + result.setType(type); + CustomObjectFlowEditHelper.insertInputPin(parentAction, result); + return result; + } + + /** + * Create an output pin + * + * @param parentAction + * the action containing this pin + * @param name + * pin name + * @param type + * pin type + * @return created pin + */ + private OutputPin createOutputPin(Action parentAction, String name, Type type) { + OutputPin result = UMLFactory.eINSTANCE.createOutputPin(); + result.setName(name); + result.setType(type); + CustomObjectFlowEditHelper.insertOutputPin(parentAction, result); + return result; + } + + /** + * Create the form to : + * + * - ask the user the name of pins to create. + * + * - ask the user the type of pins to create. + * + * @see org.eclipse.ui.forms.FormDialog#createFormContent(org.eclipse.ui.forms.IManagedForm) + */ + @Override + protected void createFormContent(IManagedForm pForm) { + pForm.getForm().setText(TITLE); + ScrolledForm scrolledForm = pForm.getForm(); + FormToolkit toolkit = pForm.getToolkit(); + Composite parent = scrolledForm.getBody(); + parent.setLayout(new GridLayout()); + createPinCreationSection(scrolledForm.getBody(), toolkit); + hookListeners(); + scrolledForm.reflow(true); + } + + /** + * Create the section to ask the user to parameterize the pin. + * + * @param pParent + * the section's parent widget + * @param pToolkit + * the form toolkit + */ + private void createPinCreationSection(Composite pParent, FormToolkit pToolkit) { + // create the section + String lSectionTitle = PIN_CREATION_SECTION_TITLE; + Section lSection = pToolkit.createSection(pParent, ExpandableComposite.EXPANDED | ExpandableComposite.TITLE_BAR); + lSection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + if (lSectionTitle != null) { + lSection.setText(lSectionTitle); + } + ImageHyperlink componentHelp = HelpComponentFactory.createHelpComponent(lSection, pToolkit, CustomMessages.CreatePinsForObjectFlowDialog_PinCreationHelp, true); + lSection.setTextClient(componentHelp); + ScrolledForm lInsideScrolledForm = pToolkit.createScrolledForm(lSection); + lInsideScrolledForm.setExpandHorizontal(true); + lInsideScrolledForm.setExpandVertical(true); + Composite lBody = lInsideScrolledForm.getBody(); + GridLayout lLayout = new GridLayout(); + lLayout.numColumns = 3; + lBody.setLayout(lLayout); + // content of the section + pToolkit.createLabel(lBody, NAME_LABEL, SWT.NONE); + creationNameText = pToolkit.createText(lBody, NAME_INITIAL_VALUE, SWT.BORDER); + creationNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); + creationNameText.setFocus(); + pToolkit.createLabel(lBody, TYPE_LABEL, SWT.NONE); + creationTypeText = pToolkit.createText(lBody, "", SWT.BORDER | SWT.READ_ONLY); + creationTypeText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + creationTypeButton = pToolkit.createButton(lBody, "...", SWT.FLAT); + Image image = UMLElementTypes.getImage(UMLPackage.eINSTANCE.getClass_()); + creationTypeButton.setImage(image); + creationTypeButton.setLayoutData(new GridData(SWT.NONE)); + lInsideScrolledForm.reflow(true); + lSection.setClient(lInsideScrolledForm); + } + + /** + * Add listeners to widgets + */ + private void hookListeners() { + // listener to new pin name + ModifyListener lNameListener = new ModifyListener() { + + /** + * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) + */ + @Override + public void modifyText(ModifyEvent e) { + creationName = creationNameText.getText(); + } + }; + creationNameText.addModifyListener(lNameListener); + // listener to select new pin type + SelectionListener selectTypeBtnListener = new SelectionAdapter() { + + /** + * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent) + */ + @Override + public void widgetSelected(SelectionEvent e) { + handleChooseType(); + } + }; + creationTypeButton.addSelectionListener(selectTypeBtnListener); + } + + /** + * Open the dialog to choose the type of the pin(s) to create + * + */ + private void handleChooseType() { + /* + * TODO Backport + */ + // UMLMultiEClassifierTreeSelectorDialog dialog = new UMLMultiEClassifierTreeSelectorDialog(getShell(),initialSource, Sets.newHashSet(UMLPackage.Literals.TYPE)); + // dialog.setMessage(CustomMessages.UMLModelingAssistantProviderMessage); + // dialog.setTitle(CustomMessages.UMLModelingAssistantProviderTitle); + // if(dialog.open() == Window.OK) { + // creationType = (Type)dialog.getTheResult(); + // creationTypeText.setText(dialog.getText(creationType)); + // } + } + + /** + * Set correctly the invoked object, by creating it if needed. Then, + * notifies that the ok button of this dialog has been pressed. + * + * @see org.eclipse.jface.dialogs.Dialog#okPressed() + * + */ + @Override + protected void okPressed() { + // create pins if needed + if (newSource == null) { + newSource = createOutputPin((OpaqueAction) initialSource, creationName, creationType); + } + if (newTarget == null) { + newTarget = createInputPin((OpaqueAction) initialTarget, creationName, creationType); + } + super.okPressed(); + } + + /** + * Get the node to use as object flow source + * + * @return new source + */ + public ActivityNode getSource() { + return newSource; + } + + /** + * Get the node to use as object flow target + * + * @return new target + */ + public ActivityNode getTarget() { + return newTarget; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateSendSignalActionDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateSendSignalActionDialog.java index 20c2521a522..3ba517abfe4 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateSendSignalActionDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/CreateSendSignalActionDialog.java @@ -1,178 +1,178 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Set;
-
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EClassifier;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.Package;
-import org.eclipse.uml2.uml.UMLPackage;
-
-import com.google.common.collect.Sets;
-
-/**
- * This class provides a dialog to initialize a SendSignalAction at its
- * creation.
- */
-public class CreateSendSignalActionDialog extends CreateInvocationActionDialog {
-
-
-
- /**
- * Create a new dialog to initialize a SendSignalAction.
- *
- * @param shell
- * parent shell
- * @param owner
- * the activity that owns the action
- */
- public CreateSendSignalActionDialog(Shell shell, Activity owner, InvocationAction newAction) {
- super(shell, owner, newAction);
- }
-
- /**
- * Get the id of the preference storing whether selection is the default
- * choice.
- *
- * @return preference id
- */
- @Override
- protected String getSelectionIsDefaultPreference() {
- return IActivityPreferenceConstants.PREF_NEW_SEND_SIGNAL_ACTION_SELECT_AS_DEFAULT;
- }
-
- /**
- * Get the id of the preference storing the last selected owner.
- *
- * @return preference id
- */
- @Override
- protected String getCreationDefaultOwnerPreference() {
- return IActivityPreferenceConstants.PREF_NEW_SEND_SIGNAL_ACTION_CREATION_OWNER;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionTitle()
- */
- @Override
- protected String getInvocationCreationSectionTitle() {
- return CustomMessages.CreateCallActionDialog_SignalInvocationCreationTitle;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionHelp()
- */
- @Override
- protected String getInvocationCreationSectionHelp() {
- return CustomMessages.CreateCallActionDialog_SignalInvocationCreationHelp;
- }
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationSelectionSectionTitle()
- */
- @Override
- protected String getInvocationSelectionSectionTitle() {
- return CustomMessages.CreateCallActionDialog_SignalInvocationSelectionTitle;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getTitle()
- */
- @Override
- protected String getTitle() {
- return CustomMessages.CreateCallActionDialog_SignalTitle;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getInvocationFeature()
- */
- @Override
- protected EReference getInvocationFeature() {
- return UMLPackage.eINSTANCE.getSendSignalAction_Signal();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedParents()
- */
- @Override
- protected Set<? extends EClassifier> getPossibleInvokedParents(EObject actionParent) {
- return Sets.newHashSet(UMLPackage.Literals.PACKAGE);
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#isPossibleInvokedParent(org.eclipse.emf.ecore.EObject)
- */
- @Override
- protected boolean isPossibleInvokedParent(EObject parent) {
- return parent instanceof Package;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedTypes()
- */
- @Override
- protected EClass[] getPossibleInvokedTypes() {
- return new EClass[] { UMLPackage.eINSTANCE.getSignal() };
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getCreationLabel()
- */
- @Override
- protected String getCreationLabel() {
- return CustomMessages.CreateCallActionDialog_CreateSignal;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getSelectionLabel()
- */
- @Override
- protected String getSelectionLabel() {
- return CustomMessages.CreateCallActionDialog_SelectSignal;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getParentImage()
- */
- @Override
- protected Image getParentImage() {
- return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage());
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Set; + +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLElementTypes; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.Package; +import org.eclipse.uml2.uml.UMLPackage; + +import com.google.common.collect.Sets; + +/** + * This class provides a dialog to initialize a SendSignalAction at its + * creation. + */ +public class CreateSendSignalActionDialog extends CreateInvocationActionDialog { + + + + /** + * Create a new dialog to initialize a SendSignalAction. + * + * @param shell + * parent shell + * @param owner + * the activity that owns the action + */ + public CreateSendSignalActionDialog(Shell shell, Activity owner, InvocationAction newAction) { + super(shell, owner, newAction); + } + + /** + * Get the id of the preference storing whether selection is the default + * choice. + * + * @return preference id + */ + @Override + protected String getSelectionIsDefaultPreference() { + return IActivityPreferenceConstants.PREF_NEW_SEND_SIGNAL_ACTION_SELECT_AS_DEFAULT; + } + + /** + * Get the id of the preference storing the last selected owner. + * + * @return preference id + */ + @Override + protected String getCreationDefaultOwnerPreference() { + return IActivityPreferenceConstants.PREF_NEW_SEND_SIGNAL_ACTION_CREATION_OWNER; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionTitle() + */ + @Override + protected String getInvocationCreationSectionTitle() { + return CustomMessages.CreateCallActionDialog_SignalInvocationCreationTitle; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationCreationSectionHelp() + */ + @Override + protected String getInvocationCreationSectionHelp() { + return CustomMessages.CreateCallActionDialog_SignalInvocationCreationHelp; + } + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#getInvocationSelectionSectionTitle() + */ + @Override + protected String getInvocationSelectionSectionTitle() { + return CustomMessages.CreateCallActionDialog_SignalInvocationSelectionTitle; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getTitle() + */ + @Override + protected String getTitle() { + return CustomMessages.CreateCallActionDialog_SignalTitle; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getInvocationFeature() + */ + @Override + protected EReference getInvocationFeature() { + return UMLPackage.eINSTANCE.getSendSignalAction_Signal(); + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedParents() + */ + @Override + protected Set<? extends EClassifier> getPossibleInvokedParents(EObject actionParent) { + return Sets.newHashSet(UMLPackage.Literals.PACKAGE); + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateInvocationActionDialog#isPossibleInvokedParent(org.eclipse.emf.ecore.EObject) + */ + @Override + protected boolean isPossibleInvokedParent(EObject parent) { + return parent instanceof Package; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getPossibleInvokedTypes() + */ + @Override + protected EClass[] getPossibleInvokedTypes() { + return new EClass[] { UMLPackage.eINSTANCE.getSignal() }; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getCreationLabel() + */ + @Override + protected String getCreationLabel() { + return CustomMessages.CreateCallActionDialog_CreateSignal; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getSelectionLabel() + */ + @Override + protected String getSelectionLabel() { + return CustomMessages.CreateCallActionDialog_SelectSignal; + } + + /** + * {@inheritDoc} + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.CreateCallActionDialog#getParentImage() + */ + @Override + protected Image getParentImage() { + return UMLElementTypes.getImage(UMLPackage.eINSTANCE.getPackage()); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndCreateAttributeDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndCreateAttributeDialog.java index 78c0b3feaaf..2ac2fa956c8 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndCreateAttributeDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndCreateAttributeDialog.java @@ -1,182 +1,182 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Collection;
-import java.util.HashSet;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature.Setting;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.uml2.common.util.CacheAdapter;
-import org.eclipse.uml2.uml.NamedElement;
-import org.eclipse.uml2.uml.Property;
-
-/**
- * WarningAndCreateAttributeDialog warns the user he can not perform an action.
- * It enables him to create an attribute instead after appropriate warnings.
- */
-public class WarningAndCreateAttributeDialog extends MessageDialog {
-
- /** Label of the create button */
- private static final String CREATE_LABEL = CustomMessages.CreateAttributeDialog_Open;
-
- /** Start form tag */
- private static final String START_FORM = "<form>";
-
- /** End form tag */
- private static final String END_FORM = "</form>";
-
- /** List tag with content format */
- private static final String LIST_FORMAT = "<li>%s</li>";
-
- /** < symbol to replace */
- private static final String LT = "<";
-
- /** < symbol escaped replacement */
- private static final String ESC_LT = "<";
-
- /** > symbol to replace */
- private static final String GT = ">";
-
- /** > symbol escaped replacement */
- private static final String ESC_GT = ">";
-
- /** Element owning the attribute if created */
- private NamedElement attributeOwner = null;
-
- /** Created attribute */
- private Property attribute;
-
- /** Label provider to use */
- private ILabelProvider provider = null;
-
- /**
- * Constructor.
- *
- * @param parentShell
- * shell
- * @param dialogTitle
- * title of the dialog
- * @param dialogMessage
- * main message of the dialog
- * @param linkElement
- * element to show
- * @param labelProvider
- * label provider
- */
- public WarningAndCreateAttributeDialog(Shell parentShell, String dialogTitle, String dialogMessage, NamedElement linkElement, ILabelProvider labelProvider) {
- super(parentShell, dialogTitle, null, dialogMessage, WARNING, new String[] { CREATE_LABEL, IDialogConstants.CLOSE_LABEL }, 0);
- attributeOwner = linkElement;
- provider = labelProvider;
- }
-
- /**
- * Create the deactivated link and the warning message for attribute
- * creation
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndLinkDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
- * @param parent
- * the parent composite
- * @return hyperlink
- */
- @Override
- protected Control createCustomArea(Composite parent) {
- Control result = super.createCustomArea(parent);
- FormToolkit toolkit = new FormToolkit(parent.getDisplay());
- FormText text = toolkit.createFormText(parent, false);
- text.setText(getImpactedElementsText(), true, false);
- text.setBackground(parent.getBackground());
- text.setLayoutData(new GridData(GridData.FILL_BOTH));
- return result;
- }
-
- /**
- * Get the text to warn about the impacts of attribute creation
- *
- * @return text
- */
- private String getImpactedElementsText() {
- StringBuffer completeText = new StringBuffer();
- completeText.append(START_FORM);
- StringBuffer impactText = new StringBuffer();
- // explore referencing elements
- Collection<Setting> references = CacheAdapter.getInstance().getNonNavigableInverseReferences(attributeOwner);
- HashSet<EObject> impactedElements = new HashSet<EObject>();
- for (Setting ref : references) {
- EObject referencing = ref.getEObject();
- if (referencing.eContainer() != null && !(referencing instanceof View) && !impactedElements.contains(referencing)) {
- impactedElements.add(referencing);
- String elementText = provider.getText(referencing);
- elementText = elementText.replaceAll(LT, ESC_LT).replaceAll(GT, ESC_GT);
- if (referencing instanceof NamedElement) {
- String qualifiedName = ((NamedElement) referencing).getQualifiedName();
- if (qualifiedName != null && qualifiedName.length() != 0) {
- elementText = elementText + " (" + qualifiedName + ")";
- }
- }
- impactText.append(String.format(LIST_FORMAT, elementText));
- }
- }
- if (impactedElements.size() <= 1) {
- completeText.append(CustomMessages.CreateAttributeDialog_WarnNoImpact);
- } else {
- completeText.append(CustomMessages.CreateAttributeDialog_WarnImpact);
- completeText.append(impactText.toString());
- }
- completeText.append(END_FORM);
- return completeText.toString();
- }
-
- /**
- * Launch create dialog if needed.
- *
- * @see org.eclipse.jface.dialogs.MessageDialog#buttonPressed(int)
- * @param buttonId
- * id of pressed button
- */
- @Override
- protected void buttonPressed(int buttonId) {
- if (buttonId == OK) {
- // Create button has been pressed
- CreateAttributeDialog dialog = new CreateAttributeDialog(getShell(), attributeOwner);
- // close dialog only if attribute has been created
- if (dialog.open() == OK) {
- attribute = dialog.getCreatedAttribute();
- super.buttonPressed(buttonId);
- }
- } else {
- super.buttonPressed(buttonId);
- }
- }
-
- /**
- * Get the created attribute
- *
- * @return created attribute or null
- */
- public Property getAttribute() {
- return attribute;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Collection; +import java.util.HashSet; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature.Setting; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.forms.widgets.FormText; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.uml2.common.util.CacheAdapter; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.Property; + +/** + * WarningAndCreateAttributeDialog warns the user he can not perform an action. + * It enables him to create an attribute instead after appropriate warnings. + */ +public class WarningAndCreateAttributeDialog extends MessageDialog { + + /** Label of the create button */ + private static final String CREATE_LABEL = CustomMessages.CreateAttributeDialog_Open; + + /** Start form tag */ + private static final String START_FORM = "<form>"; + + /** End form tag */ + private static final String END_FORM = "</form>"; + + /** List tag with content format */ + private static final String LIST_FORMAT = "<li>%s</li>"; + + /** < symbol to replace */ + private static final String LT = "<"; + + /** < symbol escaped replacement */ + private static final String ESC_LT = "<"; + + /** > symbol to replace */ + private static final String GT = ">"; + + /** > symbol escaped replacement */ + private static final String ESC_GT = ">"; + + /** Element owning the attribute if created */ + private NamedElement attributeOwner = null; + + /** Created attribute */ + private Property attribute; + + /** Label provider to use */ + private ILabelProvider provider = null; + + /** + * Constructor. + * + * @param parentShell + * shell + * @param dialogTitle + * title of the dialog + * @param dialogMessage + * main message of the dialog + * @param linkElement + * element to show + * @param labelProvider + * label provider + */ + public WarningAndCreateAttributeDialog(Shell parentShell, String dialogTitle, String dialogMessage, NamedElement linkElement, ILabelProvider labelProvider) { + super(parentShell, dialogTitle, null, dialogMessage, WARNING, new String[] { CREATE_LABEL, IDialogConstants.CLOSE_LABEL }, 0); + attributeOwner = linkElement; + provider = labelProvider; + } + + /** + * Create the deactivated link and the warning message for attribute + * creation + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndLinkDialog#createCustomArea(org.eclipse.swt.widgets.Composite) + * @param parent + * the parent composite + * @return hyperlink + */ + @Override + protected Control createCustomArea(Composite parent) { + Control result = super.createCustomArea(parent); + FormToolkit toolkit = new FormToolkit(parent.getDisplay()); + FormText text = toolkit.createFormText(parent, false); + text.setText(getImpactedElementsText(), true, false); + text.setBackground(parent.getBackground()); + text.setLayoutData(new GridData(GridData.FILL_BOTH)); + return result; + } + + /** + * Get the text to warn about the impacts of attribute creation + * + * @return text + */ + private String getImpactedElementsText() { + StringBuffer completeText = new StringBuffer(); + completeText.append(START_FORM); + StringBuffer impactText = new StringBuffer(); + // explore referencing elements + Collection<Setting> references = CacheAdapter.getInstance().getNonNavigableInverseReferences(attributeOwner); + HashSet<EObject> impactedElements = new HashSet<EObject>(); + for (Setting ref : references) { + EObject referencing = ref.getEObject(); + if (referencing.eContainer() != null && !(referencing instanceof View) && !impactedElements.contains(referencing)) { + impactedElements.add(referencing); + String elementText = provider.getText(referencing); + elementText = elementText.replaceAll(LT, ESC_LT).replaceAll(GT, ESC_GT); + if (referencing instanceof NamedElement) { + String qualifiedName = ((NamedElement) referencing).getQualifiedName(); + if (qualifiedName != null && qualifiedName.length() != 0) { + elementText = elementText + " (" + qualifiedName + ")"; + } + } + impactText.append(String.format(LIST_FORMAT, elementText)); + } + } + if (impactedElements.size() <= 1) { + completeText.append(CustomMessages.CreateAttributeDialog_WarnNoImpact); + } else { + completeText.append(CustomMessages.CreateAttributeDialog_WarnImpact); + completeText.append(impactText.toString()); + } + completeText.append(END_FORM); + return completeText.toString(); + } + + /** + * Launch create dialog if needed. + * + * @see org.eclipse.jface.dialogs.MessageDialog#buttonPressed(int) + * @param buttonId + * id of pressed button + */ + @Override + protected void buttonPressed(int buttonId) { + if (buttonId == OK) { + // Create button has been pressed + CreateAttributeDialog dialog = new CreateAttributeDialog(getShell(), attributeOwner); + // close dialog only if attribute has been created + if (dialog.open() == OK) { + attribute = dialog.getCreatedAttribute(); + super.buttonPressed(buttonId); + } + } else { + super.buttonPressed(buttonId); + } + } + + /** + * Get the created attribute + * + * @return created attribute or null + */ + public Property getAttribute() { + return attribute; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndCreateParameterDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndCreateParameterDialog.java index f650db52e84..9cbdc614525 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndCreateParameterDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndCreateParameterDialog.java @@ -1,189 +1,189 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import java.util.Collection;
-import java.util.HashSet;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature.Setting;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.uml2.common.util.CacheAdapter;
-import org.eclipse.uml2.uml.NamedElement;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.ParameterDirectionKind;
-
-/**
- * WarningAndCreateParameterDialog warns the user he can not perform an action.
- * It enables him to create a parameter instead after appropriate warnings.
- */
-public class WarningAndCreateParameterDialog extends MessageDialog {
-
- /** Label of the create button */
- private static final String CREATE_LABEL = CustomMessages.CreateParameterDialog_Open;
-
- /** Start form tag */
- private static final String START_FORM = "<form>";
-
- /** End form tag */
- private static final String END_FORM = "</form>";
-
- /** List tag with content format */
- private static final String LIST_FORMAT = "<li>%s</li>";
-
- /** < symbol to replace */
- private static final String LT = "<";
-
- /** < symbol escaped replacement */
- private static final String ESC_LT = "<";
-
- /** > symbol to replace */
- private static final String GT = ">";
-
- /** > symbol escaped replacement */
- private static final String ESC_GT = ">";
-
- /** Element owning the parameter if created */
- private NamedElement parameterOwner = null;
-
- /** Direction to choose as default */
- private ParameterDirectionKind defaultDirection;
-
- /** Created parameter */
- private Parameter parameter = null;
-
- /** Label provider to use */
- private ILabelProvider provider = null;
-
- /**
- * Constructor.
- *
- * @param parentShell
- * shell
- * @param dialogTitle
- * title of the dialog
- * @param dialogMessage
- * main message of the dialog
- * @param linkElement
- * element to show
- * @param labelProvider
- * label provider
- * @param preferredDirection
- * direction to use as default for parameter creation
- */
- public WarningAndCreateParameterDialog(Shell parentShell, String dialogTitle, String dialogMessage, NamedElement linkElement, ILabelProvider labelProvider, ParameterDirectionKind preferredDirection) {
- super(parentShell, dialogTitle, null, dialogMessage, WARNING, new String[] { CREATE_LABEL, IDialogConstants.CLOSE_LABEL }, 0);
- parameterOwner = linkElement;
- defaultDirection = preferredDirection;
- provider = labelProvider;
- }
-
- /**
- * Create the deactivated link and the warning message for parameter
- * creation
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndLinkDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
- * @param parent
- * the parent composite
- * @return hyperlink
- */
- @Override
- protected Control createCustomArea(Composite parent) {
- Control result = super.createCustomArea(parent);
- FormToolkit toolkit = new FormToolkit(parent.getDisplay());
- FormText text = toolkit.createFormText(parent, false);
- text.setText(getImpactedElementsText(), true, false);
- text.setBackground(parent.getBackground());
- text.setLayoutData(new GridData(GridData.FILL_BOTH));
- return result;
- }
-
- /**
- * Get the text to warn about the impacts of parameter creation
- *
- * @return text
- */
- private String getImpactedElementsText() {
- StringBuffer completeText = new StringBuffer();
- completeText.append(START_FORM);
- StringBuffer impactText = new StringBuffer();
- // explore referencing elements
- Collection<Setting> references = CacheAdapter.getInstance().getNonNavigableInverseReferences(parameterOwner);
- HashSet<EObject> impactedElements = new HashSet<EObject>();
- for (Setting ref : references) {
- EObject referencing = ref.getEObject();
- if (referencing.eContainer() != null && !(referencing instanceof View) && !impactedElements.contains(referencing)) {
- impactedElements.add(referencing);
- String elementText = provider.getText(referencing);
- elementText = elementText.replaceAll(LT, ESC_LT).replaceAll(GT, ESC_GT);
- if (referencing instanceof NamedElement) {
- String qualifiedName = ((NamedElement) referencing).getQualifiedName();
- if (qualifiedName != null && qualifiedName.length() != 0) {
- elementText = elementText + " (" + qualifiedName + ")";
- }
- }
- impactText.append(String.format(LIST_FORMAT, elementText));
- }
- }
- if (impactedElements.size() <= 1) {
- completeText.append(CustomMessages.CreateParameterDialog_WarnNoImpact);
- } else {
- completeText.append(CustomMessages.CreateParameterDialog_WarnImpact);
- completeText.append(impactText.toString());
- }
- completeText.append(END_FORM);
- return completeText.toString();
- }
-
- /**
- * Launch create dialog if needed.
- *
- * @see org.eclipse.jface.dialogs.MessageDialog#buttonPressed(int)
- * @param buttonId
- * id of pressed button
- */
- @Override
- protected void buttonPressed(int buttonId) {
- if (buttonId == OK) {
- // Create button has been pressed
- CreateParameterDialog dialog = new CreateParameterDialog(getShell(), parameterOwner, defaultDirection);
- // close dialog only if parameter has been created
- if (dialog.open() == OK) {
- parameter = dialog.getCreatedParameter();
- super.buttonPressed(buttonId);
- }
- } else {
- super.buttonPressed(buttonId);
- }
- }
-
- /**
- * Get the created parameter
- *
- * @return created parameter or null
- */
- public Parameter getParameter() {
- return parameter;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import java.util.Collection; +import java.util.HashSet; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature.Setting; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.forms.widgets.FormText; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.uml2.common.util.CacheAdapter; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.ParameterDirectionKind; + +/** + * WarningAndCreateParameterDialog warns the user he can not perform an action. + * It enables him to create a parameter instead after appropriate warnings. + */ +public class WarningAndCreateParameterDialog extends MessageDialog { + + /** Label of the create button */ + private static final String CREATE_LABEL = CustomMessages.CreateParameterDialog_Open; + + /** Start form tag */ + private static final String START_FORM = "<form>"; + + /** End form tag */ + private static final String END_FORM = "</form>"; + + /** List tag with content format */ + private static final String LIST_FORMAT = "<li>%s</li>"; + + /** < symbol to replace */ + private static final String LT = "<"; + + /** < symbol escaped replacement */ + private static final String ESC_LT = "<"; + + /** > symbol to replace */ + private static final String GT = ">"; + + /** > symbol escaped replacement */ + private static final String ESC_GT = ">"; + + /** Element owning the parameter if created */ + private NamedElement parameterOwner = null; + + /** Direction to choose as default */ + private ParameterDirectionKind defaultDirection; + + /** Created parameter */ + private Parameter parameter = null; + + /** Label provider to use */ + private ILabelProvider provider = null; + + /** + * Constructor. + * + * @param parentShell + * shell + * @param dialogTitle + * title of the dialog + * @param dialogMessage + * main message of the dialog + * @param linkElement + * element to show + * @param labelProvider + * label provider + * @param preferredDirection + * direction to use as default for parameter creation + */ + public WarningAndCreateParameterDialog(Shell parentShell, String dialogTitle, String dialogMessage, NamedElement linkElement, ILabelProvider labelProvider, ParameterDirectionKind preferredDirection) { + super(parentShell, dialogTitle, null, dialogMessage, WARNING, new String[] { CREATE_LABEL, IDialogConstants.CLOSE_LABEL }, 0); + parameterOwner = linkElement; + defaultDirection = preferredDirection; + provider = labelProvider; + } + + /** + * Create the deactivated link and the warning message for parameter + * creation + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndLinkDialog#createCustomArea(org.eclipse.swt.widgets.Composite) + * @param parent + * the parent composite + * @return hyperlink + */ + @Override + protected Control createCustomArea(Composite parent) { + Control result = super.createCustomArea(parent); + FormToolkit toolkit = new FormToolkit(parent.getDisplay()); + FormText text = toolkit.createFormText(parent, false); + text.setText(getImpactedElementsText(), true, false); + text.setBackground(parent.getBackground()); + text.setLayoutData(new GridData(GridData.FILL_BOTH)); + return result; + } + + /** + * Get the text to warn about the impacts of parameter creation + * + * @return text + */ + private String getImpactedElementsText() { + StringBuffer completeText = new StringBuffer(); + completeText.append(START_FORM); + StringBuffer impactText = new StringBuffer(); + // explore referencing elements + Collection<Setting> references = CacheAdapter.getInstance().getNonNavigableInverseReferences(parameterOwner); + HashSet<EObject> impactedElements = new HashSet<EObject>(); + for (Setting ref : references) { + EObject referencing = ref.getEObject(); + if (referencing.eContainer() != null && !(referencing instanceof View) && !impactedElements.contains(referencing)) { + impactedElements.add(referencing); + String elementText = provider.getText(referencing); + elementText = elementText.replaceAll(LT, ESC_LT).replaceAll(GT, ESC_GT); + if (referencing instanceof NamedElement) { + String qualifiedName = ((NamedElement) referencing).getQualifiedName(); + if (qualifiedName != null && qualifiedName.length() != 0) { + elementText = elementText + " (" + qualifiedName + ")"; + } + } + impactText.append(String.format(LIST_FORMAT, elementText)); + } + } + if (impactedElements.size() <= 1) { + completeText.append(CustomMessages.CreateParameterDialog_WarnNoImpact); + } else { + completeText.append(CustomMessages.CreateParameterDialog_WarnImpact); + completeText.append(impactText.toString()); + } + completeText.append(END_FORM); + return completeText.toString(); + } + + /** + * Launch create dialog if needed. + * + * @see org.eclipse.jface.dialogs.MessageDialog#buttonPressed(int) + * @param buttonId + * id of pressed button + */ + @Override + protected void buttonPressed(int buttonId) { + if (buttonId == OK) { + // Create button has been pressed + CreateParameterDialog dialog = new CreateParameterDialog(getShell(), parameterOwner, defaultDirection); + // close dialog only if parameter has been created + if (dialog.open() == OK) { + parameter = dialog.getCreatedParameter(); + super.buttonPressed(buttonId); + } + } else { + super.buttonPressed(buttonId); + } + } + + /** + * Get the created parameter + * + * @return created parameter or null + */ + public Parameter getParameter() { + return parameter; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndLinkDialog.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndLinkDialog.java index 6ad8d7af2ef..1cbe9dbade1 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndLinkDialog.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/dialogs/WarningAndLinkDialog.java @@ -1,155 +1,155 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
-import org.eclipse.papyrus.infra.ui.util.EditorUtils;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IViewReference;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Hyperlink;
-import org.eclipse.ui.navigator.CommonNavigator;
-import org.eclipse.uml2.uml.NamedElement;
-
-/**
- * This dialog provide a message and a link to navigate to a model element.
- */
-public class WarningAndLinkDialog extends MessageDialog {
-
- /** The element to link */
- private NamedElement element;
-
- /** The label of the link */
- private String label;
-
- /** Whether the dialog closes on navigation */
- private boolean allowNavigation;
-
- /**
- * Construct a new dialog to open a warning message and a link to an
- * element.
- *
- * @param parentShell
- * the parent shell
- * @param dialogTitle
- * the title
- * @param dialogMessage
- * the message
- * @param linkElement
- * the element link redirects to
- * @param linkLabel
- * the label of the link
- */
- public WarningAndLinkDialog(Shell parentShell, String dialogTitle, String dialogMessage, NamedElement linkElement, String linkLabel) {
- super(parentShell, dialogTitle, null, dialogMessage, WARNING, new String[] { IDialogConstants.OK_LABEL }, 0);
- element = linkElement;
- label = linkLabel;
- allowNavigation = true;
- }
-
- /**
- * Construct a new dialog to open a warning message and a link to an
- * element.
- *
- * @param parentShell
- * the parent shell
- * @param dialogTitle
- * the dialog title, or <code>null</code> if none
- * @param dialogTitleImage
- * the dialog title image, or <code>null</code> if none
- * @param dialogMessage
- * the dialog message
- * @param dialogImageType
- * one of the following values:
- * <ul>
- * <li><code>MessageDialog.NONE</code> for a dialog with no image</li>
- * <li><code>MessageDialog.ERROR</code> for a dialog with an error image</li>
- * <li><code>MessageDialog.INFORMATION</code> for a dialog with an information image</li>
- * <li><code>MessageDialog.QUESTION </code> for a dialog with a question image</li>
- * <li><code>MessageDialog.WARNING</code> for a dialog with a warning image</li>
- * </ul>
- * @param dialogButtonLabels
- * an array of labels for the buttons in the button bar
- * @param defaultIndex
- * the index in the button label array of the default button
- * @param linkElement
- * the element link redirects to
- * @param linkLabel
- * the label of the link
- */
- protected WarningAndLinkDialog(Shell parentShell, String dialogTitle, Image dialogTitleImage, String dialogMessage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex, NamedElement linkElement, String linkLabel, boolean closeAfterNavigation) {
- super(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, dialogButtonLabels, defaultIndex);
- element = linkElement;
- label = linkLabel;
- allowNavigation = closeAfterNavigation;
- }
-
- /**
- * Create the link to the element
- *
- * @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
- *
- * @param parent
- * the parent composite
- * @return the hyperlink control
- */
- @Override
- protected Control createCustomArea(Composite parent) {
- FormToolkit toolkit = new FormToolkit(parent.getDisplay());
- Hyperlink hyperLink = toolkit.createHyperlink(parent, label, SWT.UNDERLINE_LINK);
- hyperLink.setBackground(parent.getBackground());
- hyperLink.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false));
- if (allowNavigation) {
- hyperLink.addHyperlinkListener(new HyperlinkAdapter() {
-
- @Override
- public void linkActivated(HyperlinkEvent e) {
- navigateToElement();
- okPressed();
- }
- });
- }
- return hyperLink;
- }
-
- /**
- * Navigate to the linked element. Open it in model editor and print its
- * properties.
- */
- protected void navigateToElement() {
- IMultiDiagramEditor editor = EditorUtils.getMultiDiagramEditor();
- IViewReference[] views = editor.getSite().getPage().getViewReferences();
- for (IViewReference view : views) {
- IWorkbenchPart part = view.getPart(false);
- if (part instanceof CommonNavigator) {
- CommonNavigator navigator = (CommonNavigator) part;
- // set focus to navigator, otherwise, diagram view will reset
- // the selection
- navigator.setFocus();
- navigator.selectReveal(new StructuredSelection(element));
- }
- }
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.dialogs; + +import org.eclipse.jface.dialogs.IDialogConstants; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor; +import org.eclipse.papyrus.infra.ui.util.EditorUtils; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IViewReference; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.forms.events.HyperlinkAdapter; +import org.eclipse.ui.forms.events.HyperlinkEvent; +import org.eclipse.ui.forms.widgets.FormToolkit; +import org.eclipse.ui.forms.widgets.Hyperlink; +import org.eclipse.ui.navigator.CommonNavigator; +import org.eclipse.uml2.uml.NamedElement; + +/** + * This dialog provide a message and a link to navigate to a model element. + */ +public class WarningAndLinkDialog extends MessageDialog { + + /** The element to link */ + private NamedElement element; + + /** The label of the link */ + private String label; + + /** Whether the dialog closes on navigation */ + private boolean allowNavigation; + + /** + * Construct a new dialog to open a warning message and a link to an + * element. + * + * @param parentShell + * the parent shell + * @param dialogTitle + * the title + * @param dialogMessage + * the message + * @param linkElement + * the element link redirects to + * @param linkLabel + * the label of the link + */ + public WarningAndLinkDialog(Shell parentShell, String dialogTitle, String dialogMessage, NamedElement linkElement, String linkLabel) { + super(parentShell, dialogTitle, null, dialogMessage, WARNING, new String[] { IDialogConstants.OK_LABEL }, 0); + element = linkElement; + label = linkLabel; + allowNavigation = true; + } + + /** + * Construct a new dialog to open a warning message and a link to an + * element. + * + * @param parentShell + * the parent shell + * @param dialogTitle + * the dialog title, or <code>null</code> if none + * @param dialogTitleImage + * the dialog title image, or <code>null</code> if none + * @param dialogMessage + * the dialog message + * @param dialogImageType + * one of the following values: + * <ul> + * <li><code>MessageDialog.NONE</code> for a dialog with no image</li> + * <li><code>MessageDialog.ERROR</code> for a dialog with an error image</li> + * <li><code>MessageDialog.INFORMATION</code> for a dialog with an information image</li> + * <li><code>MessageDialog.QUESTION </code> for a dialog with a question image</li> + * <li><code>MessageDialog.WARNING</code> for a dialog with a warning image</li> + * </ul> + * @param dialogButtonLabels + * an array of labels for the buttons in the button bar + * @param defaultIndex + * the index in the button label array of the default button + * @param linkElement + * the element link redirects to + * @param linkLabel + * the label of the link + */ + protected WarningAndLinkDialog(Shell parentShell, String dialogTitle, Image dialogTitleImage, String dialogMessage, int dialogImageType, String[] dialogButtonLabels, int defaultIndex, NamedElement linkElement, String linkLabel, boolean closeAfterNavigation) { + super(parentShell, dialogTitle, dialogTitleImage, dialogMessage, dialogImageType, dialogButtonLabels, defaultIndex); + element = linkElement; + label = linkLabel; + allowNavigation = closeAfterNavigation; + } + + /** + * Create the link to the element + * + * @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite) + * + * @param parent + * the parent composite + * @return the hyperlink control + */ + @Override + protected Control createCustomArea(Composite parent) { + FormToolkit toolkit = new FormToolkit(parent.getDisplay()); + Hyperlink hyperLink = toolkit.createHyperlink(parent, label, SWT.UNDERLINE_LINK); + hyperLink.setBackground(parent.getBackground()); + hyperLink.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false)); + if (allowNavigation) { + hyperLink.addHyperlinkListener(new HyperlinkAdapter() { + + @Override + public void linkActivated(HyperlinkEvent e) { + navigateToElement(); + okPressed(); + } + }); + } + return hyperLink; + } + + /** + * Navigate to the linked element. Open it in model editor and print its + * properties. + */ + protected void navigateToElement() { + IMultiDiagramEditor editor = EditorUtils.getMultiDiagramEditor(); + IViewReference[] views = editor.getSite().getPage().getViewReferences(); + for (IViewReference view : views) { + IWorkbenchPart part = view.getPart(false); + if (part instanceof CommonNavigator) { + CommonNavigator navigator = (CommonNavigator) part; + // set focus to navigator, otherwise, diagram view will reset + // the selection + navigator.setFocus(); + navigator.selectReveal(new StructuredSelection(element)); + } + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/ActivityGroup/CustomInterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/ActivityGroup/CustomInterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart.java index 4b0b6fe979a..6422121920e 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/ActivityGroup/CustomInterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/ActivityGroup/CustomInterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart.java @@ -1,54 +1,54 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy - arthur.daussy@atos.net - Bug 368932 - [ActivitiyDiagram] Prevent Compartment of Activity group to be selected
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part.ActivityGroup;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart;
-
-/**
- * Set in order to have Generation Gap Pattern.
- *
- * @author arthur daussy
- *
- */
-public class CustomInterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart extends InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart implements IGroupCompartmentEditPart {
-
- public CustomInterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart(View view) {
- super(view);
- }
-
- /**
- * remove the top border
- */
- @Override
- public IFigure createFigure() {
- ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure();
- result.setTitleVisibility(false);
- // remove the top border
- result.setBorder(null);
- // Hide scrollBar
- return result;
- }
-
- /**
- * Unselectable EditPart
- */
- @Override
- public boolean isSelectable() {
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy - arthur.daussy@atos.net - Bug 368932 - [ActivitiyDiagram] Prevent Compartment of Activity group to be selected + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part.ActivityGroup; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart; + +/** + * Set in order to have Generation Gap Pattern. + * + * @author arthur daussy + * + */ +public class CustomInterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart extends InterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart implements IGroupCompartmentEditPart { + + public CustomInterruptibleActivityRegionInterruptibleActivityRegionContentCompartmentEditPart(View view) { + super(view); + } + + /** + * remove the top border + */ + @Override + public IFigure createFigure() { + ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure(); + result.setTitleVisibility(false); + // remove the top border + result.setBorder(null); + // Hide scrollBar + return result; + } + + /** + * Unselectable EditPart + */ + @Override + public boolean isSelectable() { + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/ActivityGroup/IGroupCompartmentEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/ActivityGroup/IGroupCompartmentEditPart.java index 37a25e697bf..d302729df7d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/ActivityGroup/IGroupCompartmentEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/ActivityGroup/IGroupCompartmentEditPart.java @@ -1,11 +1,11 @@ -package org.eclipse.papyrus.uml.diagram.activity.edit.part.ActivityGroup;
-
-/**
- * Is a Activity Group Compartment EditPart
- * TODO : Add to generator
- *
- * @author adaussy
- *
- */
-public interface IGroupCompartmentEditPart {
-}
+package org.eclipse.papyrus.uml.diagram.activity.edit.part.ActivityGroup; + +/** + * Is a Activity Group Compartment EditPart + * TODO : Add to generator + * + * @author adaussy + * + */ +public interface IGroupCompartmentEditPart { +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/BaseActivityContentCompartmentEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/BaseActivityContentCompartmentEditPart.java index 795d438cfc3..9eea0ffaf51 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/BaseActivityContentCompartmentEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/BaseActivityContentCompartmentEditPart.java @@ -1,52 +1,52 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.infra.gmfdiag.tooling.runtime.linklf.LinkLFShapeCompartmentEditPart;
-
-/**
- * @author adaussy
- *
- */
-public class BaseActivityContentCompartmentEditPart extends LinkLFShapeCompartmentEditPart {
-
- public BaseActivityContentCompartmentEditPart(View view) {
- super(view);
- }
-
- /**
- * remove the top border
- * hide title
- */
- @Override
- public IFigure createFigure() {
- ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure();
- result.setTitleVisibility(false);
- // remove the top border
- result.setBorder(null);
- return result;
- }
-
- /**
- * Unselectable compartment
- */
- @Override
- public boolean isSelectable() {
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.infra.gmfdiag.tooling.runtime.linklf.LinkLFShapeCompartmentEditPart; + +/** + * @author adaussy + * + */ +public class BaseActivityContentCompartmentEditPart extends LinkLFShapeCompartmentEditPart { + + public BaseActivityContentCompartmentEditPart(View view) { + super(view); + } + + /** + * remove the top border + * hide title + */ + @Override + public IFigure createFigure() { + ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure(); + result.setTitleVisibility(false); + // remove the top border + result.setBorder(null); + return result; + } + + /** + * Unselectable compartment + */ + @Override + public boolean isSelectable() { + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomAcceptTimeEventActionAppliedStereotypeEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomAcceptTimeEventActionAppliedStereotypeEditPart.java index b1fc10db25e..f7082d6f8ad 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomAcceptTimeEventActionAppliedStereotypeEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomAcceptTimeEventActionAppliedStereotypeEditPart.java @@ -1,35 +1,35 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) patrick.tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.AcceptTimeEventActionAppliedStereotypeEditPart;
-
-
-/**
- * this edit part prevent to a bad refresh with CSS
- *
- */
-public class CustomAcceptTimeEventActionAppliedStereotypeEditPart extends AcceptTimeEventActionAppliedStereotypeEditPart {
-
- public CustomAcceptTimeEventActionAppliedStereotypeEditPart(View view) {
- super(view);
-
- }
-
- @Override
- protected void refreshLabel() {
- // do nothing the label is only refresh by the editpolicy
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) patrick.tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.AcceptTimeEventActionAppliedStereotypeEditPart; + + +/** + * this edit part prevent to a bad refresh with CSS + * + */ +public class CustomAcceptTimeEventActionAppliedStereotypeEditPart extends AcceptTimeEventActionAppliedStereotypeEditPart { + + public CustomAcceptTimeEventActionAppliedStereotypeEditPart(View view) { + super(view); + + } + + @Override + protected void refreshLabel() { + // do nothing the label is only refresh by the editpolicy + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomActivityActivityContentCompartmentEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomActivityActivityContentCompartmentEditPart.java index a444b5add4c..e1da69c3e57 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomActivityActivityContentCompartmentEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomActivityActivityContentCompartmentEditPart.java @@ -1,51 +1,51 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityActivityContentCompartmentEditPart;
-
-/**
- * @author adaussy
- *
- */
-public class CustomActivityActivityContentCompartmentEditPart extends ActivityActivityContentCompartmentEditPart {
-
- public CustomActivityActivityContentCompartmentEditPart(View view) {
- super(view);
- }
-
- /**
- * remove the top border
- */
- @Override
- public IFigure createFigure() {
- ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure();
- result.setTitleVisibility(false);
- // remove the top border
- result.setBorder(null);
- return result;
- }
-
- /**
- * Unselectable compartment
- */
- @Override
- public boolean isSelectable() {
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityActivityContentCompartmentEditPart; + +/** + * @author adaussy + * + */ +public class CustomActivityActivityContentCompartmentEditPart extends ActivityActivityContentCompartmentEditPart { + + public CustomActivityActivityContentCompartmentEditPart(View view) { + super(view); + } + + /** + * remove the top border + */ + @Override + public IFigure createFigure() { + ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure(); + result.setTitleVisibility(false); + // remove the top border + result.setBorder(null); + return result; + } + + /** + * Unselectable compartment + */ + @Override + public boolean isSelectable() { + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomActivityPartitionNameEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomActivityPartitionNameEditPart.java index 3a8f353d228..c79f30ba086 100755 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomActivityPartitionNameEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomActivityPartitionNameEditPart.java @@ -1,39 +1,39 @@ -/*****************************************************************************
- * Copyright (c) 2017 Ericsson Communications and others.
- *
- * 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
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.infra.gmfdiag.common.figure.node.PapyrusWrappingLabel;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionNameEditPart;
-
-
-
-/**
- * @since 3.0
- */
-public class CustomActivityPartitionNameEditPart extends ActivityPartitionNameEditPart {
- /**
- * Constructor.
- *
- * @param view
- */
- public CustomActivityPartitionNameEditPart(View view) {
- super(view);
- }
-
- protected void setLabelTextHelper(IFigure figure, String text) {
- if (figure instanceof PapyrusWrappingLabel) {
- return;
- } else {
- super.setLabelTextHelper(figure, text);
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2017 Ericsson Communications and others. + * + * 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 + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.infra.gmfdiag.common.figure.node.PapyrusWrappingLabel; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionNameEditPart; + + + +/** + * @since 3.0 + */ +public class CustomActivityPartitionNameEditPart extends ActivityPartitionNameEditPart { + /** + * Constructor. + * + * @param view + */ + public CustomActivityPartitionNameEditPart(View view) { + super(view); + } + + protected void setLabelTextHelper(IFigure figure, String text) { + if (figure instanceof PapyrusWrappingLabel) { + return; + } else { + super.setLabelTextHelper(figure, text); + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowEditPart.java index b234e6b5b03..d7466bb23af 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowEditPart.java @@ -1,59 +1,59 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366026 - [ActivityDiagram] Refactoring in order to try respect Generation Gap Pattern
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
-import org.eclipse.gmf.runtime.notation.Node;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowInterruptibleIconEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLVisualIDRegistry;
-
-/**
- * Customization to implement InterruptibleEdge
- *
- * @author arthur daussy
- *
- */
-public class CustomControlFlowEditPart extends ControlFlowEditPart implements InterruptibleEdge {
-
- public CustomControlFlowEditPart(View view) {
- super(view);
- }
-
- /**
- * {@inheritDoc InterruptibleEdge}
- */
- @Override
- public String getInterruptibleEdgeIconVisualID() {
- return ControlFlowInterruptibleIconEditPart.VISUAL_ID;
- }
-
- /**
- * {@inheritDoc InterruptibleEdge}
- */
- @Override
- public Node getInterrutibleEgdeIcon() {
- Object view = getModel();
- if (view instanceof View) {
- View node = ViewUtil.getChildBySemanticHint((View) view, UMLVisualIDRegistry.getType(ControlFlowInterruptibleIconEditPart.VISUAL_ID));
- if (node instanceof Node) {
- return (Node) node;
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366026 - [ActivityDiagram] Refactoring in order to try respect Generation Gap Pattern + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil; +import org.eclipse.gmf.runtime.notation.Node; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowInterruptibleIconEditPart; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLVisualIDRegistry; + +/** + * Customization to implement InterruptibleEdge + * + * @author arthur daussy + * + */ +public class CustomControlFlowEditPart extends ControlFlowEditPart implements InterruptibleEdge { + + public CustomControlFlowEditPart(View view) { + super(view); + } + + /** + * {@inheritDoc InterruptibleEdge} + */ + @Override + public String getInterruptibleEdgeIconVisualID() { + return ControlFlowInterruptibleIconEditPart.VISUAL_ID; + } + + /** + * {@inheritDoc InterruptibleEdge} + */ + @Override + public Node getInterrutibleEgdeIcon() { + Object view = getModel(); + if (view instanceof View) { + View node = ViewUtil.getChildBySemanticHint((View) view, UMLVisualIDRegistry.getType(ControlFlowInterruptibleIconEditPart.VISUAL_ID)); + if (node instanceof Node) { + return (Node) node; + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowInterruptibleIconEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowInterruptibleIconEditPart.java index c91b3856e60..cd34dd0d9f4 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowInterruptibleIconEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowInterruptibleIconEditPart.java @@ -1,80 +1,80 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowInterruptibleIconEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.figures.InterruptibleEdgeExternalIconFigure;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * Customization of {@link ControlFlowInterruptibleIconEditPart} in order to make it able to handle specific Label Helper
- *
- * @author arthur daussy
- *
- */
-public class CustomControlFlowInterruptibleIconEditPart extends ControlFlowInterruptibleIconEditPart {
-
- public CustomControlFlowInterruptibleIconEditPart(View view) {
- super(view);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected String getLabelTextHelper(IFigure figure) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- return "";
- }
- return super.getLabelTextHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected void setLabelTextHelper(IFigure figure, String text) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- // Label can not be set on this figure
- return;
- }
- super.getLabelTextHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected Image getLabelIconHelper(IFigure figure) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- return ((InterruptibleEdgeExternalIconFigure) figure).getImage();
- }
- return super.getLabelIconHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected void setLabelIconHelper(IFigure figure, Image icon) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- // Icon can not be set on this figure
- return;
- }
- super.setLabelIconHelper(figure, icon);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowInterruptibleIconEditPart; +import org.eclipse.papyrus.uml.diagram.activity.figures.InterruptibleEdgeExternalIconFigure; +import org.eclipse.swt.graphics.Image; + +/** + * Customization of {@link ControlFlowInterruptibleIconEditPart} in order to make it able to handle specific Label Helper + * + * @author arthur daussy + * + */ +public class CustomControlFlowInterruptibleIconEditPart extends ControlFlowInterruptibleIconEditPart { + + public CustomControlFlowInterruptibleIconEditPart(View view) { + super(view); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected String getLabelTextHelper(IFigure figure) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + return ""; + } + return super.getLabelTextHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected void setLabelTextHelper(IFigure figure, String text) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + // Label can not be set on this figure + return; + } + super.getLabelTextHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected Image getLabelIconHelper(IFigure figure) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + return ((InterruptibleEdgeExternalIconFigure) figure).getImage(); + } + return super.getLabelIconHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected void setLabelIconHelper(IFigure figure, Image icon) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + // Icon can not be set on this figure + return; + } + super.setLabelIconHelper(figure, icon); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowNameEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowNameEditPart.java index 360cf81e2e8..a3b31ef26de 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowNameEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomControlFlowNameEditPart.java @@ -1,135 +1,135 @@ -/*****************************************************************************
- * Copyright (c) 2015 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.gef.Request;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowNameEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants;
-
-
-public class CustomControlFlowNameEditPart extends ControlFlowNameEditPart {
-
- private final IPreferenceStore preferenceStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
-
- private IPropertyChangeListener preferenceListener;
-
- public CustomControlFlowNameEditPart(View view) {
- super(view);
- // a preference listener to enable/disable the label
- preferenceListener = new IPropertyChangeListener() {
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL.equals(event.getProperty())) {
- refreshLabel();
- }
- }
- };
- }
-
- @Override
- public void activate() {
- super.activate();
- preferenceStore.addPropertyChangeListener(preferenceListener);
- }
-
- @Override
- public void deactivate() {
- preferenceStore.removePropertyChangeListener(preferenceListener);
- super.deactivate();
- }
-
- /**
- * consult preference store before displaying label
- */
- @Override
- protected String getLabelText() {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (showName) {
- return super.getLabelText();
- }
- return ""; //$NON-NLS-1$
- }
-
- /**
- * consult preference store before displaying label
- */
- @Override
- public String getEditText() {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (!showName) {
- return ""; //$NON-NLS-1$
- }
- return super.getEditText();
- }
-
- /**
- * consult preference store before displaying label
- */
- @Override
- protected void performDirectEdit() {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (showName) {
- super.performDirectEdit();
- }
- }
-
- /**
- * consult preference store before displaying label
- */
- @Override
- protected void performDirectEdit(Point eventLocation) {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (showName) {
- super.performDirectEdit(eventLocation);
- }
- }
-
- /**
- * consult preference store before displaying label
- */
- @Override
- protected void performDirectEdit(char initialCharacter) {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (showName) {
- super.performDirectEdit(initialCharacter);
- } else {
- performDirectEdit();
- }
- }
-
- /**
- * consult preference store before displaying label
- */
- @Override
- protected void performDirectEditRequest(Request request) {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (!showName) {
- return;
- }
- super.performDirectEditRequest(request);
- }
-}
+/***************************************************************************** + * Copyright (c) 2015 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.gef.Request; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowNameEditPart; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants; + + +public class CustomControlFlowNameEditPart extends ControlFlowNameEditPart { + + private final IPreferenceStore preferenceStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + + private IPropertyChangeListener preferenceListener; + + public CustomControlFlowNameEditPart(View view) { + super(view); + // a preference listener to enable/disable the label + preferenceListener = new IPropertyChangeListener() { + + @Override + public void propertyChange(PropertyChangeEvent event) { + if (IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL.equals(event.getProperty())) { + refreshLabel(); + } + } + }; + } + + @Override + public void activate() { + super.activate(); + preferenceStore.addPropertyChangeListener(preferenceListener); + } + + @Override + public void deactivate() { + preferenceStore.removePropertyChangeListener(preferenceListener); + super.deactivate(); + } + + /** + * consult preference store before displaying label + */ + @Override + protected String getLabelText() { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (showName) { + return super.getLabelText(); + } + return ""; //$NON-NLS-1$ + } + + /** + * consult preference store before displaying label + */ + @Override + public String getEditText() { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (!showName) { + return ""; //$NON-NLS-1$ + } + return super.getEditText(); + } + + /** + * consult preference store before displaying label + */ + @Override + protected void performDirectEdit() { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (showName) { + super.performDirectEdit(); + } + } + + /** + * consult preference store before displaying label + */ + @Override + protected void performDirectEdit(Point eventLocation) { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (showName) { + super.performDirectEdit(eventLocation); + } + } + + /** + * consult preference store before displaying label + */ + @Override + protected void performDirectEdit(char initialCharacter) { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (showName) { + super.performDirectEdit(initialCharacter); + } else { + performDirectEdit(); + } + } + + /** + * consult preference store before displaying label + */ + @Override + protected void performDirectEditRequest(Request request) { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (!showName) { + return; + } + super.performDirectEditRequest(request); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomExceptionHandlerIconEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomExceptionHandlerIconEditPart.java index c19aafd64e8..9fd6fbf1a7c 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomExceptionHandlerIconEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomExceptionHandlerIconEditPart.java @@ -1,80 +1,80 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 367279 - [Activity Diagram] Activity Diagram should be able to handle correctly Exception Handler element
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ExceptionHandlerIconEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.figures.InterruptibleEdgeExternalIconFigure;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * Customization of {@link ExceptionHandlerIconEditPart} in order to make it able to handle Specific Label Helper
- *
- * @author arthur daussy
- *
- */
-public class CustomExceptionHandlerIconEditPart extends ExceptionHandlerIconEditPart {
-
- public CustomExceptionHandlerIconEditPart(View view) {
- super(view);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected String getLabelTextHelper(IFigure figure) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- return "";
- }
- return super.getLabelTextHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected void setLabelTextHelper(IFigure figure, String text) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- // Label can not be set on this figure
- return;
- }
- super.getLabelTextHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected Image getLabelIconHelper(IFigure figure) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- return ((InterruptibleEdgeExternalIconFigure) figure).getImage();
- }
- return super.getLabelIconHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected void setLabelIconHelper(IFigure figure, Image icon) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- // Icon can not be set on this figure
- return;
- }
- super.setLabelIconHelper(figure, icon);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 367279 - [Activity Diagram] Activity Diagram should be able to handle correctly Exception Handler element + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ExceptionHandlerIconEditPart; +import org.eclipse.papyrus.uml.diagram.activity.figures.InterruptibleEdgeExternalIconFigure; +import org.eclipse.swt.graphics.Image; + +/** + * Customization of {@link ExceptionHandlerIconEditPart} in order to make it able to handle Specific Label Helper + * + * @author arthur daussy + * + */ +public class CustomExceptionHandlerIconEditPart extends ExceptionHandlerIconEditPart { + + public CustomExceptionHandlerIconEditPart(View view) { + super(view); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected String getLabelTextHelper(IFigure figure) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + return ""; + } + return super.getLabelTextHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected void setLabelTextHelper(IFigure figure, String text) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + // Label can not be set on this figure + return; + } + super.getLabelTextHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected Image getLabelIconHelper(IFigure figure) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + return ((InterruptibleEdgeExternalIconFigure) figure).getImage(); + } + return super.getLabelIconHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected void setLabelIconHelper(IFigure figure, Image icon) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + // Icon can not be set on this figure + return; + } + super.setLabelIconHelper(figure, icon); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowEditPart.java index 96e5d7e14ac..ca78e8ab3fd 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowEditPart.java @@ -1,59 +1,59 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366026 - [ActivityDiagram] Refactoring in order to try respect Generation Gap Pattern
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
-import org.eclipse.gmf.runtime.notation.Node;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowInterruptibleIconEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLVisualIDRegistry;
-
-/**
- * Customization to implement InterruptibleEdge
- *
- * @author arthur daussy
- *
- */
-public class CustomObjectFlowEditPart extends ObjectFlowEditPart implements InterruptibleEdge {
-
- public CustomObjectFlowEditPart(View view) {
- super(view);
- }
-
- /**
- * {@inheritDoc InterruptibleEdge}
- */
- @Override
- public String getInterruptibleEdgeIconVisualID() {
- return ObjectFlowInterruptibleIconEditPart.VISUAL_ID;
- }
-
- /**
- * {@inheritDoc InterruptibleEdge}
- */
- @Override
- public Node getInterrutibleEgdeIcon() {
- Object view = getModel();
- if (view instanceof View) {
- View node = ViewUtil.getChildBySemanticHint((View) view, UMLVisualIDRegistry.getType(ObjectFlowInterruptibleIconEditPart.VISUAL_ID));
- if (node instanceof Node) {
- return (Node) node;
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366026 - [ActivityDiagram] Refactoring in order to try respect Generation Gap Pattern + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil; +import org.eclipse.gmf.runtime.notation.Node; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowInterruptibleIconEditPart; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLVisualIDRegistry; + +/** + * Customization to implement InterruptibleEdge + * + * @author arthur daussy + * + */ +public class CustomObjectFlowEditPart extends ObjectFlowEditPart implements InterruptibleEdge { + + public CustomObjectFlowEditPart(View view) { + super(view); + } + + /** + * {@inheritDoc InterruptibleEdge} + */ + @Override + public String getInterruptibleEdgeIconVisualID() { + return ObjectFlowInterruptibleIconEditPart.VISUAL_ID; + } + + /** + * {@inheritDoc InterruptibleEdge} + */ + @Override + public Node getInterrutibleEgdeIcon() { + Object view = getModel(); + if (view instanceof View) { + View node = ViewUtil.getChildBySemanticHint((View) view, UMLVisualIDRegistry.getType(ObjectFlowInterruptibleIconEditPart.VISUAL_ID)); + if (node instanceof Node) { + return (Node) node; + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowInterruptibleIconEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowInterruptibleIconEditPart.java index 7e50c431546..f602c2a71a7 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowInterruptibleIconEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowInterruptibleIconEditPart.java @@ -1,81 +1,81 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowInterruptibleIconEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.figures.InterruptibleEdgeExternalIconFigure;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * Customization to be able to handle specific image label edit part.
- * In this case the label is an InterruptibleEdgeExternalIconFigure which specific handle
- *
- * @author arthur daussy
- *
- */
-public class CustomObjectFlowInterruptibleIconEditPart extends ObjectFlowInterruptibleIconEditPart {
-
- public CustomObjectFlowInterruptibleIconEditPart(View view) {
- super(view);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected String getLabelTextHelper(IFigure figure) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- return "";
- }
- return super.getLabelTextHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected void setLabelTextHelper(IFigure figure, String text) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- // Label can not be set on this figure
- return;
- }
- super.getLabelTextHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected Image getLabelIconHelper(IFigure figure) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- return ((InterruptibleEdgeExternalIconFigure) figure).getImage();
- }
- return super.getLabelIconHelper(figure);
- }
-
- /**
- * Make it handle with {@link InterruptibleEdgeExternalIconFigure}
- */
- @Override
- protected void setLabelIconHelper(IFigure figure, Image icon) {
- if (figure instanceof InterruptibleEdgeExternalIconFigure) {
- // Icon can not be set on this figure
- return;
- }
- super.setLabelIconHelper(figure, icon);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowInterruptibleIconEditPart; +import org.eclipse.papyrus.uml.diagram.activity.figures.InterruptibleEdgeExternalIconFigure; +import org.eclipse.swt.graphics.Image; + +/** + * Customization to be able to handle specific image label edit part. + * In this case the label is an InterruptibleEdgeExternalIconFigure which specific handle + * + * @author arthur daussy + * + */ +public class CustomObjectFlowInterruptibleIconEditPart extends ObjectFlowInterruptibleIconEditPart { + + public CustomObjectFlowInterruptibleIconEditPart(View view) { + super(view); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected String getLabelTextHelper(IFigure figure) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + return ""; + } + return super.getLabelTextHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected void setLabelTextHelper(IFigure figure, String text) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + // Label can not be set on this figure + return; + } + super.getLabelTextHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected Image getLabelIconHelper(IFigure figure) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + return ((InterruptibleEdgeExternalIconFigure) figure).getImage(); + } + return super.getLabelIconHelper(figure); + } + + /** + * Make it handle with {@link InterruptibleEdgeExternalIconFigure} + */ + @Override + protected void setLabelIconHelper(IFigure figure, Image icon) { + if (figure instanceof InterruptibleEdgeExternalIconFigure) { + // Icon can not be set on this figure + return; + } + super.setLabelIconHelper(figure, icon); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowNameEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowNameEditPart.java index fe31186e1e9..91057388670 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowNameEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowNameEditPart.java @@ -1,136 +1,136 @@ -/*****************************************************************************
- * Copyright (c) 2015 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.gef.Request;
-import org.eclipse.gmf.runtime.diagram.ui.tools.TextDirectEditManager;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowNameEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants;
-
-
-public class CustomObjectFlowNameEditPart extends ObjectFlowNameEditPart {
-
- private IPropertyChangeListener preferenceListener;
-
- private final IPreferenceStore preferenceStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
-
- /**
- * add preference listener to enable/disable the label
- */
- public CustomObjectFlowNameEditPart(View view) {
- super(view);
- // a preference listener to enable/disable the label
- preferenceListener = new IPropertyChangeListener() {
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL.equals(event.getProperty())) {
- refreshLabel();
- }
- }
- };
- }
-
- @Override
- public void activate() {
- super.activate();
- preferenceStore.addPropertyChangeListener(preferenceListener);
- }
-
- @Override
- public void deactivate() {
- preferenceStore.removePropertyChangeListener(preferenceListener);
- super.deactivate();
- }
-
- /**
- * consult preference store before displaying label
- */
- protected void performDirectEdit() {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (showName) {
- getManager().show();
- }
- }
-
- /**
- * consult preference store before displaying label
- */
- protected void performDirectEdit(Point eventLocation) {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (showName) {
- ((TextDirectEditManager) getManager()).show(eventLocation.getSWTPoint());
- }
- }
-
- /**
- * consult preference store before displaying label
- */
- protected void performDirectEdit(char initialCharacter) {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (showName) {
- super.performDirectEdit(initialCharacter);
- } else {
- performDirectEdit();
- }
- }
-
- /**
- * consult preference store before displaying label
- */
- @Override
- protected void performDirectEditRequest(Request request) {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (!showName) {
- return;
- }
- super.performDirectEditRequest(request);
- }
-
- /**
- * consult preference store before displaying label
- */
- @Override
- public String getEditText() {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (!showName) {
- return ""; //$NON-NLS-1$
- }
- return super.getEditText();
- }
-
- /**
- * consult preference store before displaying label
- */
- protected String getLabelText() {
- // consult preference store before displaying label
- boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL);
- if (showName) {
- return super.getLabelText();
- } else {
- return ""; //$NON-NLS-1$
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2015 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.gef.Request; +import org.eclipse.gmf.runtime.diagram.ui.tools.TextDirectEditManager; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.util.IPropertyChangeListener; +import org.eclipse.jface.util.PropertyChangeEvent; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowNameEditPart; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants; + + +public class CustomObjectFlowNameEditPart extends ObjectFlowNameEditPart { + + private IPropertyChangeListener preferenceListener; + + private final IPreferenceStore preferenceStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + + /** + * add preference listener to enable/disable the label + */ + public CustomObjectFlowNameEditPart(View view) { + super(view); + // a preference listener to enable/disable the label + preferenceListener = new IPropertyChangeListener() { + + @Override + public void propertyChange(PropertyChangeEvent event) { + if (IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL.equals(event.getProperty())) { + refreshLabel(); + } + } + }; + } + + @Override + public void activate() { + super.activate(); + preferenceStore.addPropertyChangeListener(preferenceListener); + } + + @Override + public void deactivate() { + preferenceStore.removePropertyChangeListener(preferenceListener); + super.deactivate(); + } + + /** + * consult preference store before displaying label + */ + protected void performDirectEdit() { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (showName) { + getManager().show(); + } + } + + /** + * consult preference store before displaying label + */ + protected void performDirectEdit(Point eventLocation) { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (showName) { + ((TextDirectEditManager) getManager()).show(eventLocation.getSWTPoint()); + } + } + + /** + * consult preference store before displaying label + */ + protected void performDirectEdit(char initialCharacter) { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (showName) { + super.performDirectEdit(initialCharacter); + } else { + performDirectEdit(); + } + } + + /** + * consult preference store before displaying label + */ + @Override + protected void performDirectEditRequest(Request request) { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (!showName) { + return; + } + super.performDirectEditRequest(request); + } + + /** + * consult preference store before displaying label + */ + @Override + public String getEditText() { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (!showName) { + return ""; //$NON-NLS-1$ + } + return super.getEditText(); + } + + /** + * consult preference store before displaying label + */ + protected String getLabelText() { + // consult preference store before displaying label + boolean showName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL); + if (showName) { + return super.getLabelText(); + } else { + return ""; //$NON-NLS-1$ + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowSelectionEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowSelectionEditPart.java index e13378b792b..8b380891585 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowSelectionEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowSelectionEditPart.java @@ -1,161 +1,161 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366026 - [ActivityDaigram] Refactoring in order to try respect Generation Gap Pattern
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.tools.DirectEditManager;
-import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramColorRegistry;
-import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
-import org.eclipse.gmf.runtime.notation.NotationPackage;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.infra.gmfdiag.tooling.runtime.directedit.locator.TextCellEditorLocator;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowSelectionEditPart;
-import org.eclipse.papyrus.uml.diagram.common.directedit.MultilineLabelDirectEditManager;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.uml2.uml.Behavior;
-import org.eclipse.uml2.uml.ObjectFlow;
-
-public class CustomObjectFlowSelectionEditPart extends ObjectFlowSelectionEditPart {
-
- private DirectEditManager manager;
-
- public CustomObjectFlowSelectionEditPart(View view) {
- super(view);
- }
-
- /**
- * handle LinkAndCornerBentWithTextFigure
- */
- @Override
- protected String getLabelTextHelper(IFigure figure) {
- if (figure instanceof LinkAndCornerBentWithTextFigure) {
- return ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().getText();
- }
- return super.getLabelTextHelper(figure);
- }
-
- /**
- * handle CustomLinkAndCornerBentWithTextFigure
- */
- @Override
- protected void setLabelTextHelper(IFigure figure, String text) {
- if (figure instanceof LinkAndCornerBentWithTextFigure) {
- ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().setText(text);
- } else {
- super.setLabelTextHelper(figure, text);
- }
- }
-
- /**
- * handle CustomLinkAndCornerBentWithTextFigure
- */
- @Override
- protected Image getLabelIconHelper(IFigure figure) {
- if (figure instanceof LinkAndCornerBentWithTextFigure) {
- return ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().getIcon();
- }
- return super.getLabelIconHelper(figure);
- }
-
- /**
- * handle CustomLinkAndCornerBentWithTextFigure
- */
- @Override
- protected void setLabelIconHelper(IFigure figure, Image icon) {
- if (figure instanceof LinkAndCornerBentWithTextFigure) {
- ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().setIcon(icon);
- } else {
- super.setLabelIconHelper(figure, icon);
- }
- }
-
- /**
- * sets the visibility of this edit part
- *
- * @param vis
- * the new value of the visibility
- */
- @Override
- protected void setVisibility(boolean vis) {
- EObject element = resolveSemanticElement();
- if (element instanceof ObjectFlow) {
- Behavior selection = ((ObjectFlow) element).getSelection();
- if (selection == null) {
- vis = false;
- }
- }
- super.setVisibility(vis);
- }
-
- /**
- * refresh the visibility in case the selection assignment
- * changed
- */
- @Override
- protected void handleNotificationEvent(Notification event) {
- Object feature = event.getFeature();
- if (NotationPackage.eINSTANCE.getFontStyle_FontColor().equals(feature)) {
- Integer c = (Integer) event.getNewValue();
- setFontColor(DiagramColorRegistry.getInstance().getColor(c));
- } else if (NotationPackage.eINSTANCE.getFontStyle_Underline().equals(feature)) {
- refreshUnderline();
- } else if (NotationPackage.eINSTANCE.getFontStyle_StrikeThrough().equals(feature)) {
- refreshStrikeThrough();
- } else if (NotationPackage.eINSTANCE.getFontStyle_FontHeight().equals(feature) || NotationPackage.eINSTANCE.getFontStyle_FontName().equals(feature) || NotationPackage.eINSTANCE.getFontStyle_Bold().equals(feature)
- || NotationPackage.eINSTANCE.getFontStyle_Italic().equals(feature)) {
- refreshFont();
- } else {
- if (getParser() != null && getParser().isAffectingEvent(event, getParserOptions().intValue())) {
- refreshLabel();
- }
- if (getParser() instanceof ISemanticParser) {
- ISemanticParser modelParser = (ISemanticParser) getParser();
- if (modelParser.areSemanticElementsAffected(null, event)) {
- removeSemanticListeners();
- if (resolveSemanticElement() != null) {
- addSemanticListeners();
- }
- refreshLabel();
- // refresh the visibility in case the selection assignment
- // changed
- refreshVisibility();
- }
- }
- }
- super.handleNotificationEvent(event);
- }
-
- /**
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowSelectionEditPart#getManager()
- *
- * Use custom locator
- */
- protected DirectEditManager getManager() {
- if (manager == null) {
- setManager(new MultilineLabelDirectEditManager(this,
- MultilineLabelDirectEditManager.getTextCellEditorClass(this),
- new TextCellEditorLocator(((ObjectFlowSelectionEditPart.LinkAndCornerBentWithTextFigure) this.getFigure()).getCornerBentContent())
- ));
- }
- return manager;
- }
-
- protected void setManager(DirectEditManager manager) {
- this.manager = manager;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366026 - [ActivityDaigram] Refactoring in order to try respect Generation Gap Pattern + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.tools.DirectEditManager; +import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramColorRegistry; +import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser; +import org.eclipse.gmf.runtime.notation.NotationPackage; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.infra.gmfdiag.tooling.runtime.directedit.locator.TextCellEditorLocator; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowSelectionEditPart; +import org.eclipse.papyrus.uml.diagram.common.directedit.MultilineLabelDirectEditManager; +import org.eclipse.swt.graphics.Image; +import org.eclipse.uml2.uml.Behavior; +import org.eclipse.uml2.uml.ObjectFlow; + +public class CustomObjectFlowSelectionEditPart extends ObjectFlowSelectionEditPart { + + private DirectEditManager manager; + + public CustomObjectFlowSelectionEditPart(View view) { + super(view); + } + + /** + * handle LinkAndCornerBentWithTextFigure + */ + @Override + protected String getLabelTextHelper(IFigure figure) { + if (figure instanceof LinkAndCornerBentWithTextFigure) { + return ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().getText(); + } + return super.getLabelTextHelper(figure); + } + + /** + * handle CustomLinkAndCornerBentWithTextFigure + */ + @Override + protected void setLabelTextHelper(IFigure figure, String text) { + if (figure instanceof LinkAndCornerBentWithTextFigure) { + ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().setText(text); + } else { + super.setLabelTextHelper(figure, text); + } + } + + /** + * handle CustomLinkAndCornerBentWithTextFigure + */ + @Override + protected Image getLabelIconHelper(IFigure figure) { + if (figure instanceof LinkAndCornerBentWithTextFigure) { + return ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().getIcon(); + } + return super.getLabelIconHelper(figure); + } + + /** + * handle CustomLinkAndCornerBentWithTextFigure + */ + @Override + protected void setLabelIconHelper(IFigure figure, Image icon) { + if (figure instanceof LinkAndCornerBentWithTextFigure) { + ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().setIcon(icon); + } else { + super.setLabelIconHelper(figure, icon); + } + } + + /** + * sets the visibility of this edit part + * + * @param vis + * the new value of the visibility + */ + @Override + protected void setVisibility(boolean vis) { + EObject element = resolveSemanticElement(); + if (element instanceof ObjectFlow) { + Behavior selection = ((ObjectFlow) element).getSelection(); + if (selection == null) { + vis = false; + } + } + super.setVisibility(vis); + } + + /** + * refresh the visibility in case the selection assignment + * changed + */ + @Override + protected void handleNotificationEvent(Notification event) { + Object feature = event.getFeature(); + if (NotationPackage.eINSTANCE.getFontStyle_FontColor().equals(feature)) { + Integer c = (Integer) event.getNewValue(); + setFontColor(DiagramColorRegistry.getInstance().getColor(c)); + } else if (NotationPackage.eINSTANCE.getFontStyle_Underline().equals(feature)) { + refreshUnderline(); + } else if (NotationPackage.eINSTANCE.getFontStyle_StrikeThrough().equals(feature)) { + refreshStrikeThrough(); + } else if (NotationPackage.eINSTANCE.getFontStyle_FontHeight().equals(feature) || NotationPackage.eINSTANCE.getFontStyle_FontName().equals(feature) || NotationPackage.eINSTANCE.getFontStyle_Bold().equals(feature) + || NotationPackage.eINSTANCE.getFontStyle_Italic().equals(feature)) { + refreshFont(); + } else { + if (getParser() != null && getParser().isAffectingEvent(event, getParserOptions().intValue())) { + refreshLabel(); + } + if (getParser() instanceof ISemanticParser) { + ISemanticParser modelParser = (ISemanticParser) getParser(); + if (modelParser.areSemanticElementsAffected(null, event)) { + removeSemanticListeners(); + if (resolveSemanticElement() != null) { + addSemanticListeners(); + } + refreshLabel(); + // refresh the visibility in case the selection assignment + // changed + refreshVisibility(); + } + } + } + super.handleNotificationEvent(event); + } + + /** + * + * @see org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowSelectionEditPart#getManager() + * + * Use custom locator + */ + protected DirectEditManager getManager() { + if (manager == null) { + setManager(new MultilineLabelDirectEditManager(this, + MultilineLabelDirectEditManager.getTextCellEditorClass(this), + new TextCellEditorLocator(((ObjectFlowSelectionEditPart.LinkAndCornerBentWithTextFigure) this.getFigure()).getCornerBentContent()) + )); + } + return manager; + } + + protected void setManager(DirectEditManager manager) { + this.manager = manager; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowTransformationEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowTransformationEditPart.java index 652fb701dbf..6e2158bc721 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowTransformationEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/CustomObjectFlowTransformationEditPart.java @@ -1,155 +1,155 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366026 - [ActivityDiagram] Refactoring in order to try respect Generation Gap Pattern
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.tools.DirectEditManager;
-import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramColorRegistry;
-import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
-import org.eclipse.gmf.runtime.notation.NotationPackage;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.infra.gmfdiag.tooling.runtime.directedit.locator.TextCellEditorLocator;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowTransformationEditPart;
-import org.eclipse.papyrus.uml.diagram.common.directedit.MultilineLabelDirectEditManager;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.uml2.uml.Behavior;
-import org.eclipse.uml2.uml.ObjectFlow;
-
-public class CustomObjectFlowTransformationEditPart extends ObjectFlowTransformationEditPart {
-
- private DirectEditManager manager;
-
- public CustomObjectFlowTransformationEditPart(View view) {
- super(view);
- }
-
- /**
- * handle LinkAndCornerBentWithTextFigure
- */
- @Override
- protected String getLabelTextHelper(IFigure figure) {
- if (figure instanceof LinkAndCornerBentWithTextFigure) {
- return ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().getText();
- }
- return super.getLabelTextHelper(figure);
- }
-
- /**
- * handle CustomLinkAndCornerBentWithTextFigure
- */
- @Override
- protected void setLabelTextHelper(IFigure figure, String text) {
- if (figure instanceof LinkAndCornerBentWithTextFigure) {
- ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().setText(text);
- } else {
- super.setLabelTextHelper(figure, text);
- }
- }
-
- /**
- * handle CustomLinkAndCornerBentWithTextFigure
- */
- @Override
- protected Image getLabelIconHelper(IFigure figure) {
- if (figure instanceof LinkAndCornerBentWithTextFigure) {
- return ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().getIcon();
- }
- return getLabelIconHelper(figure);
- }
-
- /**
- * handle CustomLinkAndCornerBentWithTextFigure
- */
- @Override
- protected void setLabelIconHelper(IFigure figure, Image icon) {
- if (figure instanceof LinkAndCornerBentWithTextFigure) {
- ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().setIcon(icon);
- } else {
- super.setLabelIconHelper(figure, icon);
- }
- }
-
- /**
- * sets the visibility of this edit part
- *
- * @param vis
- * the new value of the visibility
- */
- @Override
- protected void setVisibility(boolean vis) {
- EObject element = resolveSemanticElement();
- if (element instanceof ObjectFlow) {
- Behavior transformation = ((ObjectFlow) element).getTransformation();
- if (transformation == null) {
- vis = false;
- }
- }
- super.setVisibility(vis);
- }
-
- /**
- * Refresh the visibility in case the transformation
- * assignment changed
- */
- @Override
- protected void handleNotificationEvent(Notification event) {
- Object feature = event.getFeature();
- if (NotationPackage.eINSTANCE.getFontStyle_FontColor().equals(feature)) {
- Integer c = (Integer) event.getNewValue();
- setFontColor(DiagramColorRegistry.getInstance().getColor(c));
- } else if (NotationPackage.eINSTANCE.getFontStyle_Underline().equals(feature)) {
- refreshUnderline();
- } else if (NotationPackage.eINSTANCE.getFontStyle_StrikeThrough().equals(feature)) {
- refreshStrikeThrough();
- } else if (NotationPackage.eINSTANCE.getFontStyle_FontHeight().equals(feature) || NotationPackage.eINSTANCE.getFontStyle_FontName().equals(feature) || NotationPackage.eINSTANCE.getFontStyle_Bold().equals(feature)
- || NotationPackage.eINSTANCE.getFontStyle_Italic().equals(feature)) {
- refreshFont();
- } else {
- if (getParser() != null && getParser().isAffectingEvent(event, getParserOptions().intValue())) {
- refreshLabel();
- }
- if (getParser() instanceof ISemanticParser) {
- ISemanticParser modelParser = (ISemanticParser) getParser();
- if (modelParser.areSemanticElementsAffected(null, event)) {
- removeSemanticListeners();
- if (resolveSemanticElement() != null) {
- addSemanticListeners();
- }
- refreshLabel();
- // refresh the visibility in case the transformation
- // assignment changed
- refreshVisibility();
- }
- }
- }
- super.handleNotificationEvent(event);
- }
-
- protected DirectEditManager getManager() {
- if (manager == null) {
- setManager(new MultilineLabelDirectEditManager(this,
- MultilineLabelDirectEditManager.getTextCellEditorClass(this),
- new TextCellEditorLocator(((ObjectFlowTransformationEditPart.LinkAndCornerBentWithTextFigure) this.getFigure()).getCornerBentContent())
- ));
- }
- return manager;
- }
-
- protected void setManager(DirectEditManager manager) {
- this.manager = manager;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366026 - [ActivityDiagram] Refactoring in order to try respect Generation Gap Pattern + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.tools.DirectEditManager; +import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramColorRegistry; +import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser; +import org.eclipse.gmf.runtime.notation.NotationPackage; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.infra.gmfdiag.tooling.runtime.directedit.locator.TextCellEditorLocator; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowTransformationEditPart; +import org.eclipse.papyrus.uml.diagram.common.directedit.MultilineLabelDirectEditManager; +import org.eclipse.swt.graphics.Image; +import org.eclipse.uml2.uml.Behavior; +import org.eclipse.uml2.uml.ObjectFlow; + +public class CustomObjectFlowTransformationEditPart extends ObjectFlowTransformationEditPart { + + private DirectEditManager manager; + + public CustomObjectFlowTransformationEditPart(View view) { + super(view); + } + + /** + * handle LinkAndCornerBentWithTextFigure + */ + @Override + protected String getLabelTextHelper(IFigure figure) { + if (figure instanceof LinkAndCornerBentWithTextFigure) { + return ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().getText(); + } + return super.getLabelTextHelper(figure); + } + + /** + * handle CustomLinkAndCornerBentWithTextFigure + */ + @Override + protected void setLabelTextHelper(IFigure figure, String text) { + if (figure instanceof LinkAndCornerBentWithTextFigure) { + ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().setText(text); + } else { + super.setLabelTextHelper(figure, text); + } + } + + /** + * handle CustomLinkAndCornerBentWithTextFigure + */ + @Override + protected Image getLabelIconHelper(IFigure figure) { + if (figure instanceof LinkAndCornerBentWithTextFigure) { + return ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().getIcon(); + } + return getLabelIconHelper(figure); + } + + /** + * handle CustomLinkAndCornerBentWithTextFigure + */ + @Override + protected void setLabelIconHelper(IFigure figure, Image icon) { + if (figure instanceof LinkAndCornerBentWithTextFigure) { + ((LinkAndCornerBentWithTextFigure) figure).getCornerBentContent().setIcon(icon); + } else { + super.setLabelIconHelper(figure, icon); + } + } + + /** + * sets the visibility of this edit part + * + * @param vis + * the new value of the visibility + */ + @Override + protected void setVisibility(boolean vis) { + EObject element = resolveSemanticElement(); + if (element instanceof ObjectFlow) { + Behavior transformation = ((ObjectFlow) element).getTransformation(); + if (transformation == null) { + vis = false; + } + } + super.setVisibility(vis); + } + + /** + * Refresh the visibility in case the transformation + * assignment changed + */ + @Override + protected void handleNotificationEvent(Notification event) { + Object feature = event.getFeature(); + if (NotationPackage.eINSTANCE.getFontStyle_FontColor().equals(feature)) { + Integer c = (Integer) event.getNewValue(); + setFontColor(DiagramColorRegistry.getInstance().getColor(c)); + } else if (NotationPackage.eINSTANCE.getFontStyle_Underline().equals(feature)) { + refreshUnderline(); + } else if (NotationPackage.eINSTANCE.getFontStyle_StrikeThrough().equals(feature)) { + refreshStrikeThrough(); + } else if (NotationPackage.eINSTANCE.getFontStyle_FontHeight().equals(feature) || NotationPackage.eINSTANCE.getFontStyle_FontName().equals(feature) || NotationPackage.eINSTANCE.getFontStyle_Bold().equals(feature) + || NotationPackage.eINSTANCE.getFontStyle_Italic().equals(feature)) { + refreshFont(); + } else { + if (getParser() != null && getParser().isAffectingEvent(event, getParserOptions().intValue())) { + refreshLabel(); + } + if (getParser() instanceof ISemanticParser) { + ISemanticParser modelParser = (ISemanticParser) getParser(); + if (modelParser.areSemanticElementsAffected(null, event)) { + removeSemanticListeners(); + if (resolveSemanticElement() != null) { + addSemanticListeners(); + } + refreshLabel(); + // refresh the visibility in case the transformation + // assignment changed + refreshVisibility(); + } + } + } + super.handleNotificationEvent(event); + } + + protected DirectEditManager getManager() { + if (manager == null) { + setManager(new MultilineLabelDirectEditManager(this, + MultilineLabelDirectEditManager.getTextCellEditorClass(this), + new TextCellEditorLocator(((ObjectFlowTransformationEditPart.LinkAndCornerBentWithTextFigure) this.getFigure()).getCornerBentContent()) + )); + } + return manager; + } + + protected void setManager(DirectEditManager manager) { + this.manager = manager; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/NoBorderListCompartmentEditPart.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/NoBorderListCompartmentEditPart.java index c1835a85cf2..e034b9cebcd 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/NoBorderListCompartmentEditPart.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/NoBorderListCompartmentEditPart.java @@ -1,32 +1,32 @@ -/*****************************************************************************
- * Copyright (c) 2015 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.part;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure;
-import org.eclipse.gmf.runtime.notation.View;
-
-public abstract class NoBorderListCompartmentEditPart extends org.eclipse.gmf.runtime.diagram.ui.editparts.ListCompartmentEditPart {
-
- public NoBorderListCompartmentEditPart(View view) {
- super(view);
- }
-
- @Override
- public IFigure createFigure() {
- ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure();
- result.setBorder(null);
- return result;
- }
+/***************************************************************************** + * Copyright (c) 2015 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.part; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure; +import org.eclipse.gmf.runtime.notation.View; + +public abstract class NoBorderListCompartmentEditPart extends org.eclipse.gmf.runtime.diagram.ui.editparts.ListCompartmentEditPart { + + public NoBorderListCompartmentEditPart(View view) { + super(view); + } + + @Override + public IFigure createFigure() { + ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure(); + result.setBorder(null); + return result; + } }
\ No newline at end of file diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/interfaces/InterruptibleEdge.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/interfaces/InterruptibleEdge.java index ab94668486d..db358660425 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/interfaces/InterruptibleEdge.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/part/interfaces/InterruptibleEdge.java @@ -1,38 +1,38 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces;
-
-import org.eclipse.gmf.runtime.notation.Node;
-
-/**
- * Interfaces that need to be implemented by all activity edges
- *
- * @author arthur daussy
- *
- */
-public interface InterruptibleEdge {
-
- /**
- * @return return the visual ID of the edit which should hold the InterruptibleEdge icon
- */
- public String getInterruptibleEdgeIconVisualID();
-
- /**
- * Get the Interruptible edge icon or null if not set
- *
- * @return
- */
- public Node getInterrutibleEgdeIcon();
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces; + +import org.eclipse.gmf.runtime.notation.Node; + +/** + * Interfaces that need to be implemented by all activity edges + * + * @author arthur daussy + * + */ +public interface InterruptibleEdge { + + /** + * @return return the visual ID of the edit which should hold the InterruptibleEdge icon + */ + public String getInterruptibleEdgeIconVisualID(); + + /** + * Get the Interruptible edge icon or null if not set + * + * @return + */ + public Node getInterrutibleEgdeIcon(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/AbstractShowHideParameterPropertyEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/AbstractShowHideParameterPropertyEditPolicy.java index e404267a43e..ba5c7ddffe9 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/AbstractShowHideParameterPropertyEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/AbstractShowHideParameterPropertyEditPolicy.java @@ -1,218 +1,218 @@ -/*****************************************************************************
- * Copyright (c) 2015 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- * Camille Letavernier - camille.letavernier@cea.fr - Bug 490054
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gef.editpolicies.AbstractEditPolicy;
-import org.eclipse.gmf.runtime.diagram.core.listener.DiagramEventBroker;
-import org.eclipse.gmf.runtime.diagram.core.listener.NotificationListener;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.emf.type.core.commands.SetValueCommand;
-import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest;
-import org.eclipse.gmf.runtime.notation.NotationPackage;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.infra.emf.gmf.util.GMFUnsafe;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityParameterNodeEditPart;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.uml2.uml.ActivityParameterNode;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * Base class to show and hide stream and exception label in {@link ActivityParameterNodeEditPart}
- *
- * @since 2.0
- */
-public abstract class AbstractShowHideParameterPropertyEditPolicy extends AbstractEditPolicy implements NotificationListener {
-
- protected ActivityParameterNode semanticElement;
-
- protected Parameter currentParameter;
-
- @Override
- public void activate() {
- super.activate();
- // add listeners
- startListen();
- }
-
- @Override
- public void deactivate() {
- // remove listeners
- stopListen();
- super.deactivate();
- }
-
- /**
- * Add listeners to host semantic
- */
- protected void startListen() {
- semanticElement = findHostSemantic();
- addEObjectListener(semanticElement);
- currentParameter = semanticElement.getParameter();
- addEObjectListener(currentParameter);
- refresh();
- }
-
- public abstract void refresh();
-
- /**
- * Remove listeners to host semantic
- */
- protected void stopListen() {
- removeEObjectListener(semanticElement);
- removeEObjectListener(currentParameter);
- }
-
- /**
- * Add this class to listeners of eObject
- */
- protected void addEObjectListener(Object object) {
- if (object instanceof EObject) {
- getDiagramEventBroker().addNotificationListener((EObject) object, this);
- }
- }
-
- /**
- * Remove this class from listeners of eObject
- */
- protected void removeEObjectListener(Object object) {
- if (object instanceof EObject) {
- getDiagramEventBroker().removeNotificationListener((EObject) object, this);
- }
- }
-
- @Override
- public IGraphicalEditPart getHost() {
- return (IGraphicalEditPart) super.getHost();
- }
-
- /**
- * Resolve host semantic element
- *
- * @return {@link ActivityParameterNode}
- */
- protected ActivityParameterNode findHostSemantic() {
- return (ActivityParameterNode) getHost().resolveSemanticElement();
- }
-
- /**
- * Gets diagram event broker from editing domain.
- *
- * @return diagram event broker
- */
- protected DiagramEventBroker getDiagramEventBroker() {
- TransactionalEditingDomain editingDomain = getHost().getEditingDomain();
- if (editingDomain != null) {
- return DiagramEventBroker.getInstance(editingDomain);
- }
- return null;
- }
-
- @Override
- public void notifyChanged(Notification notification) {
- Object object = notification.getNotifier();
- if (object == semanticElement) {
- notifyActivityParameterNode(notification);
- } else if (object != null && object == currentParameter) {
- notifyParameter(notification);
- }
- }
-
- /**
- * Process notification from {@link Parameter}
- *
- * @param notification
- */
- protected abstract void notifyParameter(Notification notification);
-
- /**
- * Process notification from {@link ActivityParameterNode}
- *
- * @param notification
- */
- protected void notifyActivityParameterNode(Notification notification) {
- switch (notification.getFeatureID(ActivityParameterNode.class)) {
- case UMLPackage.ACTIVITY_PARAMETER_NODE__PARAMETER:
- switch (notification.getEventType()) {
- case Notification.SET:
- removeEObjectListener(notification.getOldValue());
- addEObjectListener(notification.getNewValue());
- if (notification.getFeature() == UMLPackage.Literals.ACTIVITY_PARAMETER_NODE__PARAMETER) {
- currentParameter = (Parameter) notification.getNewValue();
- }
- break;
- case Notification.UNSET:
- removeEObjectListener(notification.getOldValue());
- if (notification.getFeature() == UMLPackage.Literals.ACTIVITY_PARAMETER_NODE__PARAMETER) {
- currentParameter = null;
- }
- break;
- }
- refresh();
- break;
- }
- }
-
- /**
- * Usafe execute GMF command
- */
- protected void execute(final TransactionalEditingDomain domain, SetValueCommand setVisibleCommand) {
- try {
- GMFUnsafe.write(domain, setVisibleCommand);
- } catch (Exception e) {
- Activator.log.error(e);
- }
- }
-
- /**
- * Set visibility of input view to false
- */
- protected void hideLabelView(View view) {
- if (view.isVisible()) {
- SetValueCommand setVisibleCommand = new SetValueCommand(new SetRequest(view, NotationPackage.eINSTANCE.getView_Visible(), Boolean.FALSE));
- execute(getHost().getEditingDomain(), setVisibleCommand);
- }
- }
-
- /**
- * Set visibility of input view to true
- */
- protected void showLabelView(View view) {
- if (!view.isVisible()) {
- SetValueCommand setVisibleCommand = new SetValueCommand(new SetRequest(view, NotationPackage.eINSTANCE.getView_Visible(), Boolean.TRUE));
- execute(getHost().getEditingDomain(), setVisibleCommand);
- }
- }
-
- /**
- * Find in host label view with VID in type
- */
- protected View getLabelView(String VID) {
- View labelView = null;
- for (Object child : getHost().getNotationView().getChildren()) {
- View view = (View) child;
- if (view.getType().equals(VID)) {
- labelView = view;
- break;
- }
- }
- assert labelView == null : "Child view should be always present in host view";
-
- return labelView;
- }
-}
+/***************************************************************************** + * Copyright (c) 2015 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * Camille Letavernier - camille.letavernier@cea.fr - Bug 490054 + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gef.editpolicies.AbstractEditPolicy; +import org.eclipse.gmf.runtime.diagram.core.listener.DiagramEventBroker; +import org.eclipse.gmf.runtime.diagram.core.listener.NotificationListener; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.emf.type.core.commands.SetValueCommand; +import org.eclipse.gmf.runtime.emf.type.core.requests.SetRequest; +import org.eclipse.gmf.runtime.notation.NotationPackage; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.infra.emf.gmf.util.GMFUnsafe; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityParameterNodeEditPart; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.uml2.uml.ActivityParameterNode; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * Base class to show and hide stream and exception label in {@link ActivityParameterNodeEditPart} + * + * @since 2.0 + */ +public abstract class AbstractShowHideParameterPropertyEditPolicy extends AbstractEditPolicy implements NotificationListener { + + protected ActivityParameterNode semanticElement; + + protected Parameter currentParameter; + + @Override + public void activate() { + super.activate(); + // add listeners + startListen(); + } + + @Override + public void deactivate() { + // remove listeners + stopListen(); + super.deactivate(); + } + + /** + * Add listeners to host semantic + */ + protected void startListen() { + semanticElement = findHostSemantic(); + addEObjectListener(semanticElement); + currentParameter = semanticElement.getParameter(); + addEObjectListener(currentParameter); + refresh(); + } + + public abstract void refresh(); + + /** + * Remove listeners to host semantic + */ + protected void stopListen() { + removeEObjectListener(semanticElement); + removeEObjectListener(currentParameter); + } + + /** + * Add this class to listeners of eObject + */ + protected void addEObjectListener(Object object) { + if (object instanceof EObject) { + getDiagramEventBroker().addNotificationListener((EObject) object, this); + } + } + + /** + * Remove this class from listeners of eObject + */ + protected void removeEObjectListener(Object object) { + if (object instanceof EObject) { + getDiagramEventBroker().removeNotificationListener((EObject) object, this); + } + } + + @Override + public IGraphicalEditPart getHost() { + return (IGraphicalEditPart) super.getHost(); + } + + /** + * Resolve host semantic element + * + * @return {@link ActivityParameterNode} + */ + protected ActivityParameterNode findHostSemantic() { + return (ActivityParameterNode) getHost().resolveSemanticElement(); + } + + /** + * Gets diagram event broker from editing domain. + * + * @return diagram event broker + */ + protected DiagramEventBroker getDiagramEventBroker() { + TransactionalEditingDomain editingDomain = getHost().getEditingDomain(); + if (editingDomain != null) { + return DiagramEventBroker.getInstance(editingDomain); + } + return null; + } + + @Override + public void notifyChanged(Notification notification) { + Object object = notification.getNotifier(); + if (object == semanticElement) { + notifyActivityParameterNode(notification); + } else if (object != null && object == currentParameter) { + notifyParameter(notification); + } + } + + /** + * Process notification from {@link Parameter} + * + * @param notification + */ + protected abstract void notifyParameter(Notification notification); + + /** + * Process notification from {@link ActivityParameterNode} + * + * @param notification + */ + protected void notifyActivityParameterNode(Notification notification) { + switch (notification.getFeatureID(ActivityParameterNode.class)) { + case UMLPackage.ACTIVITY_PARAMETER_NODE__PARAMETER: + switch (notification.getEventType()) { + case Notification.SET: + removeEObjectListener(notification.getOldValue()); + addEObjectListener(notification.getNewValue()); + if (notification.getFeature() == UMLPackage.Literals.ACTIVITY_PARAMETER_NODE__PARAMETER) { + currentParameter = (Parameter) notification.getNewValue(); + } + break; + case Notification.UNSET: + removeEObjectListener(notification.getOldValue()); + if (notification.getFeature() == UMLPackage.Literals.ACTIVITY_PARAMETER_NODE__PARAMETER) { + currentParameter = null; + } + break; + } + refresh(); + break; + } + } + + /** + * Usafe execute GMF command + */ + protected void execute(final TransactionalEditingDomain domain, SetValueCommand setVisibleCommand) { + try { + GMFUnsafe.write(domain, setVisibleCommand); + } catch (Exception e) { + Activator.log.error(e); + } + } + + /** + * Set visibility of input view to false + */ + protected void hideLabelView(View view) { + if (view.isVisible()) { + SetValueCommand setVisibleCommand = new SetValueCommand(new SetRequest(view, NotationPackage.eINSTANCE.getView_Visible(), Boolean.FALSE)); + execute(getHost().getEditingDomain(), setVisibleCommand); + } + } + + /** + * Set visibility of input view to true + */ + protected void showLabelView(View view) { + if (!view.isVisible()) { + SetValueCommand setVisibleCommand = new SetValueCommand(new SetRequest(view, NotationPackage.eINSTANCE.getView_Visible(), Boolean.TRUE)); + execute(getHost().getEditingDomain(), setVisibleCommand); + } + } + + /** + * Find in host label view with VID in type + */ + protected View getLabelView(String VID) { + View labelView = null; + for (Object child : getHost().getNotationView().getChildren()) { + View view = (View) child; + if (view.getType().equals(VID)) { + labelView = view; + break; + } + } + assert labelView == null : "Child view should be always present in host view"; + + return labelView; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/AcceptTimeEventActionStereotypeExternalNodeEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/AcceptTimeEventActionStereotypeExternalNodeEditPolicy.java index 2a623960660..74a612d45af 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/AcceptTimeEventActionStereotypeExternalNodeEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/AcceptTimeEventActionStereotypeExternalNodeEditPolicy.java @@ -1,100 +1,100 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.papyrus.infra.gmfdiag.common.editpart.IPapyrusEditPart;
-import org.eclipse.papyrus.uml.diagram.common.editpolicies.AppliedStereotypeExternalNodeEditPolicy;
-import org.eclipse.papyrus.uml.diagram.common.figure.node.IPapyrusUMLElementFigure;
-import org.eclipse.papyrus.uml.diagram.common.stereotype.display.helper.StereotypeDisplayUtil;
-import org.eclipse.uml2.uml.AcceptEventAction;
-import org.eclipse.uml2.uml.TimeEvent;
-import org.eclipse.uml2.uml.UMLPackage;
-
-
-/**
- * this is a specific class to display stereotype label for accept event action, it is only display if the event is a TimeEvent
- *
- */
-public class AcceptTimeEventActionStereotypeExternalNodeEditPolicy extends AppliedStereotypeExternalNodeEditPolicy {
-
- /**
- * add a specific test about TimeEvent
- *
- * @see org.eclipse.papyrus.uml.diagram.common.editpolicies.AppliedStereotypeExternalNodeEditPolicy#refreshStereotypeDisplay()
- *
- */
- @Override
- protected void refreshStereotypeDisplay() {
- if (getHost() instanceof IPapyrusEditPart) {
- IFigure figure = ((IPapyrusEditPart) getHost()).getPrimaryShape();
-
- if (getUMLElement() instanceof AcceptEventAction) {
- if (((AcceptEventAction) getUMLElement()).getTriggers().size() > 0
- && (((AcceptEventAction) getUMLElement()).getTriggers().get(0).getEvent() instanceof TimeEvent)) {
- if (figure instanceof IPapyrusUMLElementFigure) {
- // calculate text
- // and icon to display
- final String stereotypesToDisplay = stereotypesToDisplay();
- ((IPapyrusUMLElementFigure) figure).setStereotypeDisplay(tag + (stereotypesToDisplay), null);
- }
- }
- else {
- ((IPapyrusUMLElementFigure) figure).setStereotypeDisplay("", null);
- }
- }
- }
-
- }
-
- /**
- *
- * do not pary attention if this compartment or brace due to shape change
- *
- * @return the list of stereotypes to display with properties if there are
- * selected to be displayed
- */
- @Override
- public String stereotypesToDisplay() {
-
- // retrieve all stereotypes to be displayed
-
- if (parentView == null) {
- return "";
- }
-
- // try to display stereotype properties
- String stereotypesToDisplay = StereotypeDisplayUtil.getInstance().getStereotypeTextToDisplay(parentView);
- return stereotypesToDisplay;
-
- }
-
- /**
- * add notification about trigger
- *
- * @see org.eclipse.papyrus.uml.diagram.common.editpolicies.AbstractAppliedStereotypeDisplayEditPolicy#notifyChanged(org.eclipse.emf.common.notify.Notification)
- *
- * @param notification
- */
- @Override
- public void notifyChanged(Notification notification) {
-
- super.notifyChanged(notification);
- if (UMLPackage.eINSTANCE.getAcceptEventAction_Trigger().equals(notification.getFeature())) {
- refreshStereotypeDisplay();
- }
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.papyrus.infra.gmfdiag.common.editpart.IPapyrusEditPart; +import org.eclipse.papyrus.uml.diagram.common.editpolicies.AppliedStereotypeExternalNodeEditPolicy; +import org.eclipse.papyrus.uml.diagram.common.figure.node.IPapyrusUMLElementFigure; +import org.eclipse.papyrus.uml.diagram.common.stereotype.display.helper.StereotypeDisplayUtil; +import org.eclipse.uml2.uml.AcceptEventAction; +import org.eclipse.uml2.uml.TimeEvent; +import org.eclipse.uml2.uml.UMLPackage; + + +/** + * this is a specific class to display stereotype label for accept event action, it is only display if the event is a TimeEvent + * + */ +public class AcceptTimeEventActionStereotypeExternalNodeEditPolicy extends AppliedStereotypeExternalNodeEditPolicy { + + /** + * add a specific test about TimeEvent + * + * @see org.eclipse.papyrus.uml.diagram.common.editpolicies.AppliedStereotypeExternalNodeEditPolicy#refreshStereotypeDisplay() + * + */ + @Override + protected void refreshStereotypeDisplay() { + if (getHost() instanceof IPapyrusEditPart) { + IFigure figure = ((IPapyrusEditPart) getHost()).getPrimaryShape(); + + if (getUMLElement() instanceof AcceptEventAction) { + if (((AcceptEventAction) getUMLElement()).getTriggers().size() > 0 + && (((AcceptEventAction) getUMLElement()).getTriggers().get(0).getEvent() instanceof TimeEvent)) { + if (figure instanceof IPapyrusUMLElementFigure) { + // calculate text + // and icon to display + final String stereotypesToDisplay = stereotypesToDisplay(); + ((IPapyrusUMLElementFigure) figure).setStereotypeDisplay(tag + (stereotypesToDisplay), null); + } + } + else { + ((IPapyrusUMLElementFigure) figure).setStereotypeDisplay("", null); + } + } + } + + } + + /** + * + * do not pary attention if this compartment or brace due to shape change + * + * @return the list of stereotypes to display with properties if there are + * selected to be displayed + */ + @Override + public String stereotypesToDisplay() { + + // retrieve all stereotypes to be displayed + + if (parentView == null) { + return ""; + } + + // try to display stereotype properties + String stereotypesToDisplay = StereotypeDisplayUtil.getInstance().getStereotypeTextToDisplay(parentView); + return stereotypesToDisplay; + + } + + /** + * add notification about trigger + * + * @see org.eclipse.papyrus.uml.diagram.common.editpolicies.AbstractAppliedStereotypeDisplayEditPolicy#notifyChanged(org.eclipse.emf.common.notify.Notification) + * + * @param notification + */ + @Override + public void notifyChanged(Notification notification) { + + super.notifyChanged(notification); + if (UMLPackage.eINSTANCE.getAcceptEventAction_Trigger().equals(notification.getFeature())) { + refreshStereotypeDisplay(); + } + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityDiagramChangeStereotypedShapeEditpolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityDiagramChangeStereotypedShapeEditpolicy.java index eb7ba6e2c41..668cf1efd1f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityDiagramChangeStereotypedShapeEditpolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityDiagramChangeStereotypedShapeEditpolicy.java @@ -1,105 +1,105 @@ -/*****************************************************************************
- * Copyright (c) 2010 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import java.util.ArrayList;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.RequestConstants;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.requests.GroupRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest;
-import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper;
-import org.eclipse.papyrus.uml.diagram.activity.edit.commands.ElementToStereotypedShape;
-import org.eclipse.papyrus.uml.diagram.common.editpolicies.ChangeStereotypedShapeEditPolicy;
-import org.eclipse.swt.widgets.Display;
-
-/**
- * the goal of this class is to allow changing the aspect of an element by
- * taking in account its stereotype
- *
- */
-public class ActivityDiagramChangeStereotypedShapeEditpolicy extends ChangeStereotypedShapeEditPolicy {
-
- @Override
- public void transformIntoShape(final EditPart part) {
- try {
- ((IGraphicalEditPart) getHost()).getEditingDomain().runExclusive(new Runnable() {
-
- @Override
- public void run() {
- Display.getCurrent().asyncExec(new Runnable() {
-
- @Override
- public void run() {
- if (part instanceof GraphicalEditPart) {
- GraphicalEditPart gmfparent = (GraphicalEditPart) part.getParent();
- GraphicalEditPart gmfpart = (GraphicalEditPart) part;
- org.eclipse.papyrus.uml.diagram.activity.edit.commands.ElementToStereotypedShape command = new ElementToStereotypedShape(gmfpart.getEditingDomain(), gmfpart);
- gmfpart.getEditingDomain().getCommandStack().execute(command);
- ArrayList<EObject> elementToDrop = getAllSemanticLink(gmfpart);
- Request deleteViewRequest = new GroupRequest(RequestConstants.REQ_DELETE);
- Command deleteCommand = gmfpart.getCommand(deleteViewRequest);
- gmfpart.getDiagramEditDomain().getDiagramCommandStack().execute(deleteCommand);
- dropLink(gmfparent, elementToDrop);
- }
- }
- });
- }
- });
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void transformIntoNormalShape(final EditPart part) {
- try {
- ((IGraphicalEditPart) getHost()).getEditingDomain().runExclusive(new Runnable() {
-
- @Override
- public void run() {
- Display.getCurrent().asyncExec(new Runnable() {
-
- @Override
- public void run() {
- if (part instanceof GraphicalEditPart) {
- GraphicalEditPart gmfparent = (GraphicalEditPart) part.getParent();
- GraphicalEditPart gmfpart = (GraphicalEditPart) part;
- DropObjectsRequest dropObjectsRequest = new DropObjectsRequest();
- ArrayList<EObject> list = new ArrayList<EObject>();
- list.add(gmfpart.resolveSemanticElement());
- dropObjectsRequest.setObjects(list);
- dropObjectsRequest.setLocation(gmfpart.getFigure().getBounds().getLocation());
- Command command = gmfpart.getParent().getCommand(dropObjectsRequest);
- gmfpart.getEditingDomain().getCommandStack().execute(new GEFtoEMFCommandWrapper(command));
- ArrayList<EObject> elementToDrop = getAllSemanticLink(gmfpart);
- Request deleteViewRequest = new GroupRequest(RequestConstants.REQ_DELETE);
- Command deleteCommand = gmfpart.getCommand(deleteViewRequest);
- gmfpart.getDiagramEditDomain().getDiagramCommandStack().execute(deleteCommand);
- dropLink(gmfparent, elementToDrop);
- }
- }
- });
- }
- });
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2010 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import java.util.ArrayList; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.Request; +import org.eclipse.gef.RequestConstants; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.requests.GroupRequest; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest; +import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper; +import org.eclipse.papyrus.uml.diagram.activity.edit.commands.ElementToStereotypedShape; +import org.eclipse.papyrus.uml.diagram.common.editpolicies.ChangeStereotypedShapeEditPolicy; +import org.eclipse.swt.widgets.Display; + +/** + * the goal of this class is to allow changing the aspect of an element by + * taking in account its stereotype + * + */ +public class ActivityDiagramChangeStereotypedShapeEditpolicy extends ChangeStereotypedShapeEditPolicy { + + @Override + public void transformIntoShape(final EditPart part) { + try { + ((IGraphicalEditPart) getHost()).getEditingDomain().runExclusive(new Runnable() { + + @Override + public void run() { + Display.getCurrent().asyncExec(new Runnable() { + + @Override + public void run() { + if (part instanceof GraphicalEditPart) { + GraphicalEditPart gmfparent = (GraphicalEditPart) part.getParent(); + GraphicalEditPart gmfpart = (GraphicalEditPart) part; + org.eclipse.papyrus.uml.diagram.activity.edit.commands.ElementToStereotypedShape command = new ElementToStereotypedShape(gmfpart.getEditingDomain(), gmfpart); + gmfpart.getEditingDomain().getCommandStack().execute(command); + ArrayList<EObject> elementToDrop = getAllSemanticLink(gmfpart); + Request deleteViewRequest = new GroupRequest(RequestConstants.REQ_DELETE); + Command deleteCommand = gmfpart.getCommand(deleteViewRequest); + gmfpart.getDiagramEditDomain().getDiagramCommandStack().execute(deleteCommand); + dropLink(gmfparent, elementToDrop); + } + } + }); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + @Override + public void transformIntoNormalShape(final EditPart part) { + try { + ((IGraphicalEditPart) getHost()).getEditingDomain().runExclusive(new Runnable() { + + @Override + public void run() { + Display.getCurrent().asyncExec(new Runnable() { + + @Override + public void run() { + if (part instanceof GraphicalEditPart) { + GraphicalEditPart gmfparent = (GraphicalEditPart) part.getParent(); + GraphicalEditPart gmfpart = (GraphicalEditPart) part; + DropObjectsRequest dropObjectsRequest = new DropObjectsRequest(); + ArrayList<EObject> list = new ArrayList<EObject>(); + list.add(gmfpart.resolveSemanticElement()); + dropObjectsRequest.setObjects(list); + dropObjectsRequest.setLocation(gmfpart.getFigure().getBounds().getLocation()); + Command command = gmfpart.getParent().getCommand(dropObjectsRequest); + gmfpart.getEditingDomain().getCommandStack().execute(new GEFtoEMFCommandWrapper(command)); + ArrayList<EObject> elementToDrop = getAllSemanticLink(gmfpart); + Request deleteViewRequest = new GroupRequest(RequestConstants.REQ_DELETE); + Command deleteCommand = gmfpart.getCommand(deleteViewRequest); + gmfpart.getDiagramEditDomain().getDiagramCommandStack().execute(deleteCommand); + dropLink(gmfparent, elementToDrop); + } + } + }); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityGroupCustomDragAndDropEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityGroupCustomDragAndDropEditPolicy.java index d97f2084aca..4ddda9160fd 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityGroupCustomDragAndDropEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityGroupCustomDragAndDropEditPolicy.java @@ -1,130 +1,130 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import java.util.Collection;
-
-import org.eclipse.core.commands.operations.IUndoableOperation;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.commands.CompoundCommand;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand;
-import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ContainerNodeDescriptorRegistry;
-import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Pin;
-
-/**
- * Drag and drop policy which allow drop of objects which are not contains from a semantic point of view into a visual element such as Activity
- * Partition
- *
- * @author adaussy
- *
- */
-public class ActivityGroupCustomDragAndDropEditPolicy extends CustomDiagramDragDropEditPolicy {
-
- /**
- * Override in order to accept drop of element which are not directly containing by a referencing group
- *
- * @see org.eclipse.papyrus.uml.diagram.common.editpolicies.CommonDiagramDragDropEditPolicy#getDropObjectCommand(org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest, org.eclipse.emf.ecore.EObject)
- */
- @Override
- protected IUndoableOperation getDropObjectCommand(DropObjectsRequest dropRequest, EObject droppedObject) {
- Point location = dropRequest.getLocation().getCopy();
- EditPart hostForDroppedObject = droppedObject instanceof Pin ? getHost().getParent() : getHost();
- String nodeVISUALID = getNodeVisualID(((IGraphicalEditPart) hostForDroppedObject).getNotationView(), droppedObject);
- String linkVISUALID = getLinkWithClassVisualID(droppedObject);
- if (getSpecificDrop().contains(nodeVISUALID) || getSpecificDrop().contains(linkVISUALID)) {
- Command specificDropCommand = getSpecificDropCommand(dropRequest, (Element) droppedObject, nodeVISUALID, linkVISUALID);
- CompositeCommand cc = new CompositeCommand("Drop command");
- cc.compose(new CommandProxy(specificDropCommand));
- // If ctrl key activate, get the content of element dropped
- if (isCopy(dropRequest)) {
- // Check for ICommandProxy and CompoundCommand the most command type used
- if (specificDropCommand instanceof ICommandProxy) {
- ICommandProxy specificDropCommandProxy = (ICommandProxy) specificDropCommand;
- createDeferredCommandWithCommandResult(droppedObject, cc, specificDropCommandProxy);
- } else if (specificDropCommand instanceof CompoundCommand) {
- CompoundCommand specificDropCompoundCommand = (CompoundCommand) specificDropCommand;
- ICommandProxy cp = getCommandProxyFromCompoundCommand(specificDropCompoundCommand);
- if (cp != null) {
- createDeferredCommandWithCommandResult(droppedObject, cc, cp);
- }
- }
- }
- return cc;
- }
- if (linkVISUALID == null && nodeVISUALID != null) {
- // The element to drop is a node
- // Retrieve it's expected graphical parent
- EObject graphicalParent = ((GraphicalEditPart) getHost()).resolveSemanticElement();
- // Restrict the default node creation to the following cases:
- // . Take the containment relationship into consideration
- // . Release the constraint when GraphicalParent is a diagram
- IContainerNodeDescriptor descriptor = ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(getContainerEClass());
- if ((graphicalParent instanceof Element)) {
- if (descriptor.canIBeModelParentOf(droppedObject.eClass())) {
- if (droppedObject.eContainer() != null && !droppedObject.eContainer().equals(getHostObject())) {
- return UnexecutableCommand.INSTANCE;
- }
- return getDefaultDropNodeCommand(hostForDroppedObject, nodeVISUALID, location, droppedObject, dropRequest);
- } else if (descriptor.canIBeGraphicalParentOf(droppedObject.eClass())) {
- return getDefaultDropNodeCommand(hostForDroppedObject, nodeVISUALID, location, droppedObject, dropRequest);
- }
- }
- return org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand.INSTANCE;
- }
- if (linkVISUALID != null) {
- Collection<?> sources = linkmappingHelper.getSource((Element) droppedObject);
- Collection<?> targets = linkmappingHelper.getTarget((Element) droppedObject);
- if (sources.size() == 0 || targets.size() == 0) {
- return org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand.INSTANCE;
- }
- // binary association
- Element source = (Element) sources.toArray()[0];
- Element target = (Element) targets.toArray()[0];
- CompositeCommand cc = new CompositeCommand("Add Link"); //$NON-NLS-1$
- dropBinaryLink(cc, source, target, linkVISUALID, location, (Element) droppedObject);
- return cc;
- }
- return org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand.INSTANCE;
- }
-
- /**
- * Retreive the {@link EClass} of the host
- *
- * @return
- */
- protected EClass getContainerEClass() {
- EditPart editPart = getHost();
- if (editPart instanceof IGraphicalEditPart) {
- IGraphicalEditPart part = (IGraphicalEditPart) editPart;
- EObject element = part.resolveSemanticElement();
- if (element != null) {
- return element.eClass();
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : 372745: [ActivityDiagram] Major refactoring group framework + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import java.util.Collection; + +import org.eclipse.core.commands.operations.IUndoableOperation; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.commands.CompoundCommand; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand; +import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.ContainerNodeDescriptorRegistry; +import org.eclipse.papyrus.uml.diagram.activity.activitygroup.IContainerNodeDescriptor; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Pin; + +/** + * Drag and drop policy which allow drop of objects which are not contains from a semantic point of view into a visual element such as Activity + * Partition + * + * @author adaussy + * + */ +public class ActivityGroupCustomDragAndDropEditPolicy extends CustomDiagramDragDropEditPolicy { + + /** + * Override in order to accept drop of element which are not directly containing by a referencing group + * + * @see org.eclipse.papyrus.uml.diagram.common.editpolicies.CommonDiagramDragDropEditPolicy#getDropObjectCommand(org.eclipse.gmf.runtime.diagram.ui.requests.DropObjectsRequest, org.eclipse.emf.ecore.EObject) + */ + @Override + protected IUndoableOperation getDropObjectCommand(DropObjectsRequest dropRequest, EObject droppedObject) { + Point location = dropRequest.getLocation().getCopy(); + EditPart hostForDroppedObject = droppedObject instanceof Pin ? getHost().getParent() : getHost(); + String nodeVISUALID = getNodeVisualID(((IGraphicalEditPart) hostForDroppedObject).getNotationView(), droppedObject); + String linkVISUALID = getLinkWithClassVisualID(droppedObject); + if (getSpecificDrop().contains(nodeVISUALID) || getSpecificDrop().contains(linkVISUALID)) { + Command specificDropCommand = getSpecificDropCommand(dropRequest, (Element) droppedObject, nodeVISUALID, linkVISUALID); + CompositeCommand cc = new CompositeCommand("Drop command"); + cc.compose(new CommandProxy(specificDropCommand)); + // If ctrl key activate, get the content of element dropped + if (isCopy(dropRequest)) { + // Check for ICommandProxy and CompoundCommand the most command type used + if (specificDropCommand instanceof ICommandProxy) { + ICommandProxy specificDropCommandProxy = (ICommandProxy) specificDropCommand; + createDeferredCommandWithCommandResult(droppedObject, cc, specificDropCommandProxy); + } else if (specificDropCommand instanceof CompoundCommand) { + CompoundCommand specificDropCompoundCommand = (CompoundCommand) specificDropCommand; + ICommandProxy cp = getCommandProxyFromCompoundCommand(specificDropCompoundCommand); + if (cp != null) { + createDeferredCommandWithCommandResult(droppedObject, cc, cp); + } + } + } + return cc; + } + if (linkVISUALID == null && nodeVISUALID != null) { + // The element to drop is a node + // Retrieve it's expected graphical parent + EObject graphicalParent = ((GraphicalEditPart) getHost()).resolveSemanticElement(); + // Restrict the default node creation to the following cases: + // . Take the containment relationship into consideration + // . Release the constraint when GraphicalParent is a diagram + IContainerNodeDescriptor descriptor = ContainerNodeDescriptorRegistry.getInstance().getContainerNodeDescriptor(getContainerEClass()); + if ((graphicalParent instanceof Element)) { + if (descriptor.canIBeModelParentOf(droppedObject.eClass())) { + if (droppedObject.eContainer() != null && !droppedObject.eContainer().equals(getHostObject())) { + return UnexecutableCommand.INSTANCE; + } + return getDefaultDropNodeCommand(hostForDroppedObject, nodeVISUALID, location, droppedObject, dropRequest); + } else if (descriptor.canIBeGraphicalParentOf(droppedObject.eClass())) { + return getDefaultDropNodeCommand(hostForDroppedObject, nodeVISUALID, location, droppedObject, dropRequest); + } + } + return org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand.INSTANCE; + } + if (linkVISUALID != null) { + Collection<?> sources = linkmappingHelper.getSource((Element) droppedObject); + Collection<?> targets = linkmappingHelper.getTarget((Element) droppedObject); + if (sources.size() == 0 || targets.size() == 0) { + return org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand.INSTANCE; + } + // binary association + Element source = (Element) sources.toArray()[0]; + Element target = (Element) targets.toArray()[0]; + CompositeCommand cc = new CompositeCommand("Add Link"); //$NON-NLS-1$ + dropBinaryLink(cc, source, target, linkVISUALID, location, (Element) droppedObject); + return cc; + } + return org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand.INSTANCE; + } + + /** + * Retreive the {@link EClass} of the host + * + * @return + */ + protected EClass getContainerEClass() { + EditPart editPart = getHost(); + if (editPart instanceof IGraphicalEditPart) { + IGraphicalEditPart part = (IGraphicalEditPart) editPart; + EObject element = part.resolveSemanticElement(); + if (element != null) { + return element.eClass(); + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityPartitionLabelEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityPartitionLabelEditPolicy.java index 4efb6772857..403ee0e3ae9 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityPartitionLabelEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ActivityPartitionLabelEditPolicy.java @@ -1,100 +1,100 @@ -/*****************************************************************************
- * Copyright (c) 2017 Ericsson Communications.
- *
- * 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:
- * Ericsson Communications - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.gef.GraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionNameEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.helper.ActivityPartitionLabelHelper;
-import org.eclipse.papyrus.uml.diagram.common.editpolicies.AbstractMaskManagedEditPolicy;
-import org.eclipse.uml2.uml.ActivityPartition;
-import org.eclipse.uml2.uml.Element;
-
-/**
- * @since 3.0
- */
-public class ActivityPartitionLabelEditPolicy extends AbstractMaskManagedEditPolicy {
-
- @Override
- public void addAdditionalListeners() {
- super.addAdditionalListeners();
-
- ActivityPartition activityPartition = getUMLElement();
- // check host semantic element is not null
- if (activityPartition == null) {
- return;
- }
- // adds a listener to the element itself, and to linked elements, like Type
- getDiagramEventBroker().addNotificationListener(activityPartition, this);
- Element el = activityPartition.getRepresents();
- if (el != null) {
- getDiagramEventBroker().addNotificationListener(el, this);
- }
- }
-
- @Override
- protected void removeAdditionalListeners() {
- super.removeAdditionalListeners();
- ActivityPartition activityPartition = getUMLElement();
- // check host semantic element is not null
- if (activityPartition == null) {
- return;
- }
- getDiagramEventBroker().removeNotificationListener(activityPartition, this);
- Element el = activityPartition.getRepresents();
- if (el != null) {
- getDiagramEventBroker().removeNotificationListener(el, this);
- }
- }
-
-
- @Override
- public void refreshDisplay() {
- // calls the helper for this edit Part
- ActivityPartitionEditPart lp = (ActivityPartitionEditPart) getHost();
- List children = lp.getChildren();
- for (Object p : children) {
- if (p instanceof ActivityPartitionNameEditPart) {
- ActivityPartitionLabelHelper.getInstance().refreshEditPartDisplay((GraphicalEditPart) p);
- }
- }
- }
-
-
- @Override
- public Collection<String> getDefaultDisplayValue() {
- return ActivityPartitionLabelHelper.DEFAULT_LABEL_DISPLAY;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Map<String, String> getMasks() {
- return ActivityPartitionLabelHelper.getInstance().getMasks();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public ActivityPartition getUMLElement() {
- return (ActivityPartition) hostSemanticElement;
-
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2017 Ericsson Communications. + * + * 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: + * Ericsson Communications - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +import org.eclipse.gef.GraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityPartitionNameEditPart; +import org.eclipse.papyrus.uml.diagram.activity.helper.ActivityPartitionLabelHelper; +import org.eclipse.papyrus.uml.diagram.common.editpolicies.AbstractMaskManagedEditPolicy; +import org.eclipse.uml2.uml.ActivityPartition; +import org.eclipse.uml2.uml.Element; + +/** + * @since 3.0 + */ +public class ActivityPartitionLabelEditPolicy extends AbstractMaskManagedEditPolicy { + + @Override + public void addAdditionalListeners() { + super.addAdditionalListeners(); + + ActivityPartition activityPartition = getUMLElement(); + // check host semantic element is not null + if (activityPartition == null) { + return; + } + // adds a listener to the element itself, and to linked elements, like Type + getDiagramEventBroker().addNotificationListener(activityPartition, this); + Element el = activityPartition.getRepresents(); + if (el != null) { + getDiagramEventBroker().addNotificationListener(el, this); + } + } + + @Override + protected void removeAdditionalListeners() { + super.removeAdditionalListeners(); + ActivityPartition activityPartition = getUMLElement(); + // check host semantic element is not null + if (activityPartition == null) { + return; + } + getDiagramEventBroker().removeNotificationListener(activityPartition, this); + Element el = activityPartition.getRepresents(); + if (el != null) { + getDiagramEventBroker().removeNotificationListener(el, this); + } + } + + + @Override + public void refreshDisplay() { + // calls the helper for this edit Part + ActivityPartitionEditPart lp = (ActivityPartitionEditPart) getHost(); + List children = lp.getChildren(); + for (Object p : children) { + if (p instanceof ActivityPartitionNameEditPart) { + ActivityPartitionLabelHelper.getInstance().refreshEditPartDisplay((GraphicalEditPart) p); + } + } + } + + + @Override + public Collection<String> getDefaultDisplayValue() { + return ActivityPartitionLabelHelper.DEFAULT_LABEL_DISPLAY; + } + + /** + * {@inheritDoc} + */ + @Override + public Map<String, String> getMasks() { + return ActivityPartitionLabelHelper.getInstance().getMasks(); + } + + /** + * {@inheritDoc} + */ + @Override + public ActivityPartition getUMLElement() { + return (ActivityPartition) hostSemanticElement; + + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/BehaviorPropertyNodeEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/BehaviorPropertyNodeEditPolicy.java index 9f9c4dec843..1bd2a75d4f7 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/BehaviorPropertyNodeEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/BehaviorPropertyNodeEditPolicy.java @@ -1,367 +1,367 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import java.util.Collections;
-import java.util.List;
-
-import org.eclipse.draw2d.Connection;
-import org.eclipse.draw2d.Graphics;
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.PolylineShape;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.draw2d.geometry.PointList;
-import org.eclipse.draw2d.geometry.PrecisionRectangle;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.gef.GraphicalEditPart;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.handles.MoveHandle;
-import org.eclipse.gef.requests.AlignmentRequest;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.commands.SetBoundsCommand;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IBorderItemEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.LabelEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.NonResizableEditPolicyEx;
-import org.eclipse.gmf.runtime.diagram.ui.figures.IBorderItemLocator;
-import org.eclipse.gmf.runtime.diagram.ui.internal.figures.LabelHelper;
-import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramUIMessages;
-import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants;
-import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
-import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
-import org.eclipse.gmf.runtime.notation.View;
-
-public class BehaviorPropertyNodeEditPolicy extends NonResizableEditPolicyEx {
-
- private PolylineShape linkFeedback = null;
-
- /**
- * @see org.eclipse.gef.editpolicies.NonResizableEditPolicy#createSelectionHandles()
- */
- @Override
- protected List createSelectionHandles() {
- MoveHandle mh = new MoveHandle((GraphicalEditPart) getHost());
- mh.setBorder(null);
- return Collections.singletonList(mh);
- }
-
- /**
- * Calls other methods as appropriate.
- */
- @Override
- public void eraseSourceFeedback(Request request) {
- if ((REQ_MOVE.equals(request.getType()) && isDragAllowed()) || REQ_CLONE.equals(request.getType()) || REQ_ADD.equals(request.getType()) || RequestConstants.REQ_DROP.equals(request.getType())) {
- eraseChangeBoundsFeedback((ChangeBoundsRequest) request);
- }
- }
-
- /**
- * Calls other methods as appropriate.
- */
- @Override
- public void showSourceFeedback(Request request) {
- if ((REQ_MOVE.equals(request.getType()) && isDragAllowed()) || REQ_ADD.equals(request.getType()) || REQ_CLONE.equals(request.getType()) || RequestConstants.REQ_DROP.equals(request.getType())) {
- showChangeBoundsFeedback((ChangeBoundsRequest) request);
- }
- }
-
- /**
- * Returns the command contribution to a change bounds request.
- *
- * @param request
- * the change bounds requesgt
- * @return the command contribution to the request
- */
- @Override
- protected Command getMoveCommand(ChangeBoundsRequest request) {
- // translate the feedback figure
- PrecisionRectangle rect = new PrecisionRectangle(getInitialFeedbackBounds().getCopy());
- getHostFigure().translateToAbsolute(rect);
- rect.translate(request.getMoveDelta());
- rect.resize(request.getSizeDelta());
- getHostFigure().translateToRelative(rect);
- if (getHost() instanceof IBorderItemEditPart) {
- IBorderItemEditPart borderItemEP = (IBorderItemEditPart) getHost();
- IBorderItemLocator borderItemLocator = borderItemEP.getBorderItemLocator();
- if (borderItemLocator != null) {
- Rectangle realLocation = borderItemLocator.getValidLocation(rect.getCopy(), borderItemEP.getFigure());
- Point parentOrigin = borderItemEP.getFigure().getParent().getBounds().getTopLeft();
- Dimension d = realLocation.getTopLeft().getDifference(parentOrigin);
- Point location = new Point(d.width, d.height);
- ICommand moveCommand = new SetBoundsCommand(borderItemEP.getEditingDomain(), DiagramUIMessages.Commands_MoveElement, new EObjectAdapter((View) getHost().getModel()), location);
- return new ICommandProxy(moveCommand);
- }
- } else if (getHost() instanceof LabelEditPart) {
- LabelEditPart editPart = (LabelEditPart) getHost();
- Point refPoint = editPart.getReferencePoint();
- Point normalPoint = LabelHelper.offsetFromRelativeCoordinate(getHostFigure(), rect, refPoint);
- ICommand moveCommand = new SetBoundsCommand(editPart.getEditingDomain(), DiagramUIMessages.Commands_MoveElement, new EObjectAdapter((View) editPart.getModel()), normalPoint);
- return new ICommandProxy(moveCommand);
- }
- return null;
- }
-
- /** Return <tt>null</tt> to avoid handling the request. */
- @Override
- protected Command getAlignCommand(AlignmentRequest request) {
- return null;
- }
-
- /**
- * Erase the feedback link figure
- *
- * @see org.eclipse.gef.editpolicies.NonResizableEditPolicy#eraseChangeBoundsFeedback(org.eclipse.gef.requests.ChangeBoundsRequest)
- */
- @Override
- protected void eraseChangeBoundsFeedback(ChangeBoundsRequest request) {
- super.eraseChangeBoundsFeedback(request);
- if (linkFeedback != null) {
- removeFeedback(linkFeedback);
- }
- linkFeedback = null;
- }
-
- /**
- * Create the feedback link figure
- *
- * @see org.eclipse.gef.editpolicies.NonResizableEditPolicy#createDragSourceFeedbackFigure()
- */
- @Override
- protected IFigure createDragSourceFeedbackFigure() {
- IFigure feedback = super.createDragSourceFeedbackFigure();
- linkFeedback = new PolylineShape();
- linkFeedback.setLineWidth(1);
- linkFeedback.setLineStyle(Graphics.LINE_DASHDOT);
- linkFeedback.setForegroundColor(((IGraphicalEditPart) getHost()).getFigure().getForegroundColor());
- addFeedback(linkFeedback);
- return feedback;
- }
-
- /**
- * Show link feedback
- *
- * @see org.eclipse.gmf.runtime.diagram.ui.editpolicies.BorderItemSelectionEditPolicy#showChangeBoundsFeedback(org.eclipse.gef.requests.ChangeBoundsRequest)
- */
- @Override
- protected void showChangeBoundsFeedback(org.eclipse.gef.requests.ChangeBoundsRequest request) {
- if (getHost() instanceof IBorderItemEditPart) {
- IBorderItemEditPart borderItemEP = (IBorderItemEditPart) getHost();
- IBorderItemLocator borderItemLocator = borderItemEP.getBorderItemLocator();
- if (borderItemLocator != null) {
- IFigure feedback = getDragSourceFeedbackFigure();
- PrecisionRectangle rect = new PrecisionRectangle(getInitialFeedbackBounds().getCopy());
- getHostFigure().translateToAbsolute(rect);
- rect.translate(request.getMoveDelta());
- rect.resize(request.getSizeDelta());
- getHostFigure().translateToRelative(rect);
- Rectangle realLocation = borderItemLocator.getValidLocation(rect.getCopy(), borderItemEP.getFigure());
- getHostFigure().translateToAbsolute(realLocation);
- feedback.translateToRelative(realLocation);
- feedback.setBounds(realLocation);
- }
- } else {
- super.showChangeBoundsFeedback(request);
- }
- // translate the feedback figure
- IFigure p = getDragSourceFeedbackFigure();
- PrecisionRectangle rect = new PrecisionRectangle(getInitialFeedbackBounds().getCopy());
- getHostFigure().translateToAbsolute(rect);
- rect.translate(request.getMoveDelta());
- rect.resize(request.getSizeDelta());
- p.translateToRelative(rect);
- p.setBounds(rect);
- Point referencePoint = getReferencePoint(request);
- Point end = getLinkEndPoint(request, referencePoint);
- linkFeedback.setEnd(end);
- Point start = getLinkStartPoint(request, referencePoint, end);
- if (start != null) {
- linkFeedback.setStart(start);
- } else {
- linkFeedback.setStart(referencePoint);
- }
- };
-
- /**
- * Get the reference point at the center of the parent figure
- *
- * @param request
- * change bounds request
- * @return point
- */
- private Point getReferencePoint(ChangeBoundsRequest request) {
- Point refPoint = ((LabelEditPart) getHost()).getReferencePoint();
- Rectangle centerMain = null;
- if (((IGraphicalEditPart) getHost().getParent()).getFigure() instanceof Connection) {
- centerMain = new Rectangle(refPoint.x, refPoint.y, 0, 0);
- } else {
- centerMain = ((IGraphicalEditPart) getHost().getParent()).getFigure().getBounds().getCopy();
- centerMain.translate(centerMain.width / 2, centerMain.height / 2);
- }
- PrecisionRectangle ref = new PrecisionRectangle(centerMain);
- getHostFigure().translateToAbsolute(ref);
- getDragSourceFeedbackFigure().translateToRelative(ref);
- return ref.getLocation();
- }
-
- /**
- * Get the point for starting the link
- *
- * @param request
- * change bounds request
- * @param referencePoint
- * the reference point at the center of the start figure
- * @param endPoint
- * the end point at the border of the end figure
- * @return point where to start the link
- */
- private Point getLinkStartPoint(ChangeBoundsRequest request, Point referencePoint, Point endPoint) {
- Point u1 = referencePoint;
- Point u2 = endPoint;
- if (getHost().getParent() instanceof AbstractBorderedShapeEditPart) {
- // the parent figure is a node : choose a point on its border
- AbstractBorderedShapeEditPart parentPart = (AbstractBorderedShapeEditPart) getHost().getParent();
- IFigure fig = parentPart.getMainFigure();
- if (fig instanceof NodeFigure) {
- PointList pointsList = ((NodeFigure) fig).getPolygonPoints().getCopy();
- // translate points relatively to drag feedback
- fig.translateToAbsolute(pointsList);
- getDragSourceFeedbackFigure().translateToRelative(pointsList);
- return getIntersectionPoint(pointsList, u1, u2);
- }
- }
- // either computation failed or the parent figure is a link
- return referencePoint;
- }
-
- /**
- * Get the point for ending the link
- *
- * @param request
- * change bounds request
- * @param referencePoint
- * the reference point at the center of the start figure
- * @return point
- */
- private Point getLinkEndPoint(ChangeBoundsRequest request, Point referencePoint) {
- Rectangle rect = getDragSourceFeedbackFigure().getBounds();
- Point endPoint = getAppropriateBorderPoint(referencePoint, rect);
- return endPoint;
- }
-
- /**
- * Get the point on the border intersection the segment
- *
- * @param polygonalBounds
- * the list of points tracing the border
- * @param insidePoint
- * first segment extremity
- * @param outsideExtremity
- * second segment extremity
- * @return the intersection point or null if none
- */
- public static Point getIntersectionPoint(PointList polygonalBounds, Point insidePoint, Point outsideExtremity) {
- Point intersection = null;
- int i = 0;
- while (intersection == null && i < polygonalBounds.size() - 1) {
- Point v1 = polygonalBounds.getPoint(i).getCopy();
- Point v2 = polygonalBounds.getPoint(i + 1).getCopy();
- intersection = getIntersection(insidePoint, outsideExtremity, v1, v2);
- i++;
- }
- return intersection;
- }
-
- /**
- * Get the point of the border which is the more appropriated to link to the
- * reference point
- *
- * @param referencePoint
- * point to refer to, which the link is directed to (not
- * necessary an end of the link)
- * @param border
- * the border on which an anchoring point must be chosen
- * @return a point of the border to use as link end
- */
- public static Point getAppropriateBorderPoint(Point referencePoint, Rectangle border) {
- Point midTop = new Point(border.x + border.width / 2, border.y);
- Point midBottom = new Point(border.x + border.width / 2, border.y + border.height);
- Point midLeft = new Point(border.x, border.y + border.height / 2);
- Point midRight = new Point(border.x + border.width, border.y + border.height / 2);
- Dimension diffTop = referencePoint.getDifference(midTop);
- Dimension diffBottom = referencePoint.getDifference(midBottom);
- Dimension diffRight = referencePoint.getDifference(midRight);
- Dimension diffLeft = referencePoint.getDifference(midLeft);
- Point startPoint = midBottom;
- if (diffBottom.height > 0) {
- // check if right or left is more appropriated
- if (diffLeft.width < 0 && diffBottom.height < -diffLeft.width) {
- startPoint = midLeft;
- } else if (diffRight.width > 0 && diffBottom.height < diffRight.width) {
- startPoint = midRight;
- } else {
- startPoint = midBottom;
- }
- } else if (diffTop.height < 0) {
- // check if right or left is more appropriated
- if (diffLeft.width < 0 && -diffTop.height < -diffLeft.width) {
- startPoint = midLeft;
- } else if (diffRight.width > 0 && -diffTop.height < diffRight.width) {
- startPoint = midRight;
- } else {
- startPoint = midTop;
- }
- } else if (diffLeft.width < 0) {
- startPoint = midLeft;
- } else if (diffRight.width > 0) {
- startPoint = midRight;
- }
- return startPoint;
- }
-
- /**
- * Get the intersection between segments joining the points
- *
- * @param u1
- * the first extremity of the u segment
- * @param u2
- * the second extremity of the u segment
- * @param v1
- * the first extremity of the v segment
- * @param v2
- * the second extremity of the v segment
- * @return the intersection point or null if none
- */
- public static Point getIntersection(Point u1, Point u2, Point v1, Point v2) {
- float denom = ((u2.y - u1.y) * (v2.x - v1.x)) - ((u2.x - u1.x) * (v2.y - v1.y));
- float nume_a = ((u2.x - u1.x) * (v1.y - u1.y)) - ((u2.y - u1.y) * (v1.x - u1.x));
- float nume_b = ((v2.x - v1.x) * (v1.y - u1.y)) - ((v2.y - v1.y) * (v1.x - u1.x));
- if (denom == 0.0f) {
- return null;
- }
- float ua = nume_a / denom;
- float ub = nume_b / denom;
- if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
- // Get the intersection point.
- Float x = v1.x + ua * (v2.x - v1.x);
- Float y = v1.y + ua * (v2.y - v1.y);
- return new Point(x.intValue(), y.intValue());
- }
- return null;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import java.util.Collections; +import java.util.List; + +import org.eclipse.draw2d.Connection; +import org.eclipse.draw2d.Graphics; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.PolylineShape; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.PointList; +import org.eclipse.draw2d.geometry.PrecisionRectangle; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.gef.GraphicalEditPart; +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.handles.MoveHandle; +import org.eclipse.gef.requests.AlignmentRequest; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.commands.SetBoundsCommand; +import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IBorderItemEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.LabelEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.NonResizableEditPolicyEx; +import org.eclipse.gmf.runtime.diagram.ui.figures.IBorderItemLocator; +import org.eclipse.gmf.runtime.diagram.ui.internal.figures.LabelHelper; +import org.eclipse.gmf.runtime.diagram.ui.l10n.DiagramUIMessages; +import org.eclipse.gmf.runtime.diagram.ui.requests.RequestConstants; +import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter; +import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure; +import org.eclipse.gmf.runtime.notation.View; + +public class BehaviorPropertyNodeEditPolicy extends NonResizableEditPolicyEx { + + private PolylineShape linkFeedback = null; + + /** + * @see org.eclipse.gef.editpolicies.NonResizableEditPolicy#createSelectionHandles() + */ + @Override + protected List createSelectionHandles() { + MoveHandle mh = new MoveHandle((GraphicalEditPart) getHost()); + mh.setBorder(null); + return Collections.singletonList(mh); + } + + /** + * Calls other methods as appropriate. + */ + @Override + public void eraseSourceFeedback(Request request) { + if ((REQ_MOVE.equals(request.getType()) && isDragAllowed()) || REQ_CLONE.equals(request.getType()) || REQ_ADD.equals(request.getType()) || RequestConstants.REQ_DROP.equals(request.getType())) { + eraseChangeBoundsFeedback((ChangeBoundsRequest) request); + } + } + + /** + * Calls other methods as appropriate. + */ + @Override + public void showSourceFeedback(Request request) { + if ((REQ_MOVE.equals(request.getType()) && isDragAllowed()) || REQ_ADD.equals(request.getType()) || REQ_CLONE.equals(request.getType()) || RequestConstants.REQ_DROP.equals(request.getType())) { + showChangeBoundsFeedback((ChangeBoundsRequest) request); + } + } + + /** + * Returns the command contribution to a change bounds request. + * + * @param request + * the change bounds requesgt + * @return the command contribution to the request + */ + @Override + protected Command getMoveCommand(ChangeBoundsRequest request) { + // translate the feedback figure + PrecisionRectangle rect = new PrecisionRectangle(getInitialFeedbackBounds().getCopy()); + getHostFigure().translateToAbsolute(rect); + rect.translate(request.getMoveDelta()); + rect.resize(request.getSizeDelta()); + getHostFigure().translateToRelative(rect); + if (getHost() instanceof IBorderItemEditPart) { + IBorderItemEditPart borderItemEP = (IBorderItemEditPart) getHost(); + IBorderItemLocator borderItemLocator = borderItemEP.getBorderItemLocator(); + if (borderItemLocator != null) { + Rectangle realLocation = borderItemLocator.getValidLocation(rect.getCopy(), borderItemEP.getFigure()); + Point parentOrigin = borderItemEP.getFigure().getParent().getBounds().getTopLeft(); + Dimension d = realLocation.getTopLeft().getDifference(parentOrigin); + Point location = new Point(d.width, d.height); + ICommand moveCommand = new SetBoundsCommand(borderItemEP.getEditingDomain(), DiagramUIMessages.Commands_MoveElement, new EObjectAdapter((View) getHost().getModel()), location); + return new ICommandProxy(moveCommand); + } + } else if (getHost() instanceof LabelEditPart) { + LabelEditPart editPart = (LabelEditPart) getHost(); + Point refPoint = editPart.getReferencePoint(); + Point normalPoint = LabelHelper.offsetFromRelativeCoordinate(getHostFigure(), rect, refPoint); + ICommand moveCommand = new SetBoundsCommand(editPart.getEditingDomain(), DiagramUIMessages.Commands_MoveElement, new EObjectAdapter((View) editPart.getModel()), normalPoint); + return new ICommandProxy(moveCommand); + } + return null; + } + + /** Return <tt>null</tt> to avoid handling the request. */ + @Override + protected Command getAlignCommand(AlignmentRequest request) { + return null; + } + + /** + * Erase the feedback link figure + * + * @see org.eclipse.gef.editpolicies.NonResizableEditPolicy#eraseChangeBoundsFeedback(org.eclipse.gef.requests.ChangeBoundsRequest) + */ + @Override + protected void eraseChangeBoundsFeedback(ChangeBoundsRequest request) { + super.eraseChangeBoundsFeedback(request); + if (linkFeedback != null) { + removeFeedback(linkFeedback); + } + linkFeedback = null; + } + + /** + * Create the feedback link figure + * + * @see org.eclipse.gef.editpolicies.NonResizableEditPolicy#createDragSourceFeedbackFigure() + */ + @Override + protected IFigure createDragSourceFeedbackFigure() { + IFigure feedback = super.createDragSourceFeedbackFigure(); + linkFeedback = new PolylineShape(); + linkFeedback.setLineWidth(1); + linkFeedback.setLineStyle(Graphics.LINE_DASHDOT); + linkFeedback.setForegroundColor(((IGraphicalEditPart) getHost()).getFigure().getForegroundColor()); + addFeedback(linkFeedback); + return feedback; + } + + /** + * Show link feedback + * + * @see org.eclipse.gmf.runtime.diagram.ui.editpolicies.BorderItemSelectionEditPolicy#showChangeBoundsFeedback(org.eclipse.gef.requests.ChangeBoundsRequest) + */ + @Override + protected void showChangeBoundsFeedback(org.eclipse.gef.requests.ChangeBoundsRequest request) { + if (getHost() instanceof IBorderItemEditPart) { + IBorderItemEditPart borderItemEP = (IBorderItemEditPart) getHost(); + IBorderItemLocator borderItemLocator = borderItemEP.getBorderItemLocator(); + if (borderItemLocator != null) { + IFigure feedback = getDragSourceFeedbackFigure(); + PrecisionRectangle rect = new PrecisionRectangle(getInitialFeedbackBounds().getCopy()); + getHostFigure().translateToAbsolute(rect); + rect.translate(request.getMoveDelta()); + rect.resize(request.getSizeDelta()); + getHostFigure().translateToRelative(rect); + Rectangle realLocation = borderItemLocator.getValidLocation(rect.getCopy(), borderItemEP.getFigure()); + getHostFigure().translateToAbsolute(realLocation); + feedback.translateToRelative(realLocation); + feedback.setBounds(realLocation); + } + } else { + super.showChangeBoundsFeedback(request); + } + // translate the feedback figure + IFigure p = getDragSourceFeedbackFigure(); + PrecisionRectangle rect = new PrecisionRectangle(getInitialFeedbackBounds().getCopy()); + getHostFigure().translateToAbsolute(rect); + rect.translate(request.getMoveDelta()); + rect.resize(request.getSizeDelta()); + p.translateToRelative(rect); + p.setBounds(rect); + Point referencePoint = getReferencePoint(request); + Point end = getLinkEndPoint(request, referencePoint); + linkFeedback.setEnd(end); + Point start = getLinkStartPoint(request, referencePoint, end); + if (start != null) { + linkFeedback.setStart(start); + } else { + linkFeedback.setStart(referencePoint); + } + }; + + /** + * Get the reference point at the center of the parent figure + * + * @param request + * change bounds request + * @return point + */ + private Point getReferencePoint(ChangeBoundsRequest request) { + Point refPoint = ((LabelEditPart) getHost()).getReferencePoint(); + Rectangle centerMain = null; + if (((IGraphicalEditPart) getHost().getParent()).getFigure() instanceof Connection) { + centerMain = new Rectangle(refPoint.x, refPoint.y, 0, 0); + } else { + centerMain = ((IGraphicalEditPart) getHost().getParent()).getFigure().getBounds().getCopy(); + centerMain.translate(centerMain.width / 2, centerMain.height / 2); + } + PrecisionRectangle ref = new PrecisionRectangle(centerMain); + getHostFigure().translateToAbsolute(ref); + getDragSourceFeedbackFigure().translateToRelative(ref); + return ref.getLocation(); + } + + /** + * Get the point for starting the link + * + * @param request + * change bounds request + * @param referencePoint + * the reference point at the center of the start figure + * @param endPoint + * the end point at the border of the end figure + * @return point where to start the link + */ + private Point getLinkStartPoint(ChangeBoundsRequest request, Point referencePoint, Point endPoint) { + Point u1 = referencePoint; + Point u2 = endPoint; + if (getHost().getParent() instanceof AbstractBorderedShapeEditPart) { + // the parent figure is a node : choose a point on its border + AbstractBorderedShapeEditPart parentPart = (AbstractBorderedShapeEditPart) getHost().getParent(); + IFigure fig = parentPart.getMainFigure(); + if (fig instanceof NodeFigure) { + PointList pointsList = ((NodeFigure) fig).getPolygonPoints().getCopy(); + // translate points relatively to drag feedback + fig.translateToAbsolute(pointsList); + getDragSourceFeedbackFigure().translateToRelative(pointsList); + return getIntersectionPoint(pointsList, u1, u2); + } + } + // either computation failed or the parent figure is a link + return referencePoint; + } + + /** + * Get the point for ending the link + * + * @param request + * change bounds request + * @param referencePoint + * the reference point at the center of the start figure + * @return point + */ + private Point getLinkEndPoint(ChangeBoundsRequest request, Point referencePoint) { + Rectangle rect = getDragSourceFeedbackFigure().getBounds(); + Point endPoint = getAppropriateBorderPoint(referencePoint, rect); + return endPoint; + } + + /** + * Get the point on the border intersection the segment + * + * @param polygonalBounds + * the list of points tracing the border + * @param insidePoint + * first segment extremity + * @param outsideExtremity + * second segment extremity + * @return the intersection point or null if none + */ + public static Point getIntersectionPoint(PointList polygonalBounds, Point insidePoint, Point outsideExtremity) { + Point intersection = null; + int i = 0; + while (intersection == null && i < polygonalBounds.size() - 1) { + Point v1 = polygonalBounds.getPoint(i).getCopy(); + Point v2 = polygonalBounds.getPoint(i + 1).getCopy(); + intersection = getIntersection(insidePoint, outsideExtremity, v1, v2); + i++; + } + return intersection; + } + + /** + * Get the point of the border which is the more appropriated to link to the + * reference point + * + * @param referencePoint + * point to refer to, which the link is directed to (not + * necessary an end of the link) + * @param border + * the border on which an anchoring point must be chosen + * @return a point of the border to use as link end + */ + public static Point getAppropriateBorderPoint(Point referencePoint, Rectangle border) { + Point midTop = new Point(border.x + border.width / 2, border.y); + Point midBottom = new Point(border.x + border.width / 2, border.y + border.height); + Point midLeft = new Point(border.x, border.y + border.height / 2); + Point midRight = new Point(border.x + border.width, border.y + border.height / 2); + Dimension diffTop = referencePoint.getDifference(midTop); + Dimension diffBottom = referencePoint.getDifference(midBottom); + Dimension diffRight = referencePoint.getDifference(midRight); + Dimension diffLeft = referencePoint.getDifference(midLeft); + Point startPoint = midBottom; + if (diffBottom.height > 0) { + // check if right or left is more appropriated + if (diffLeft.width < 0 && diffBottom.height < -diffLeft.width) { + startPoint = midLeft; + } else if (diffRight.width > 0 && diffBottom.height < diffRight.width) { + startPoint = midRight; + } else { + startPoint = midBottom; + } + } else if (diffTop.height < 0) { + // check if right or left is more appropriated + if (diffLeft.width < 0 && -diffTop.height < -diffLeft.width) { + startPoint = midLeft; + } else if (diffRight.width > 0 && -diffTop.height < diffRight.width) { + startPoint = midRight; + } else { + startPoint = midTop; + } + } else if (diffLeft.width < 0) { + startPoint = midLeft; + } else if (diffRight.width > 0) { + startPoint = midRight; + } + return startPoint; + } + + /** + * Get the intersection between segments joining the points + * + * @param u1 + * the first extremity of the u segment + * @param u2 + * the second extremity of the u segment + * @param v1 + * the first extremity of the v segment + * @param v2 + * the second extremity of the v segment + * @return the intersection point or null if none + */ + public static Point getIntersection(Point u1, Point u2, Point v1, Point v2) { + float denom = ((u2.y - u1.y) * (v2.x - v1.x)) - ((u2.x - u1.x) * (v2.y - v1.y)); + float nume_a = ((u2.x - u1.x) * (v1.y - u1.y)) - ((u2.y - u1.y) * (v1.x - u1.x)); + float nume_b = ((v2.x - v1.x) * (v1.y - u1.y)) - ((v2.y - v1.y) * (v1.x - u1.x)); + if (denom == 0.0f) { + return null; + } + float ua = nume_a / denom; + float ub = nume_b / denom; + if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) { + // Get the intersection point. + Float x = v1.x + ua * (v2.x - v1.x); + Float y = v1.y + ua * (v2.y - v1.y); + return new Point(x.intValue(), y.intValue()); + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/CompartmentXYLayoutEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/CompartmentXYLayoutEditPolicy.java index 58bb7d604f7..6772539b927 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/CompartmentXYLayoutEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/CompartmentXYLayoutEditPolicy.java @@ -1,100 +1,100 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.gef.GraphicalEditPart;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.XYLayoutEditPolicy;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.CommentEditPartCN;
-
-/**
- * This XY layout edit policy consults children parts for chosing a minimum
- * size.
- * <p/>
- * Special considerations made for reflowable edit parts, with minimum size depending on suggested width.
- */
-public class CompartmentXYLayoutEditPolicy extends XYLayoutEditPolicy {
-
- /**
- * Fix for #422827
- * <p/>
- * We would better override the Dimension.max() logic from the super class but it itself calls super.super so we can't easily do that.
- * <p/>
- * So we have to explicitly call {@link #getMinimumSizeForHint(GraphicalEditPart, Dimension)} and ensure that Dimension.max() logic in super-class does not affect results by returning something small from {@link #getMinimumSizeFor(GraphicalEditPart)}
- */
- @Override
- protected Object getConstraintFor(Request request, GraphicalEditPart child, Rectangle rect) {
- if (isReflowable(child) && request instanceof ChangeBoundsRequest) {
- ChangeBoundsRequest reqImpl = (ChangeBoundsRequest) request;
-
- Dimension sizeDelta = reqImpl.getSizeDelta();
- if (sizeDelta.width != 0 || sizeDelta.height != 0) {
- Dimension correctedMinSize = getMinimumSizeForHint(child, rect.getSize());
- rect.setSize(Dimension.max(correctedMinSize, rect.getSize()));
- }
- }
- return super.getConstraintFor(request, child, rect);
- }
-
- /**
- * Called for reflowable editpart and allows them to compute minimum height based on suggested width.
- *
- * @return minimum size computed by using the given width as a hint.
- */
- protected Dimension getMinimumSizeForHint(GraphicalEditPart child, Dimension hint) {
- IFigure figure = child.getFigure();
- if (figure == null) {
- return super.getMinimumSizeFor(child);
- }
- return figure.getMinimumSize(hint.width, -1);
- }
-
- /**
- * Return true if editpart can reflow, that is if it minimum size
- * is not static but depends on the width.
- */
- protected boolean isReflowable(GraphicalEditPart editPart) {
- // for now we can check it this way to fix #422827
- return editPart instanceof CommentEditPartCN;
- // more general check will be available after fixing #429197
- }
-
- /**
- * Get the static minimum size from child edit part rather than imposing a constant one.
- * <p/>
- * Bug #422827 is about this method called for reflowable comments, so the new version of this class should call {@link #getMinimumSizeForHint(GraphicalEditPart, Dimension)} instead.
- *
- * @see org.eclipse.gef.editpolicies.XYLayoutEditPolicy#getMinimumSizeFor(org.eclipse.gef.GraphicalEditPart)
- * @param child
- * the child
- * @return the minumum size
- */
- @Override
- protected Dimension getMinimumSizeFor(GraphicalEditPart child) {
- if (isReflowable(child)) {
- // call from super class, we need to return something very small
- // because this class will call getMinimumSizeForHint() anyway
- return new Dimension(5, 5);
- }
- if (child.getFigure() != null) {
- return child.getFigure().getMinimumSize();
- }
- return super.getMinimumSizeFor(child);
- }
-
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.gef.GraphicalEditPart; +import org.eclipse.gef.Request; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.XYLayoutEditPolicy; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.CommentEditPartCN; + +/** + * This XY layout edit policy consults children parts for chosing a minimum + * size. + * <p/> + * Special considerations made for reflowable edit parts, with minimum size depending on suggested width. + */ +public class CompartmentXYLayoutEditPolicy extends XYLayoutEditPolicy { + + /** + * Fix for #422827 + * <p/> + * We would better override the Dimension.max() logic from the super class but it itself calls super.super so we can't easily do that. + * <p/> + * So we have to explicitly call {@link #getMinimumSizeForHint(GraphicalEditPart, Dimension)} and ensure that Dimension.max() logic in super-class does not affect results by returning something small from {@link #getMinimumSizeFor(GraphicalEditPart)} + */ + @Override + protected Object getConstraintFor(Request request, GraphicalEditPart child, Rectangle rect) { + if (isReflowable(child) && request instanceof ChangeBoundsRequest) { + ChangeBoundsRequest reqImpl = (ChangeBoundsRequest) request; + + Dimension sizeDelta = reqImpl.getSizeDelta(); + if (sizeDelta.width != 0 || sizeDelta.height != 0) { + Dimension correctedMinSize = getMinimumSizeForHint(child, rect.getSize()); + rect.setSize(Dimension.max(correctedMinSize, rect.getSize())); + } + } + return super.getConstraintFor(request, child, rect); + } + + /** + * Called for reflowable editpart and allows them to compute minimum height based on suggested width. + * + * @return minimum size computed by using the given width as a hint. + */ + protected Dimension getMinimumSizeForHint(GraphicalEditPart child, Dimension hint) { + IFigure figure = child.getFigure(); + if (figure == null) { + return super.getMinimumSizeFor(child); + } + return figure.getMinimumSize(hint.width, -1); + } + + /** + * Return true if editpart can reflow, that is if it minimum size + * is not static but depends on the width. + */ + protected boolean isReflowable(GraphicalEditPart editPart) { + // for now we can check it this way to fix #422827 + return editPart instanceof CommentEditPartCN; + // more general check will be available after fixing #429197 + } + + /** + * Get the static minimum size from child edit part rather than imposing a constant one. + * <p/> + * Bug #422827 is about this method called for reflowable comments, so the new version of this class should call {@link #getMinimumSizeForHint(GraphicalEditPart, Dimension)} instead. + * + * @see org.eclipse.gef.editpolicies.XYLayoutEditPolicy#getMinimumSizeFor(org.eclipse.gef.GraphicalEditPart) + * @param child + * the child + * @return the minumum size + */ + @Override + protected Dimension getMinimumSizeFor(GraphicalEditPart child) { + if (isReflowable(child)) { + // call from super class, we need to return something very small + // because this class will call getMinimumSizeForHint() anyway + return new Dimension(5, 5); + } + if (child.getFigure() != null) { + return child.getFigure().getMinimumSize(); + } + return super.getMinimumSizeFor(child); + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/CustomUMLBaseItemSemanticPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/CustomUMLBaseItemSemanticPolicy.java index 67d52f92d5d..5fc05e6930c 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/CustomUMLBaseItemSemanticPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/CustomUMLBaseItemSemanticPolicy.java @@ -1,10 +1,10 @@ -package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.gmf.runtime.emf.type.core.IElementType;
-
-public class CustomUMLBaseItemSemanticPolicy extends UMLBaseItemSemanticEditPolicy {
-
- protected CustomUMLBaseItemSemanticPolicy(IElementType elementType) {
- super(elementType);
- }
-}
+package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.gmf.runtime.emf.type.core.IElementType; + +public class CustomUMLBaseItemSemanticPolicy extends UMLBaseItemSemanticEditPolicy { + + protected CustomUMLBaseItemSemanticPolicy(IElementType elementType) { + super(elementType); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/DeleteActionViewEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/DeleteActionViewEditPolicy.java index 666c26c8b9c..51e50a17535 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/DeleteActionViewEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/DeleteActionViewEditPolicy.java @@ -1,105 +1,105 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.requests.GroupRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionNodeEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ViewComponentEditPolicy;
-import org.eclipse.uml2.uml.Action;
-
-/**
- * This edit policy deletes linked local conditions view when an action view is
- * deleted.
- */
-public class DeleteActionViewEditPolicy extends ViewComponentEditPolicy {
-
- /**
- * Returns true when the request is a graphical delete
- *
- * @see org.eclipse.gef.EditPolicy#understandsRequest(Request)
- * @return true for a graphical delete request
- */
- @Override
- public boolean understandsRequest(Request req) {
- return org.eclipse.gef.RequestConstants.REQ_DELETE.equals(req.getType());
- }
-
- /**
- * Returns a command for graphical delete (with local conditions also
- * deleted).
- *
- * @see org.eclipse.gef.EditPolicy#getCommand(Request)
- * @return the command or null
- */
- @Override
- public Command getCommand(Request request) {
- if (org.eclipse.gef.RequestConstants.REQ_DELETE.equals(request.getType())) {
- if (request instanceof GroupRequest) {
- // List of parts from the request is not up to date. Consider
- // the host only.
- List<?> parts = Collections.singletonList(getHost());
- ((GroupRequest) request).setEditParts(getHost());
- // inspect the list of parts to add linked local conditions
- List<EditPart> partsToAdd = getListOfLinkedLocalConditionsParts(parts);
- ((GroupRequest) request).getEditParts().addAll(partsToAdd);
- return getDeleteCommand((GroupRequest) request);
- }
- }
- return null;
- }
-
- /**
- * Get the list of local condition parts linked to a part of the list
- *
- * @param partsToExplore
- * list of parts to explore
- * @return list of local condition parts
- */
- private List<EditPart> getListOfLinkedLocalConditionsParts(List<?> partsToExplore) {
- List<EditPart> result = new LinkedList<EditPart>();
- for (Object part : partsToExplore) {
- if (part instanceof AbstractBorderedShapeEditPart) {
- EObject element = ((AbstractBorderedShapeEditPart) part).resolveSemanticElement();
- if (element instanceof Action) {
- Action action = (Action) element;
- List<?> connections = ((AbstractBorderedShapeEditPart) part).getSourceConnections();
- if (connections != null) {
- for (Object connection : connections) {
- if (connection instanceof ConnectionNodeEditPart) {
- EditPart target = ((ConnectionNodeEditPart) connection).getTarget();
- if (target instanceof ShapeNodeEditPart) {
- EObject linkedElement = ((ShapeNodeEditPart) target).resolveSemanticElement();
- if (action.getLocalPreconditions().contains(linkedElement) || action.getLocalPostconditions().contains(linkedElement)) {
- result.add(target);
- }
- }
- }
- }
- }
- }
- }
- }
- return result;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.requests.GroupRequest; +import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderedShapeEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionNodeEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ViewComponentEditPolicy; +import org.eclipse.uml2.uml.Action; + +/** + * This edit policy deletes linked local conditions view when an action view is + * deleted. + */ +public class DeleteActionViewEditPolicy extends ViewComponentEditPolicy { + + /** + * Returns true when the request is a graphical delete + * + * @see org.eclipse.gef.EditPolicy#understandsRequest(Request) + * @return true for a graphical delete request + */ + @Override + public boolean understandsRequest(Request req) { + return org.eclipse.gef.RequestConstants.REQ_DELETE.equals(req.getType()); + } + + /** + * Returns a command for graphical delete (with local conditions also + * deleted). + * + * @see org.eclipse.gef.EditPolicy#getCommand(Request) + * @return the command or null + */ + @Override + public Command getCommand(Request request) { + if (org.eclipse.gef.RequestConstants.REQ_DELETE.equals(request.getType())) { + if (request instanceof GroupRequest) { + // List of parts from the request is not up to date. Consider + // the host only. + List<?> parts = Collections.singletonList(getHost()); + ((GroupRequest) request).setEditParts(getHost()); + // inspect the list of parts to add linked local conditions + List<EditPart> partsToAdd = getListOfLinkedLocalConditionsParts(parts); + ((GroupRequest) request).getEditParts().addAll(partsToAdd); + return getDeleteCommand((GroupRequest) request); + } + } + return null; + } + + /** + * Get the list of local condition parts linked to a part of the list + * + * @param partsToExplore + * list of parts to explore + * @return list of local condition parts + */ + private List<EditPart> getListOfLinkedLocalConditionsParts(List<?> partsToExplore) { + List<EditPart> result = new LinkedList<EditPart>(); + for (Object part : partsToExplore) { + if (part instanceof AbstractBorderedShapeEditPart) { + EObject element = ((AbstractBorderedShapeEditPart) part).resolveSemanticElement(); + if (element instanceof Action) { + Action action = (Action) element; + List<?> connections = ((AbstractBorderedShapeEditPart) part).getSourceConnections(); + if (connections != null) { + for (Object connection : connections) { + if (connection instanceof ConnectionNodeEditPart) { + EditPart target = ((ConnectionNodeEditPart) connection).getTarget(); + if (target instanceof ShapeNodeEditPart) { + EObject linkedElement = ((ShapeNodeEditPart) target).resolveSemanticElement(); + if (action.getLocalPreconditions().contains(linkedElement) || action.getLocalPostconditions().contains(linkedElement)) { + result.add(target); + } + } + } + } + } + } + } + } + return result; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ForkJoinResizeEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ForkJoinResizeEditPolicy.java index 905ec59877c..182750f6e37 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ForkJoinResizeEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ForkJoinResizeEditPolicy.java @@ -1,54 +1,54 @@ -/*****************************************************************************
- * Copyright (c) 2010 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation
- */
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.gef.RequestConstants;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ResizableShapeEditPolicy;
-import org.eclipse.papyrus.uml.diagram.common.editparts.UMLNodeEditPart;
-
-/**
- * A resizable editpolicy for shape editparts. It ensure that the resize keeps
- * the shape as a fork or a join
- *
- * @see ResizableShapeEditPolicy
- */
-public class ForkJoinResizeEditPolicy extends ResizableShapeEditPolicy {
-
- /**
- * Shows or updates feedback for a change bounds request. The request is
- * updated by the way so that the shape stays a square.
- *
- * @param request
- * the request
- */
- @Override
- protected void showChangeBoundsFeedback(ChangeBoundsRequest request) {
- // adapt the request for a square resize
- if (request.getType().equals(RequestConstants.REQ_RESIZE) && getHost() instanceof UMLNodeEditPart) {
- Dimension dim = getHostFigure().getBounds().getSize();
- Dimension preferedDim = ((UMLNodeEditPart) getHost()).getPrimaryShape().getPreferredSize();
- Dimension delta = request.getSizeDelta();
- int dH = delta.height;
- int dW = delta.width;
- if (dH > dW) {
- dW = preferedDim.width - dim.width;
- } else {
- dH = preferedDim.height - dim.height;
- }
- request.setSizeDelta(new Dimension(dW, dH));
- }
- super.showChangeBoundsFeedback(request);
- }
-}
+/***************************************************************************** + * Copyright (c) 2010 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation + */ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.gef.RequestConstants; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ResizableShapeEditPolicy; +import org.eclipse.papyrus.uml.diagram.common.editparts.UMLNodeEditPart; + +/** + * A resizable editpolicy for shape editparts. It ensure that the resize keeps + * the shape as a fork or a join + * + * @see ResizableShapeEditPolicy + */ +public class ForkJoinResizeEditPolicy extends ResizableShapeEditPolicy { + + /** + * Shows or updates feedback for a change bounds request. The request is + * updated by the way so that the shape stays a square. + * + * @param request + * the request + */ + @Override + protected void showChangeBoundsFeedback(ChangeBoundsRequest request) { + // adapt the request for a square resize + if (request.getType().equals(RequestConstants.REQ_RESIZE) && getHost() instanceof UMLNodeEditPart) { + Dimension dim = getHostFigure().getBounds().getSize(); + Dimension preferedDim = ((UMLNodeEditPart) getHost()).getPrimaryShape().getPreferredSize(); + Dimension delta = request.getSizeDelta(); + int dH = delta.height; + int dW = delta.width; + if (dH > dW) { + dW = preferedDim.width - dim.width; + } else { + dH = preferedDim.height - dim.height; + } + request.setSizeDelta(new Dimension(dW, dH)); + } + super.showChangeBoundsFeedback(request); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/InterruptibleEdgeEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/InterruptibleEdgeEditPolicy.java index acfa2e20742..5d323627bcd 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/InterruptibleEdgeEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/InterruptibleEdgeEditPolicy.java @@ -1,235 +1,235 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
-import org.eclipse.emf.edit.domain.EditingDomain;
-import org.eclipse.emf.transaction.Transaction;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.emf.workspace.AbstractEMFOperation;
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.EditPartViewer;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.editpolicies.AbstractEditPolicy;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.common.core.util.Log;
-import org.eclipse.gmf.runtime.common.core.util.StringStatics;
-import org.eclipse.gmf.runtime.common.core.util.Trace;
-import org.eclipse.gmf.runtime.diagram.core.services.ViewService;
-import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
-import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIDebugOptions;
-import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin;
-import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIStatusCodes;
-import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer;
-import org.eclipse.gmf.runtime.diagram.ui.util.EditPartUtil;
-import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.gmf.runtime.notation.Node;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLVisualIDRegistry;
-import org.eclipse.uml2.uml.ActivityEdge;
-
-/**
- * InterruptibleEdgeEditPolicy handle all action relative to interruptible Edge.
- * WARNING : All EditPart where this EditPolicy is installed has to implement {@link InterruptibleEdge}
- *
- * @author arthur daussy
- *
- */
-public class InterruptibleEdgeEditPolicy extends AbstractEditPolicy {
-
- /** constant for this edit policy role */
- public static String INTERRUPTIBLE_ICON_POLICY = "interruptibleIconPolicy";
-
- /**
- * Validate the consistency of the view of the Interruptible Edge Icon
- */
- @Override
- public void activate() {
- validateConsistency();
- super.activate();
- }
-
- /**
- * Validate the Consistency of the InterruptibleEdgeIcon
- */
- protected void validateConsistency() {
- try {
- final IGraphicalEditPart graphicalHost = (IGraphicalEditPart) getHost();
- final InterruptibleEdge interruptibleEdge = (InterruptibleEdge) getHost();
- EObject resolveSemanticElement = graphicalHost.resolveSemanticElement();
- ActivityEdge activityEdgeAux;
- if (resolveSemanticElement instanceof ActivityEdge) {
- activityEdgeAux = (ActivityEdge) resolveSemanticElement;
- } else {
- activityEdgeAux = null;
- }
- final ActivityEdge activityEdge = activityEdgeAux;
- final View interruptbleEdgeIcon = getInterruptbleEdgeIcon(graphicalHost, interruptibleEdge);
- // If property == null and there is an view => delete
- if (activityEdge != null) {
- if (activityEdge.getInterrupts() == null && interruptbleEdgeIcon != null) {
- ICommand destroyCommand = new AbstractTransactionalCommand(graphicalHost.getEditingDomain(), "Destroy Interruptible Edge Icon", null) {
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- ViewUtil.destroy(interruptbleEdgeIcon);
- return CommandResult.newOKCommandResult();
- }
- };
- executeCommand(new ICommandProxy(destroyCommand));
- }
- // If property is set and no view exist => create a view
- if (activityEdge.getInterrupts() != null && interruptbleEdgeIcon == null) {
- ICommand createCommand = new AbstractTransactionalCommand(graphicalHost.getEditingDomain(), "Create Interruptible Edge Icon", null) {
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- Object model = graphicalHost.getModel();
- if (model != null) {
- Node node = ViewService.createNode((View) model, UMLVisualIDRegistry.getType(interruptibleEdge.getInterruptibleEdgeIconVisualID()), UMLDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);
- if (node != null) {
- return CommandResult.newOKCommandResult(node);
- } else {
- return CommandResult.newErrorCommandResult("Unable to create the view for Interruptible Edge label");
- }
- }
- return null;
- }
- };
- executeCommand(new ICommandProxy(createCommand));
- }
- }
- } catch (ClassCastException e) {
- throw new RuntimeException("The host of InterruptibleEdgeEditPolicy should implement IGraphicalEditPart and InterruptibleEdge which refer to an ActivityEdge");//
- }
- }
-
- /**
- * Retreive the view corresponding to interruptible edge icon
- */
- private View getInterruptbleEdgeIcon(IGraphicalEditPart graphicalHost, InterruptibleEdge interruptibleEdge) {
- View view = graphicalHost.getNotationView();
- if (view != null) {
- return ViewUtil.getChildBySemanticHint(view, String.valueOf(interruptibleEdge.getInterruptibleEdgeIconVisualID()));
- }
- return null;
- }
-
- /**
- * Executes the supplied command inside an <code>unchecked action</code> COPIED FROM CANONICAL EDIT POLICY
- *
- * @param cmd
- * command that can be executed (i.e., cmd.canExecute() == true)
- */
- protected void executeCommand(final Command cmd) {
- Map<String, Boolean> options = null;
- EditPart ep = getHost();
- boolean isActivating = true;
- // use the viewer to determine if we are still initializing the diagram
- // do not use the DiagramEditPart.isActivating since ConnectionEditPart's
- // parent will not be a diagram edit part
- EditPartViewer viewer = ep.getViewer();
- if (viewer instanceof DiagramGraphicalViewer) {
- isActivating = ((DiagramGraphicalViewer) viewer).isInitializing();
- }
- if (isActivating || !EditPartUtil.isWriteTransactionInProgress((IGraphicalEditPart) getHost(), false, false)) {
- options = Collections.singletonMap(Transaction.OPTION_UNPROTECTED, Boolean.TRUE);
- }
- AbstractEMFOperation operation = new AbstractEMFOperation(((IGraphicalEditPart) getHost()).getEditingDomain(), StringStatics.BLANK, options) {
-
- @Override
- protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- cmd.execute();
- return Status.OK_STATUS;
- }
- };
- try {
- operation.execute(new NullProgressMonitor(), null);
- } catch (ExecutionException e) {
- Trace.catching(DiagramUIPlugin.getInstance(), DiagramUIDebugOptions.EXCEPTIONS_CATCHING, getClass(), "executeCommand", e); //$NON-NLS-1$
- Log.warning(DiagramUIPlugin.getInstance(), DiagramUIStatusCodes.IGNORED_EXCEPTION_WARNING, "executeCommand", e); //$NON-NLS-1$
- }
- }
-
- @Override
- public EditPart getTargetEditPart(Request request) {
- return getHost();
- }
-
- /**
- * Get the type of the node to create
- *
- * @return
- */
- protected String getInterruptibleEdgeIconID() {
- return getInterruptibleEdgeIcon().getInterruptibleEdgeIconVisualID();
- }
-
- /**
- * Get the interruptible Edge
- */
- protected InterruptibleEdge getInterruptibleEdgeIcon() {
- return ((InterruptibleEdge) getHost());
- }
-
- /**
- * Get the Actvity Edge
- */
- protected ActivityEdge getActivtyEdge() {
- EObject eObject = ((IGraphicalEditPart) getHost()).resolveSemanticElement();
- if (eObject instanceof ActivityEdge) {
- return (ActivityEdge) eObject;
- }
- return null;
- }
-
- /**
- * Get the {@link TransactionalEditingDomain}
- *
- * @return
- */
- protected TransactionalEditingDomain getEditingDomain() {
- EditPart getHost = getHost();
- if (getHost instanceof GraphicalEditPart) {
- GraphicalEditPart host = (GraphicalEditPart) getHost;
- return host.getEditingDomain();
- }
- Object view = getHost.getModel();
- if (view instanceof EObject) {
- EditingDomain editinDomain = AdapterFactoryEditingDomain.getEditingDomainFor((EObject) view);
- if (editinDomain instanceof TransactionalEditingDomain) {
- return (TransactionalEditingDomain) editinDomain;
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import java.util.Collections; +import java.util.Map; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Status; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; +import org.eclipse.emf.edit.domain.EditingDomain; +import org.eclipse.emf.transaction.Transaction; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.emf.workspace.AbstractEMFOperation; +import org.eclipse.gef.EditPart; +import org.eclipse.gef.EditPartViewer; +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.editpolicies.AbstractEditPolicy; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.common.core.util.Log; +import org.eclipse.gmf.runtime.common.core.util.StringStatics; +import org.eclipse.gmf.runtime.common.core.util.Trace; +import org.eclipse.gmf.runtime.diagram.core.services.ViewService; +import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil; +import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIDebugOptions; +import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin; +import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIStatusCodes; +import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramGraphicalViewer; +import org.eclipse.gmf.runtime.diagram.ui.util.EditPartUtil; +import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.gmf.runtime.notation.Node; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLVisualIDRegistry; +import org.eclipse.uml2.uml.ActivityEdge; + +/** + * InterruptibleEdgeEditPolicy handle all action relative to interruptible Edge. + * WARNING : All EditPart where this EditPolicy is installed has to implement {@link InterruptibleEdge} + * + * @author arthur daussy + * + */ +public class InterruptibleEdgeEditPolicy extends AbstractEditPolicy { + + /** constant for this edit policy role */ + public static String INTERRUPTIBLE_ICON_POLICY = "interruptibleIconPolicy"; + + /** + * Validate the consistency of the view of the Interruptible Edge Icon + */ + @Override + public void activate() { + validateConsistency(); + super.activate(); + } + + /** + * Validate the Consistency of the InterruptibleEdgeIcon + */ + protected void validateConsistency() { + try { + final IGraphicalEditPart graphicalHost = (IGraphicalEditPart) getHost(); + final InterruptibleEdge interruptibleEdge = (InterruptibleEdge) getHost(); + EObject resolveSemanticElement = graphicalHost.resolveSemanticElement(); + ActivityEdge activityEdgeAux; + if (resolveSemanticElement instanceof ActivityEdge) { + activityEdgeAux = (ActivityEdge) resolveSemanticElement; + } else { + activityEdgeAux = null; + } + final ActivityEdge activityEdge = activityEdgeAux; + final View interruptbleEdgeIcon = getInterruptbleEdgeIcon(graphicalHost, interruptibleEdge); + // If property == null and there is an view => delete + if (activityEdge != null) { + if (activityEdge.getInterrupts() == null && interruptbleEdgeIcon != null) { + ICommand destroyCommand = new AbstractTransactionalCommand(graphicalHost.getEditingDomain(), "Destroy Interruptible Edge Icon", null) { + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + ViewUtil.destroy(interruptbleEdgeIcon); + return CommandResult.newOKCommandResult(); + } + }; + executeCommand(new ICommandProxy(destroyCommand)); + } + // If property is set and no view exist => create a view + if (activityEdge.getInterrupts() != null && interruptbleEdgeIcon == null) { + ICommand createCommand = new AbstractTransactionalCommand(graphicalHost.getEditingDomain(), "Create Interruptible Edge Icon", null) { + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + Object model = graphicalHost.getModel(); + if (model != null) { + Node node = ViewService.createNode((View) model, UMLVisualIDRegistry.getType(interruptibleEdge.getInterruptibleEdgeIconVisualID()), UMLDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); + if (node != null) { + return CommandResult.newOKCommandResult(node); + } else { + return CommandResult.newErrorCommandResult("Unable to create the view for Interruptible Edge label"); + } + } + return null; + } + }; + executeCommand(new ICommandProxy(createCommand)); + } + } + } catch (ClassCastException e) { + throw new RuntimeException("The host of InterruptibleEdgeEditPolicy should implement IGraphicalEditPart and InterruptibleEdge which refer to an ActivityEdge");// + } + } + + /** + * Retreive the view corresponding to interruptible edge icon + */ + private View getInterruptbleEdgeIcon(IGraphicalEditPart graphicalHost, InterruptibleEdge interruptibleEdge) { + View view = graphicalHost.getNotationView(); + if (view != null) { + return ViewUtil.getChildBySemanticHint(view, String.valueOf(interruptibleEdge.getInterruptibleEdgeIconVisualID())); + } + return null; + } + + /** + * Executes the supplied command inside an <code>unchecked action</code> COPIED FROM CANONICAL EDIT POLICY + * + * @param cmd + * command that can be executed (i.e., cmd.canExecute() == true) + */ + protected void executeCommand(final Command cmd) { + Map<String, Boolean> options = null; + EditPart ep = getHost(); + boolean isActivating = true; + // use the viewer to determine if we are still initializing the diagram + // do not use the DiagramEditPart.isActivating since ConnectionEditPart's + // parent will not be a diagram edit part + EditPartViewer viewer = ep.getViewer(); + if (viewer instanceof DiagramGraphicalViewer) { + isActivating = ((DiagramGraphicalViewer) viewer).isInitializing(); + } + if (isActivating || !EditPartUtil.isWriteTransactionInProgress((IGraphicalEditPart) getHost(), false, false)) { + options = Collections.singletonMap(Transaction.OPTION_UNPROTECTED, Boolean.TRUE); + } + AbstractEMFOperation operation = new AbstractEMFOperation(((IGraphicalEditPart) getHost()).getEditingDomain(), StringStatics.BLANK, options) { + + @Override + protected IStatus doExecute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + cmd.execute(); + return Status.OK_STATUS; + } + }; + try { + operation.execute(new NullProgressMonitor(), null); + } catch (ExecutionException e) { + Trace.catching(DiagramUIPlugin.getInstance(), DiagramUIDebugOptions.EXCEPTIONS_CATCHING, getClass(), "executeCommand", e); //$NON-NLS-1$ + Log.warning(DiagramUIPlugin.getInstance(), DiagramUIStatusCodes.IGNORED_EXCEPTION_WARNING, "executeCommand", e); //$NON-NLS-1$ + } + } + + @Override + public EditPart getTargetEditPart(Request request) { + return getHost(); + } + + /** + * Get the type of the node to create + * + * @return + */ + protected String getInterruptibleEdgeIconID() { + return getInterruptibleEdgeIcon().getInterruptibleEdgeIconVisualID(); + } + + /** + * Get the interruptible Edge + */ + protected InterruptibleEdge getInterruptibleEdgeIcon() { + return ((InterruptibleEdge) getHost()); + } + + /** + * Get the Actvity Edge + */ + protected ActivityEdge getActivtyEdge() { + EObject eObject = ((IGraphicalEditPart) getHost()).resolveSemanticElement(); + if (eObject instanceof ActivityEdge) { + return (ActivityEdge) eObject; + } + return null; + } + + /** + * Get the {@link TransactionalEditingDomain} + * + * @return + */ + protected TransactionalEditingDomain getEditingDomain() { + EditPart getHost = getHost(); + if (getHost instanceof GraphicalEditPart) { + GraphicalEditPart host = (GraphicalEditPart) getHost; + return host.getEditingDomain(); + } + Object view = getHost.getModel(); + if (view instanceof EObject) { + EditingDomain editinDomain = AdapterFactoryEditingDomain.getEditingDomainFor((EObject) view); + if (editinDomain instanceof TransactionalEditingDomain) { + return (TransactionalEditingDomain) editinDomain; + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/MaskManagedPinEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/MaskManagedPinEditPolicy.java index 89125e5ce72..c6858765ba1 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/MaskManagedPinEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/MaskManagedPinEditPolicy.java @@ -1,63 +1,63 @@ -/*****************************************************************************
- * Copyright (c) 2009 CEA LIST.
- *
- * 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:
- * Remi Schnekenburger (CEA LIST) remi.schnekenburger@cea.fr - Initial API and implementation
- * Nizar GUEDIDI (CEA LIST) - Update getUMLElement()
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Map;
-
-import org.eclipse.gef.GraphicalEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.helper.PinLabelHelper;
-import org.eclipse.papyrus.uml.diagram.common.editpolicies.AbstractMaskManagedEditPolicy;
-import org.eclipse.papyrus.uml.tools.utils.ICustomAppearance;
-import org.eclipse.uml2.uml.Pin;
-
-public class MaskManagedPinEditPolicy extends AbstractMaskManagedEditPolicy {
-
- public MaskManagedPinEditPolicy() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Collection<String> getDefaultDisplayValue() {
- return Arrays.asList(ICustomAppearance.DISP_NAME);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Map<String, String> getMasks() {
- return PinLabelHelper.getInstance().getMasks();
- }
-
- /**
- * {@inheritedDoc}
- */
- @Override
- public Pin getUMLElement() {
- return PinLabelHelper.getInstance().getUMLElement((GraphicalEditPart) getHost());
- }
-
- /**
- * {@inheritedDoc}
- */
- @Override
- public void refreshDisplay() {
- PinLabelHelper.getInstance().refreshEditPartDisplay((GraphicalEditPart) getHost());
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 CEA LIST. + * + * 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: + * Remi Schnekenburger (CEA LIST) remi.schnekenburger@cea.fr - Initial API and implementation + * Nizar GUEDIDI (CEA LIST) - Update getUMLElement() + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; + +import org.eclipse.gef.GraphicalEditPart; +import org.eclipse.papyrus.uml.diagram.activity.helper.PinLabelHelper; +import org.eclipse.papyrus.uml.diagram.common.editpolicies.AbstractMaskManagedEditPolicy; +import org.eclipse.papyrus.uml.tools.utils.ICustomAppearance; +import org.eclipse.uml2.uml.Pin; + +public class MaskManagedPinEditPolicy extends AbstractMaskManagedEditPolicy { + + public MaskManagedPinEditPolicy() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public Collection<String> getDefaultDisplayValue() { + return Arrays.asList(ICustomAppearance.DISP_NAME); + } + + /** + * {@inheritDoc} + */ + @Override + public Map<String, String> getMasks() { + return PinLabelHelper.getInstance().getMasks(); + } + + /** + * {@inheritedDoc} + */ + @Override + public Pin getUMLElement() { + return PinLabelHelper.getInstance().getUMLElement((GraphicalEditPart) getHost()); + } + + /** + * {@inheritedDoc} + */ + @Override + public void refreshDisplay() { + PinLabelHelper.getInstance().refreshEditPartDisplay((GraphicalEditPart) getHost()); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/NoDeleteFromDiagramEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/NoDeleteFromDiagramEditPolicy.java index 3321ebac34f..fc5dc68386f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/NoDeleteFromDiagramEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/NoDeleteFromDiagramEditPolicy.java @@ -1,48 +1,48 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.commands.UnexecutableCommand;
-import org.eclipse.gef.editpolicies.AbstractEditPolicy;
-
-/**
- * This edit policy disables the graphical deletion of a diagram element.
- */
-public class NoDeleteFromDiagramEditPolicy extends AbstractEditPolicy {
-
- /**
- * Returns true when the request is a graphical delete
- *
- * @see org.eclipse.gef.EditPolicy#understandsRequest(Request)
- */
- @Override
- public boolean understandsRequest(Request req) {
- return org.eclipse.gef.RequestConstants.REQ_DELETE.equals(req.getType());
- }
-
- /**
- * Returns an unexecutable command for graphical delete.
- *
- * @see org.eclipse.gef.EditPolicy#getCommand(Request)
- */
- @Override
- public Command getCommand(Request request) {
- if (org.eclipse.gef.RequestConstants.REQ_DELETE.equals(request.getType())) {
- return UnexecutableCommand.INSTANCE;
- }
- return super.getCommand(request);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.commands.UnexecutableCommand; +import org.eclipse.gef.editpolicies.AbstractEditPolicy; + +/** + * This edit policy disables the graphical deletion of a diagram element. + */ +public class NoDeleteFromDiagramEditPolicy extends AbstractEditPolicy { + + /** + * Returns true when the request is a graphical delete + * + * @see org.eclipse.gef.EditPolicy#understandsRequest(Request) + */ + @Override + public boolean understandsRequest(Request req) { + return org.eclipse.gef.RequestConstants.REQ_DELETE.equals(req.getType()); + } + + /** + * Returns an unexecutable command for graphical delete. + * + * @see org.eclipse.gef.EditPolicy#getCommand(Request) + */ + @Override + public Command getCommand(Request request) { + if (org.eclipse.gef.RequestConstants.REQ_DELETE.equals(request.getType())) { + return UnexecutableCommand.INSTANCE; + } + return super.getCommand(request); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/NoDirectEditFromDiagramEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/NoDirectEditFromDiagramEditPolicy.java index e1b18efdcd3..c43d8fae312 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/NoDirectEditFromDiagramEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/NoDirectEditFromDiagramEditPolicy.java @@ -1,46 +1,46 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.commands.UnexecutableCommand;
-import org.eclipse.gef.editpolicies.AbstractEditPolicy;
-
-public class NoDirectEditFromDiagramEditPolicy extends AbstractEditPolicy {
-
- /**
- * Returns true when the request is a graphical delete
- *
- * @see org.eclipse.gef.EditPolicy#understandsRequest(Request)
- */
- @Override
- public boolean understandsRequest(Request req) {
- return org.eclipse.gef.RequestConstants.REQ_DIRECT_EDIT.equals(req.getType());
- }
-
- /**
- * Returns an unexecutable command for graphical delete.
- *
- * @see org.eclipse.gef.EditPolicy#getCommand(Request)
- */
- @Override
- public Command getCommand(Request request) {
- if (org.eclipse.gef.RequestConstants.REQ_DIRECT_EDIT.equals(request.getType())) {
- return UnexecutableCommand.INSTANCE;
- }
- return super.getCommand(request);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.commands.UnexecutableCommand; +import org.eclipse.gef.editpolicies.AbstractEditPolicy; + +public class NoDirectEditFromDiagramEditPolicy extends AbstractEditPolicy { + + /** + * Returns true when the request is a graphical delete + * + * @see org.eclipse.gef.EditPolicy#understandsRequest(Request) + */ + @Override + public boolean understandsRequest(Request req) { + return org.eclipse.gef.RequestConstants.REQ_DIRECT_EDIT.equals(req.getType()); + } + + /** + * Returns an unexecutable command for graphical delete. + * + * @see org.eclipse.gef.EditPolicy#getCommand(Request) + */ + @Override + public Command getCommand(Request request) { + if (org.eclipse.gef.RequestConstants.REQ_DIRECT_EDIT.equals(request.getType())) { + return UnexecutableCommand.INSTANCE; + } + return super.getCommand(request); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PapyrusUnmovableShapeEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PapyrusUnmovableShapeEditPolicy.java index 530f077e8b9..da730acbb16 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PapyrusUnmovableShapeEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PapyrusUnmovableShapeEditPolicy.java @@ -1,41 +1,41 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy - arthur.daussy@atos.net - Bug 368972 - [ActivityDiagram] Prevent to move root Activity Figure and select root Activity Compartment
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.gef.Request;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.UnmovableShapeEditPolicy;
-
-/**
- * Erase all movement functionality
- *
- * @author arthur daussy
- *
- */
-public class PapyrusUnmovableShapeEditPolicy extends UnmovableShapeEditPolicy {
-
- @Override
- protected IFigure createDragSourceFeedbackFigure() {
- return null;
- }
-
- @Override
- public void eraseSourceFeedback(Request request) {
- }
-
- @Override
- public void showSourceFeedback(Request request) {
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy - arthur.daussy@atos.net - Bug 368972 - [ActivityDiagram] Prevent to move root Activity Figure and select root Activity Compartment + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.gef.Request; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.UnmovableShapeEditPolicy; + +/** + * Erase all movement functionality + * + * @author arthur daussy + * + */ +public class PapyrusUnmovableShapeEditPolicy extends UnmovableShapeEditPolicy { + + @Override + protected IFigure createDragSourceFeedbackFigure() { + return null; + } + + @Override + public void eraseSourceFeedback(Request request) { + } + + @Override + public void showSourceFeedback(Request request) { + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PinAndEdgeCreationInCompartmentEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PinAndEdgeCreationInCompartmentEditPolicy.java index 8a70bc56984..6140e024222 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PinAndEdgeCreationInCompartmentEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PinAndEdgeCreationInCompartmentEditPolicy.java @@ -1,52 +1,52 @@ -/*****************************************************************************
- * Copyright (c) 2011 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import java.util.Collection;
-import java.util.List;
-
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.Request;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.requests.CreateUnspecifiedTypeRequest;
-import org.eclipse.gmf.runtime.emf.type.core.IElementType;
-import org.eclipse.papyrus.uml.diagram.common.editpolicies.PapyrusCreationEditPolicy;
-
-/**
- * Aim to redirect pin and edge creation to parent element
- * WARNING : NOT WORKING FOR NOW
- */
-public abstract class PinAndEdgeCreationInCompartmentEditPolicy extends PapyrusCreationEditPolicy {
-
- @Override
- public EditPart getTargetEditPart(Request request) {
- if (request instanceof CreateUnspecifiedTypeRequest) {
- CreateUnspecifiedTypeRequest createUnspecifiedTypeRequest = (CreateUnspecifiedTypeRequest) request;
- if (understandsRequest(request)) {
- List<?> elementTypes = createUnspecifiedTypeRequest.getElementTypes();
- // Treat the case where only one element type is listed
- // Only take Port or Parameter element type into account
- if ((elementTypes.size() == 1) && getElementHandleByParent().contains(((elementTypes.get(0))))) {
- // If the target is a compartment replace by its parent edit part
- if ((getHost() instanceof ShapeCompartmentEditPart)) {
- return getHost().getParent();
- }
- }
- }
- }
- return super.getTargetEditPart(request);
- }
-
- protected abstract Collection<IElementType> getElementHandleByParent();
-}
+/***************************************************************************** + * Copyright (c) 2011 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import java.util.Collection; +import java.util.List; + +import org.eclipse.gef.EditPart; +import org.eclipse.gef.Request; +import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart; +import org.eclipse.gmf.runtime.diagram.ui.requests.CreateUnspecifiedTypeRequest; +import org.eclipse.gmf.runtime.emf.type.core.IElementType; +import org.eclipse.papyrus.uml.diagram.common.editpolicies.PapyrusCreationEditPolicy; + +/** + * Aim to redirect pin and edge creation to parent element + * WARNING : NOT WORKING FOR NOW + */ +public abstract class PinAndEdgeCreationInCompartmentEditPolicy extends PapyrusCreationEditPolicy { + + @Override + public EditPart getTargetEditPart(Request request) { + if (request instanceof CreateUnspecifiedTypeRequest) { + CreateUnspecifiedTypeRequest createUnspecifiedTypeRequest = (CreateUnspecifiedTypeRequest) request; + if (understandsRequest(request)) { + List<?> elementTypes = createUnspecifiedTypeRequest.getElementTypes(); + // Treat the case where only one element type is listed + // Only take Port or Parameter element type into account + if ((elementTypes.size() == 1) && getElementHandleByParent().contains(((elementTypes.get(0))))) { + // If the target is a compartment replace by its parent edit part + if ((getHost() instanceof ShapeCompartmentEditPart)) { + return getHost().getParent(); + } + } + } + } + return super.getTargetEditPart(request); + } + + protected abstract Collection<IElementType> getElementHandleByParent(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PinLayoutEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PinLayoutEditPolicy.java index 5879c03002b..b113fcf26a3 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PinLayoutEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/PinLayoutEditPolicy.java @@ -1,48 +1,48 @@ -/*****************************************************************************
- * Copyright (c) 2010 CEA LIST.
- *
- *
- * 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:
- * Yann Tanguy (CEA LIST) yann.tanguy@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.gef.EditPart;
-import org.eclipse.gef.EditPolicy;
-import org.eclipse.gef.Request;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.editpolicies.LayoutEditPolicy;
-import org.eclipse.gef.requests.CreateRequest;
-import org.eclipse.gmf.runtime.notation.View;
-
-/**
- * This edit policy replaces the GMF generated edit policy for Port.
- * In particular it installs {@link ExternalLabelPrimaryDragRoleEditPolicy} on
- * children that are external label.
- * The code generated by GMF can be found in {@link PinEditPart#createLayoutEditPolicy()}.
- */
-public class PinLayoutEditPolicy extends LayoutEditPolicy {
-
- @Override
- protected EditPolicy createChildEditPolicy(EditPart child) {
- View childView = (View) child.getModel();
-
- return new ExternalLabelPrimaryDragRoleEditPolicy();
- }
-
- @Override
- protected Command getMoveChildrenCommand(Request request) {
- return null;
- }
-
- @Override
- protected Command getCreateCommand(CreateRequest request) {
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2010 CEA LIST. + * + * + * 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: + * Yann Tanguy (CEA LIST) yann.tanguy@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.gef.EditPart; +import org.eclipse.gef.EditPolicy; +import org.eclipse.gef.Request; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.editpolicies.LayoutEditPolicy; +import org.eclipse.gef.requests.CreateRequest; +import org.eclipse.gmf.runtime.notation.View; + +/** + * This edit policy replaces the GMF generated edit policy for Port. + * In particular it installs {@link ExternalLabelPrimaryDragRoleEditPolicy} on + * children that are external label. + * The code generated by GMF can be found in {@link PinEditPart#createLayoutEditPolicy()}. + */ +public class PinLayoutEditPolicy extends LayoutEditPolicy { + + @Override + protected EditPolicy createChildEditPolicy(EditPart child) { + View childView = (View) child.getModel(); + + return new ExternalLabelPrimaryDragRoleEditPolicy(); + } + + @Override + protected Command getMoveChildrenCommand(Request request) { + return null; + } + + @Override + protected Command getCreateCommand(CreateRequest request) { + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ResizableSquareEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ResizableSquareEditPolicy.java index 19574e8df51..cdaf197d296 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ResizableSquareEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ResizableSquareEditPolicy.java @@ -1,75 +1,75 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.draw2d.PositionConstants;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ResizableShapeEditPolicy;
-
-/**
- * A resizable editpolicy for shape editparts. It constraint the resize requests
- * so that the shape stays as a square.
- *
- * @see ResizableShapeEditPolicy
- */
-public class ResizableSquareEditPolicy extends ResizableShapeEditPolicy {
-
- /**
- * Shows or updates feedback for a change bounds request. The request is
- * updated by the way so that the shape stays a square.
- *
- * @param request
- * the request
- */
- @Override
- protected void showChangeBoundsFeedback(ChangeBoundsRequest request) {
- // adapt the request for a square resize
- Point move = request.getMoveDelta();
- Dimension delta = request.getSizeDelta();
- int dH = delta.height;
- int dW = delta.width;
- int signum = 0;
- if (dH <= 0 && dW <= 0) {
- signum = -1;
- } else {
- signum = 1;
- }
- int positiveResize = Math.max(dH, dW);
- if (positiveResize <= 0) {
- if (dH == 0) {
- positiveResize = -dW;
- } else if (dW == 0) {
- positiveResize = -dH;
- } else {
- positiveResize = Math.min(-dH, -dW);
- }
- }
- int newDH = signum * positiveResize;
- int newDW = newDH;
- int dir = request.getResizeDirection();
- // adjust new position if impacted by resizing
- if ((dir & PositionConstants.NORTH) > 0) {
- move.y += dH - newDH;
- }
- if ((dir & PositionConstants.WEST) > 0) {
- move.x += dW - newDW;
- }
- request.setMoveDelta(move);
- delta.height = newDH;
- delta.width = newDW;
- super.showChangeBoundsFeedback(request);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ResizableShapeEditPolicy; + +/** + * A resizable editpolicy for shape editparts. It constraint the resize requests + * so that the shape stays as a square. + * + * @see ResizableShapeEditPolicy + */ +public class ResizableSquareEditPolicy extends ResizableShapeEditPolicy { + + /** + * Shows or updates feedback for a change bounds request. The request is + * updated by the way so that the shape stays a square. + * + * @param request + * the request + */ + @Override + protected void showChangeBoundsFeedback(ChangeBoundsRequest request) { + // adapt the request for a square resize + Point move = request.getMoveDelta(); + Dimension delta = request.getSizeDelta(); + int dH = delta.height; + int dW = delta.width; + int signum = 0; + if (dH <= 0 && dW <= 0) { + signum = -1; + } else { + signum = 1; + } + int positiveResize = Math.max(dH, dW); + if (positiveResize <= 0) { + if (dH == 0) { + positiveResize = -dW; + } else if (dW == 0) { + positiveResize = -dH; + } else { + positiveResize = Math.min(-dH, -dW); + } + } + int newDH = signum * positiveResize; + int newDW = newDH; + int dir = request.getResizeDirection(); + // adjust new position if impacted by resizing + if ((dir & PositionConstants.NORTH) > 0) { + move.y += dH - newDH; + } + if ((dir & PositionConstants.WEST) > 0) { + move.x += dW - newDW; + } + request.setMoveDelta(move); + delta.height = newDH; + delta.width = newDW; + super.showChangeBoundsFeedback(request); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ResizeActivityEditPolicy.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ResizeActivityEditPolicy.java index 87d3b102887..6eeef472080 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ResizeActivityEditPolicy.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/policies/ResizeActivityEditPolicy.java @@ -1,51 +1,51 @@ -/*****************************************************************************
- * Copyright (c) 2009 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:
- * Atos Origin - Initial API and implementation
- * CEA LIT - modification for the resize
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.edit.policies;
-
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.commands.UnexecutableCommand;
-import org.eclipse.gef.requests.ChangeBoundsRequest;
-import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ResizableShapeEditPolicy;
-
-/**
- * This editPolicy prevent from moving the activity and preserve the -1,-1 size
- * for the activity. This way, the activity is automatically resized to the
- * optimal size, being enlarged when an element is drag out of it and taking the
- * default large size otherwise.
- * now the user can resize the activity
- */
-public class ResizeActivityEditPolicy extends ResizableShapeEditPolicy {
-
- /**
- * Disable moving the activity.
- *
- * @param request
- * request to change location
- * @return UnexecutableCommand.INSTANCE
- */
- @Override
- protected Command getMoveCommand(ChangeBoundsRequest request) {
- return UnexecutableCommand.INSTANCE;
- }
-
- /**
- *
- * the user can resize the activity
- */
- @Override
- protected Command getResizeCommand(ChangeBoundsRequest request) {
- return super.getResizeCommand(request);
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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: + * Atos Origin - Initial API and implementation + * CEA LIT - modification for the resize + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.edit.policies; + +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.commands.UnexecutableCommand; +import org.eclipse.gef.requests.ChangeBoundsRequest; +import org.eclipse.gmf.runtime.diagram.ui.editpolicies.ResizableShapeEditPolicy; + +/** + * This editPolicy prevent from moving the activity and preserve the -1,-1 size + * for the activity. This way, the activity is automatically resized to the + * optimal size, being enlarged when an element is drag out of it and taking the + * default large size otherwise. + * now the user can resize the activity + */ +public class ResizeActivityEditPolicy extends ResizableShapeEditPolicy { + + /** + * Disable moving the activity. + * + * @param request + * request to change location + * @return UnexecutableCommand.INSTANCE + */ + @Override + protected Command getMoveCommand(ChangeBoundsRequest request) { + return UnexecutableCommand.INSTANCE; + } + + /** + * + * the user can resize the activity + */ + @Override + protected Command getResizeCommand(ChangeBoundsRequest request) { + return super.getResizeCommand(request); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/AbstractCallActionPinUpdater.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/AbstractCallActionPinUpdater.java index 747441c0cc8..939916eeb5f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/AbstractCallActionPinUpdater.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/AbstractCallActionPinUpdater.java @@ -1,48 +1,48 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * J�r�mie TATIBOUET (CEA LIST) - Initial API and implementation
- * S�bastien REVOL (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater;
-
-import java.util.List;
-
-import org.eclipse.uml2.uml.CallAction;
-import org.eclipse.uml2.uml.OutputPin;
-
-public abstract class AbstractCallActionPinUpdater<NodeType extends CallAction> extends AbstractInvocationActionPinUpdater<NodeType> {
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.AbstractInvocationActionPinUpdater#updatePin(org.eclipse.uml2.uml.InvocationAction)
- *
- * @param node
- */
- @Override
- public void updatePins(NodeType node) {
- super.updatePins(node);
- if (node.isSynchronous()) {
- this.update(node.getResults(), this.deriveResults(node));
- } else {
- node.getResults().clear();
- }
- }
-
- /**
- * Derive the list of result pins for the CallAction
- *
- * @param node
- * the call action for which result pins are derived
- *
- * @return the list of derived result pins
- */
- public abstract List<OutputPin> deriveResults(NodeType node);
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * J�r�mie TATIBOUET (CEA LIST) - Initial API and implementation + * S�bastien REVOL (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater; + +import java.util.List; + +import org.eclipse.uml2.uml.CallAction; +import org.eclipse.uml2.uml.OutputPin; + +public abstract class AbstractCallActionPinUpdater<NodeType extends CallAction> extends AbstractInvocationActionPinUpdater<NodeType> { + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.AbstractInvocationActionPinUpdater#updatePin(org.eclipse.uml2.uml.InvocationAction) + * + * @param node + */ + @Override + public void updatePins(NodeType node) { + super.updatePins(node); + if (node.isSynchronous()) { + this.update(node.getResults(), this.deriveResults(node)); + } else { + node.getResults().clear(); + } + } + + /** + * Derive the list of result pins for the CallAction + * + * @param node + * the call action for which result pins are derived + * + * @return the list of derived result pins + */ + public abstract List<OutputPin> deriveResults(NodeType node); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/AbstractInvocationActionPinUpdater.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/AbstractInvocationActionPinUpdater.java index ce0664ce2bc..ffe0fd03804 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/AbstractInvocationActionPinUpdater.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/AbstractInvocationActionPinUpdater.java @@ -1,175 +1,175 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * Jérémie TATIBOUET (CEA LIST) - Initial API and implementation
- * Sébastien REVOL (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.ActivityEdge;
-import org.eclipse.uml2.uml.ActivityPartition;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.InputPin;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.Pin;
-import org.eclipse.uml2.uml.StructuredActivityNode;
-
-public abstract class AbstractInvocationActionPinUpdater<NodeType extends InvocationAction> implements IPinUpdater<NodeType> {
-
- /**
- * The derived target is always named 'target'.
- */
- protected static final String TARGET_NAME = "target";
-
- /**
- * Update the original pins with newly derived pins. If it is possible to preserve
- * existing pins then this action is preferred to replacement.
- *
- * @param originPins
- * the list of pins already existing for the node
- * @param newPins
- * the list of pins newly computed for the node
- */
- protected <P extends Pin> void update(List<P> originPins, List<P> newPins) {
- List<P> orderedPinsList = new ArrayList<P>();
- Iterator<P> newPinsIterator = newPins.iterator();
- while (newPinsIterator.hasNext()) {
- P newPin = newPinsIterator.next();
- Iterator<P> originPinsIterator = originPins.iterator();
- P preservedPin = null;
- while (originPinsIterator.hasNext() && preservedPin == null) {
- // Search an existing pin in the 'originPins' which can be
- // preserved and updated with the data of the new pin under
- // consideration
- P originPin = originPinsIterator.next();
- if (!orderedPinsList.contains(originPin) && isReusable(newPin, originPin)) {
- preservedPin = originPin;
- update(preservedPin, newPin);
- orderedPinsList.add(preservedPin);
- }
- }
- if (preservedPin == null) {
- // No original pin could be preserved.
- orderedPinsList.add(newPin);
- }
- }
- // 2 - Propagate deletion of unpreserved pins to edges
- // that may use them either as source or target
- for (P pin : originPins) {
- if (!orderedPinsList.contains(pin)) {
- delete(pin);
- }
- }
- // 3 - Update the originPins list with the content of the orderedPinList
- originPins.clear();
- originPins.addAll(orderedPinsList);
- }
-
- /**
- * An existing pin can only be reused under the following conditions:
- * 1] Original type conforms to the new type (i.e. the new type is a super type of the original type or the original type itself)
- * 2] The multiplicity of the new pin is wider than, or the same as, self
- *
- * @param new_
- * the new pin
- * @param origin
- * the original pin
- * @return true of it can be reused, false otherwise
- */
- private static boolean isReusable(Pin new_, Pin origin) {
- boolean reuse = true;
- if (new_.getType() != null && origin.getType() != null) {
- reuse = origin.getType().conformsTo(new_.getType());
- }
- if (reuse) {
- reuse = origin.compatibleWith(new_);
- }
- return reuse;
- }
-
- /**
- * Update multiplicity, type and name of origin pin with the new pin
- *
- * @param origin
- * the original pin
- * @param new_
- * the new pin
- */
- protected static void update(Pin origin, Pin new_) {
- origin.setLower(new_.getLower());
- origin.setUpper(new_.getUpper());
- origin.setType(new_.getType());
- origin.setName(new_.getName());
- }
-
- /**
- * The deletion of a pin has an impact on edges that are using as a source or a target.
- * To ensure model consistency, the deletion of a pin implies deletion of edges referencing
- * this pin either as a source or a target.
- *
- * @param pin
- */
- protected static void delete(Pin pin) {
- List<ActivityEdge> edgeToDelete = new ArrayList<ActivityEdge>(pin.getIncomings());
- edgeToDelete.addAll(pin.getOutgoings());
- Iterator<ActivityEdge> edgeToDeleteIterator = edgeToDelete.iterator();
- while (edgeToDeleteIterator.hasNext()) {
- ActivityEdge edge = edgeToDeleteIterator.next();
- Element owner = edge.getOwner();
- if (owner != null) {
- if (owner instanceof StructuredActivityNode) {
- ((StructuredActivityNode) owner).getEdges().remove(edge);
- } else if (owner instanceof Activity) {
- ((Activity) owner).getEdges().remove(edge);
- } else if (owner instanceof ActivityPartition) {
- ((ActivityPartition) owner).getEdges().remove(edge);
- }
- }
- }
- }
-
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater#updatePin(org.eclipse.uml2.uml.ActivityNode)
- *
- * @param node
- */
- @Override
- public void updatePins(NodeType node) {
- this.update(node.getArguments(), this.deriveArguments(node));
- }
-
- /**
- * Derive the argument pins of the invocation action
- *
- * @param node
- * the invocation action for which the arguments pin are derived
- * @return the list of derived arguments pin
- */
- public abstract List<InputPin> deriveArguments(NodeType node);
-
- /**
- * Derive the target used for the invocation action
- *
- * @param node
- * the invocation action for which the target is derived
- * @return the input pin corresponding to the derived target
- */
- public InputPin deriveTarget(NodeType node) {
- return null; // By default do nothing
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * Jérémie TATIBOUET (CEA LIST) - Initial API and implementation + * Sébastien REVOL (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.ActivityEdge; +import org.eclipse.uml2.uml.ActivityPartition; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.InputPin; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.Pin; +import org.eclipse.uml2.uml.StructuredActivityNode; + +public abstract class AbstractInvocationActionPinUpdater<NodeType extends InvocationAction> implements IPinUpdater<NodeType> { + + /** + * The derived target is always named 'target'. + */ + protected static final String TARGET_NAME = "target"; + + /** + * Update the original pins with newly derived pins. If it is possible to preserve + * existing pins then this action is preferred to replacement. + * + * @param originPins + * the list of pins already existing for the node + * @param newPins + * the list of pins newly computed for the node + */ + protected <P extends Pin> void update(List<P> originPins, List<P> newPins) { + List<P> orderedPinsList = new ArrayList<P>(); + Iterator<P> newPinsIterator = newPins.iterator(); + while (newPinsIterator.hasNext()) { + P newPin = newPinsIterator.next(); + Iterator<P> originPinsIterator = originPins.iterator(); + P preservedPin = null; + while (originPinsIterator.hasNext() && preservedPin == null) { + // Search an existing pin in the 'originPins' which can be + // preserved and updated with the data of the new pin under + // consideration + P originPin = originPinsIterator.next(); + if (!orderedPinsList.contains(originPin) && isReusable(newPin, originPin)) { + preservedPin = originPin; + update(preservedPin, newPin); + orderedPinsList.add(preservedPin); + } + } + if (preservedPin == null) { + // No original pin could be preserved. + orderedPinsList.add(newPin); + } + } + // 2 - Propagate deletion of unpreserved pins to edges + // that may use them either as source or target + for (P pin : originPins) { + if (!orderedPinsList.contains(pin)) { + delete(pin); + } + } + // 3 - Update the originPins list with the content of the orderedPinList + originPins.clear(); + originPins.addAll(orderedPinsList); + } + + /** + * An existing pin can only be reused under the following conditions: + * 1] Original type conforms to the new type (i.e. the new type is a super type of the original type or the original type itself) + * 2] The multiplicity of the new pin is wider than, or the same as, self + * + * @param new_ + * the new pin + * @param origin + * the original pin + * @return true of it can be reused, false otherwise + */ + private static boolean isReusable(Pin new_, Pin origin) { + boolean reuse = true; + if (new_.getType() != null && origin.getType() != null) { + reuse = origin.getType().conformsTo(new_.getType()); + } + if (reuse) { + reuse = origin.compatibleWith(new_); + } + return reuse; + } + + /** + * Update multiplicity, type and name of origin pin with the new pin + * + * @param origin + * the original pin + * @param new_ + * the new pin + */ + protected static void update(Pin origin, Pin new_) { + origin.setLower(new_.getLower()); + origin.setUpper(new_.getUpper()); + origin.setType(new_.getType()); + origin.setName(new_.getName()); + } + + /** + * The deletion of a pin has an impact on edges that are using as a source or a target. + * To ensure model consistency, the deletion of a pin implies deletion of edges referencing + * this pin either as a source or a target. + * + * @param pin + */ + protected static void delete(Pin pin) { + List<ActivityEdge> edgeToDelete = new ArrayList<ActivityEdge>(pin.getIncomings()); + edgeToDelete.addAll(pin.getOutgoings()); + Iterator<ActivityEdge> edgeToDeleteIterator = edgeToDelete.iterator(); + while (edgeToDeleteIterator.hasNext()) { + ActivityEdge edge = edgeToDeleteIterator.next(); + Element owner = edge.getOwner(); + if (owner != null) { + if (owner instanceof StructuredActivityNode) { + ((StructuredActivityNode) owner).getEdges().remove(edge); + } else if (owner instanceof Activity) { + ((Activity) owner).getEdges().remove(edge); + } else if (owner instanceof ActivityPartition) { + ((ActivityPartition) owner).getEdges().remove(edge); + } + } + } + } + + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater#updatePin(org.eclipse.uml2.uml.ActivityNode) + * + * @param node + */ + @Override + public void updatePins(NodeType node) { + this.update(node.getArguments(), this.deriveArguments(node)); + } + + /** + * Derive the argument pins of the invocation action + * + * @param node + * the invocation action for which the arguments pin are derived + * @return the list of derived arguments pin + */ + public abstract List<InputPin> deriveArguments(NodeType node); + + /** + * Derive the target used for the invocation action + * + * @param node + * the invocation action for which the target is derived + * @return the input pin corresponding to the derived target + */ + public InputPin deriveTarget(NodeType node) { + return null; // By default do nothing + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/IPinUpdater.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/IPinUpdater.java index bd257b36d8d..4e2f7a75d2b 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/IPinUpdater.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/IPinUpdater.java @@ -1,31 +1,31 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * Jérémie TATIBOUET (CEA LIST) - Initial API and implementation
- * Sébastien REVOL (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater;
-
-import org.eclipse.uml2.uml.ActivityNode;
-
-public interface IPinUpdater<NodeType extends ActivityNode> {
-
- /**
- * The role of a 'pin updater' is to enable update of any pin of a particular activity node.
- * This operation is intended to implement the the general algorithm to update pins.
- *
- * @param node
- * the activity node for which the pins need to be updated
- *
- */
- public void updatePins(NodeType node);
-
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * Jérémie TATIBOUET (CEA LIST) - Initial API and implementation + * Sébastien REVOL (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater; + +import org.eclipse.uml2.uml.ActivityNode; + +public interface IPinUpdater<NodeType extends ActivityNode> { + + /** + * The role of a 'pin updater' is to enable update of any pin of a particular activity node. + * This operation is intended to implement the the general algorithm to update pins. + * + * @param node + * the activity node for which the pins need to be updated + * + */ + public void updatePins(NodeType node); + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/PinUpdaterFactory.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/PinUpdaterFactory.java index a8d08072c4f..32cef60e7ca 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/PinUpdaterFactory.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/PinUpdaterFactory.java @@ -1,121 +1,121 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * J�r�mie TATIBOUET (CEA LIST) - Initial API and implementation
- * S�bastien REVOL (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater;
-
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.AcceptCallActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.AcceptEventActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.AddStructuralFeatureValueActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.CreateLinkActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.CreateObjectActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.LinkActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.ReadLinkActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.ReadStructuralFeatureActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.TestIdentityActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.ValueSpecificationActionPinUpdater;
-import org.eclipse.uml2.uml.AcceptCallAction;
-import org.eclipse.uml2.uml.AcceptEventAction;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.StartClassifierBehaviorActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.StartObjectBehaviorActionPinUpdater;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.ReadSelfActionPinUpdater;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.AddStructuralFeatureValueAction;
-import org.eclipse.uml2.uml.CallBehaviorAction;
-import org.eclipse.uml2.uml.CallOperationAction;
-import org.eclipse.uml2.uml.CreateLinkAction;
-import org.eclipse.uml2.uml.CreateObjectAction;
-import org.eclipse.uml2.uml.DestroyLinkAction;
-import org.eclipse.uml2.uml.ReadLinkAction;
-import org.eclipse.uml2.uml.ReadStructuralFeatureAction;
-import org.eclipse.uml2.uml.ReadSelfAction;
-import org.eclipse.uml2.uml.SendSignalAction;
-import org.eclipse.uml2.uml.TestIdentityAction;
-import org.eclipse.uml2.uml.ValueSpecificationAction;
-import org.eclipse.uml2.uml.StartClassifierBehaviorAction;
-import org.eclipse.uml2.uml.StartObjectBehaviorAction;
-
-public class PinUpdaterFactory {
-
- /**
- * Singleton reference
- */
- private static PinUpdaterFactory INSTANCE;
-
- /**
- * Constructor.
- */
- private PinUpdaterFactory() {
- }
-
- /**
- * Provide access to the singleton instance
- *
- * @return INSTANCE
- * the singleton
- */
- public static PinUpdaterFactory getInstance() {
- if (INSTANCE == null) {
- INSTANCE = new PinUpdaterFactory();
- }
- return INSTANCE;
- }
-
- /**
- * Provide a pin updater for the given activity node. This update encapsulates
- * logic to derive activity node pins.
- *
- * @param node
- * the activity node
- * @return updater
- * the pin updater for the given activity node
- */
- @SuppressWarnings("unchecked")
- public <T extends ActivityNode> IPinUpdater<T> instantiate(ActivityNode node) {
- IPinUpdater<T> updater = null;
- if (node instanceof CallBehaviorAction) {
- updater = (IPinUpdater<T>) new CallBehaviorActionPinUpdater();
- } else if (node instanceof CallOperationAction) {
- updater = (IPinUpdater<T>) new CallOperationActionPinUpdater();
- } else if (node instanceof SendSignalAction) {
- updater = (IPinUpdater<T>) new SendSignalActionPinUpdater();
- } else if (node instanceof AcceptCallAction) {
- updater = (IPinUpdater<T>) new AcceptCallActionPinUpdater();
- } else if (node instanceof AcceptEventAction) {
- updater = (IPinUpdater<T>) new AcceptEventActionPinUpdater();
- } else if (node instanceof ReadStructuralFeatureAction) {
- updater = (IPinUpdater<T>) new ReadStructuralFeatureActionPinUpdater();
- } else if (node instanceof AddStructuralFeatureValueAction) {
- updater = (IPinUpdater<T>) new AddStructuralFeatureValueActionPinUpdater();
- } else if (node instanceof CreateObjectAction) {
- updater = (IPinUpdater<T>) new CreateObjectActionPinUpdater();
- } else if (node instanceof ValueSpecificationAction) {
- updater = (IPinUpdater<T>) new ValueSpecificationActionPinUpdater();
- } else if (node instanceof TestIdentityAction) {
- updater = (IPinUpdater<T>) new TestIdentityActionPinUpdater();
- } else if (node instanceof CreateLinkAction) {
- updater = (IPinUpdater<T>) new CreateLinkActionPinUpdater();
- } else if (node instanceof DestroyLinkAction) {
- updater = (IPinUpdater<T>) new LinkActionPinUpdater();
- } else if (node instanceof ReadLinkAction) {
- updater = (IPinUpdater<T>) new ReadLinkActionPinUpdater();
- } else if (node instanceof StartClassifierBehaviorAction) {
- updater = (IPinUpdater<T>) new StartClassifierBehaviorActionPinUpdater();
- } else if (node instanceof StartObjectBehaviorAction) {
- updater = (IPinUpdater<T>) new StartObjectBehaviorActionPinUpdater();
- } else if (node instanceof ReadSelfAction) {
- updater = (IPinUpdater<T>) new ReadSelfActionPinUpdater();
- }
- return updater;
- }
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * J�r�mie TATIBOUET (CEA LIST) - Initial API and implementation + * S�bastien REVOL (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater; + +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.AcceptCallActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.AcceptEventActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.AddStructuralFeatureValueActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.CreateLinkActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.CreateObjectActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.LinkActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.ReadLinkActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.ReadStructuralFeatureActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.TestIdentityActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.ValueSpecificationActionPinUpdater; +import org.eclipse.uml2.uml.AcceptCallAction; +import org.eclipse.uml2.uml.AcceptEventAction; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.StartClassifierBehaviorActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.StartObjectBehaviorActionPinUpdater; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions.ReadSelfActionPinUpdater; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.AddStructuralFeatureValueAction; +import org.eclipse.uml2.uml.CallBehaviorAction; +import org.eclipse.uml2.uml.CallOperationAction; +import org.eclipse.uml2.uml.CreateLinkAction; +import org.eclipse.uml2.uml.CreateObjectAction; +import org.eclipse.uml2.uml.DestroyLinkAction; +import org.eclipse.uml2.uml.ReadLinkAction; +import org.eclipse.uml2.uml.ReadStructuralFeatureAction; +import org.eclipse.uml2.uml.ReadSelfAction; +import org.eclipse.uml2.uml.SendSignalAction; +import org.eclipse.uml2.uml.TestIdentityAction; +import org.eclipse.uml2.uml.ValueSpecificationAction; +import org.eclipse.uml2.uml.StartClassifierBehaviorAction; +import org.eclipse.uml2.uml.StartObjectBehaviorAction; + +public class PinUpdaterFactory { + + /** + * Singleton reference + */ + private static PinUpdaterFactory INSTANCE; + + /** + * Constructor. + */ + private PinUpdaterFactory() { + } + + /** + * Provide access to the singleton instance + * + * @return INSTANCE + * the singleton + */ + public static PinUpdaterFactory getInstance() { + if (INSTANCE == null) { + INSTANCE = new PinUpdaterFactory(); + } + return INSTANCE; + } + + /** + * Provide a pin updater for the given activity node. This update encapsulates + * logic to derive activity node pins. + * + * @param node + * the activity node + * @return updater + * the pin updater for the given activity node + */ + @SuppressWarnings("unchecked") + public <T extends ActivityNode> IPinUpdater<T> instantiate(ActivityNode node) { + IPinUpdater<T> updater = null; + if (node instanceof CallBehaviorAction) { + updater = (IPinUpdater<T>) new CallBehaviorActionPinUpdater(); + } else if (node instanceof CallOperationAction) { + updater = (IPinUpdater<T>) new CallOperationActionPinUpdater(); + } else if (node instanceof SendSignalAction) { + updater = (IPinUpdater<T>) new SendSignalActionPinUpdater(); + } else if (node instanceof AcceptCallAction) { + updater = (IPinUpdater<T>) new AcceptCallActionPinUpdater(); + } else if (node instanceof AcceptEventAction) { + updater = (IPinUpdater<T>) new AcceptEventActionPinUpdater(); + } else if (node instanceof ReadStructuralFeatureAction) { + updater = (IPinUpdater<T>) new ReadStructuralFeatureActionPinUpdater(); + } else if (node instanceof AddStructuralFeatureValueAction) { + updater = (IPinUpdater<T>) new AddStructuralFeatureValueActionPinUpdater(); + } else if (node instanceof CreateObjectAction) { + updater = (IPinUpdater<T>) new CreateObjectActionPinUpdater(); + } else if (node instanceof ValueSpecificationAction) { + updater = (IPinUpdater<T>) new ValueSpecificationActionPinUpdater(); + } else if (node instanceof TestIdentityAction) { + updater = (IPinUpdater<T>) new TestIdentityActionPinUpdater(); + } else if (node instanceof CreateLinkAction) { + updater = (IPinUpdater<T>) new CreateLinkActionPinUpdater(); + } else if (node instanceof DestroyLinkAction) { + updater = (IPinUpdater<T>) new LinkActionPinUpdater(); + } else if (node instanceof ReadLinkAction) { + updater = (IPinUpdater<T>) new ReadLinkActionPinUpdater(); + } else if (node instanceof StartClassifierBehaviorAction) { + updater = (IPinUpdater<T>) new StartClassifierBehaviorActionPinUpdater(); + } else if (node instanceof StartObjectBehaviorAction) { + updater = (IPinUpdater<T>) new StartObjectBehaviorActionPinUpdater(); + } else if (node instanceof ReadSelfAction) { + updater = (IPinUpdater<T>) new ReadSelfActionPinUpdater(); + } + return updater; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/CreateObjectActionPinUpdater.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/CreateObjectActionPinUpdater.java index bdd4fab8e4f..7a83f726d49 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/CreateObjectActionPinUpdater.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/CreateObjectActionPinUpdater.java @@ -1,50 +1,50 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions;
-
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.AbstractActionPinUpdater;
-import org.eclipse.uml2.uml.CreateObjectAction;
-import org.eclipse.uml2.uml.OutputPin;
-import org.eclipse.uml2.uml.UMLFactory;
-
-/**
- * Pins of CreateObjectAction should be create and update automatically
- *
- * This class define derivation rules
- */
-public class CreateObjectActionPinUpdater extends AbstractActionPinUpdater<CreateObjectAction> {
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater#updatePins(org.eclipse.uml2.uml.ActivityNode)
- *
- * @param node
- */
- @Override
- public void updatePins(CreateObjectAction node) {
- // 1] create result pin if it is not created yet
- OutputPin result = node.getResult();
- if(result == null){
- result = UMLFactory.eINSTANCE.createOutputPin();
- result.setLower(1);
- result.setUpper(1);
- result.setName("result"); //$NON-NLS-1$
- }
- // 2] when the classifier feature is set, the result pin type is set too with this classifier
- if(node.getClassifier() != null){
- result.setType(node.getClassifier());
- }
- node.setResult(result);
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions; + +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.AbstractActionPinUpdater; +import org.eclipse.uml2.uml.CreateObjectAction; +import org.eclipse.uml2.uml.OutputPin; +import org.eclipse.uml2.uml.UMLFactory; + +/** + * Pins of CreateObjectAction should be create and update automatically + * + * This class define derivation rules + */ +public class CreateObjectActionPinUpdater extends AbstractActionPinUpdater<CreateObjectAction> { + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater#updatePins(org.eclipse.uml2.uml.ActivityNode) + * + * @param node + */ + @Override + public void updatePins(CreateObjectAction node) { + // 1] create result pin if it is not created yet + OutputPin result = node.getResult(); + if(result == null){ + result = UMLFactory.eINSTANCE.createOutputPin(); + result.setLower(1); + result.setUpper(1); + result.setName("result"); //$NON-NLS-1$ + } + // 2] when the classifier feature is set, the result pin type is set too with this classifier + if(node.getClassifier() != null){ + result.setType(node.getClassifier()); + } + node.setResult(result); + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/StartClassifierBehaviorActionPinUpdater.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/StartClassifierBehaviorActionPinUpdater.java index 0dd876de47b..31492570d2f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/StartClassifierBehaviorActionPinUpdater.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/StartClassifierBehaviorActionPinUpdater.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions;
-
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.AbstractActionPinUpdater;
-import org.eclipse.uml2.uml.InputPin;
-import org.eclipse.uml2.uml.StartClassifierBehaviorAction;
-import org.eclipse.uml2.uml.UMLFactory;
-
-/**
- *
- * Pin of StartClassifierBehaviorAction should be create and update automatically
- *
- */
-public class StartClassifierBehaviorActionPinUpdater extends AbstractActionPinUpdater<StartClassifierBehaviorAction> {
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater#updatePins(org.eclipse.uml2.uml.ActivityNode)
- *
- * @param node
- */
- @Override
- public void updatePins(StartClassifierBehaviorAction node) {
- if (node != null) {
- // 1] create the object pin if it is not created yet
- // the object pin stay untyped because we can not deduce its type
- InputPin object = node.getObject();
- if (object == null) {
- object = UMLFactory.eINSTANCE.createInputPin();
- object.setName("object");
- }
- object.setLower(1);
- object.setUpper(1);
- node.setObject(object);
- }
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions; + +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.AbstractActionPinUpdater; +import org.eclipse.uml2.uml.InputPin; +import org.eclipse.uml2.uml.StartClassifierBehaviorAction; +import org.eclipse.uml2.uml.UMLFactory; + +/** + * + * Pin of StartClassifierBehaviorAction should be create and update automatically + * + */ +public class StartClassifierBehaviorActionPinUpdater extends AbstractActionPinUpdater<StartClassifierBehaviorAction> { + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater#updatePins(org.eclipse.uml2.uml.ActivityNode) + * + * @param node + */ + @Override + public void updatePins(StartClassifierBehaviorAction node) { + if (node != null) { + // 1] create the object pin if it is not created yet + // the object pin stay untyped because we can not deduce its type + InputPin object = node.getObject(); + if (object == null) { + object = UMLFactory.eINSTANCE.createInputPin(); + object.setName("object"); + } + object.setLower(1); + object.setUpper(1); + node.setObject(object); + } + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/ValueSpecificationActionPinUpdater.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/ValueSpecificationActionPinUpdater.java index df6968a622c..0bb8423a341 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/ValueSpecificationActionPinUpdater.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/edit/utils/updater/intermediateactions/ValueSpecificationActionPinUpdater.java @@ -1,90 +1,90 @@ -/*****************************************************************************
- * Copyright (c) 2016 CEA LIST and others.
- *
- * 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:
- * (CEA LIST) - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions;
-
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.AbstractActionPinUpdater;
-import org.eclipse.uml2.uml.EnumerationLiteral;
-import org.eclipse.uml2.uml.InstanceSpecification;
-import org.eclipse.uml2.uml.InstanceValue;
-import org.eclipse.uml2.uml.LiteralBoolean;
-import org.eclipse.uml2.uml.LiteralInteger;
-import org.eclipse.uml2.uml.LiteralReal;
-import org.eclipse.uml2.uml.LiteralString;
-import org.eclipse.uml2.uml.LiteralUnlimitedNatural;
-import org.eclipse.uml2.uml.OutputPin;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.ValueSpecification;
-import org.eclipse.uml2.uml.ValueSpecificationAction;
-
-/**
- *
- * Pin of ValueSpecificationAction should be create and update automatically
- *
- */
-public class ValueSpecificationActionPinUpdater extends AbstractActionPinUpdater<ValueSpecificationAction> {
-
- /**
- * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater#updatePins(org.eclipse.uml2.uml.ActivityNode)
- *
- * @param node
- */
- @Override
- public void updatePins(ValueSpecificationAction node) {
- // 1] create result pin if it is not created yet
- if (node != null) {
- OutputPin result = node.getResult();
- if (result == null) {
- result = UMLFactory.eINSTANCE.createOutputPin();
- result.setLower(1);
- result.setUpper(1);
- result.setName("result"); //$NON-NLS-1$
- }
- // 2] type the result pin according to the value type
- ValueSpecification valueSpecification = node.getValue();
- if (valueSpecification != null) {
- if (valueSpecification instanceof LiteralInteger) {
- result.setType(this.getUMLPrimitiveType("Integer", valueSpecification.getModel())); //$NON-NLS-1$
- } else if (valueSpecification instanceof LiteralUnlimitedNatural) {
- result.setType(this.getUMLPrimitiveType("UnlimitedNatural", valueSpecification.getModel())); //$NON-NLS-1$
- } else if (valueSpecification instanceof LiteralReal) {
- result.setType(this.getUMLPrimitiveType("Real", valueSpecification.getModel())); //$NON-NLS-1$
- } else if (valueSpecification instanceof LiteralString) {
- result.setType(this.getUMLPrimitiveType("String", valueSpecification.getModel())); //$NON-NLS-1$
- } else if (valueSpecification instanceof LiteralBoolean) {
- result.setType(this.getUMLPrimitiveType("Boolean", valueSpecification.getModel())); //$NON-NLS-1$
- } else if (valueSpecification instanceof InstanceValue) {
- InstanceSpecification specification = ((InstanceValue) valueSpecification).getInstance();
- if (specification != null) {
- // 3] case EnumerationLiteral
- // the result pin is typed by the enumeration owning the EnumerationLiteral
- if (specification instanceof EnumerationLiteral) {
- result.setType(((EnumerationLiteral) specification).getEnumeration());
- } else {
- // 4] case InstanceSpecification
- // the result pin is typed by the classifier of the InstanceSpecification
- // if there is more than one classifier the pin is typed by the common super classifer
- if (specification.getClassifiers().size() == 1) {
- result.setType(specification.getClassifiers().iterator().next());
- } else if (specification.getClassifiers().size() > 1) {
- result.setType(getFirstCommonSuperClassifier(specification.getClassifiers()));
- }
- }
- }
- }
- }
- node.setResult(result);
- }
- }
-
-}
+/***************************************************************************** + * Copyright (c) 2016 CEA LIST and others. + * + * 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: + * (CEA LIST) - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.intermediateactions; + +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.AbstractActionPinUpdater; +import org.eclipse.uml2.uml.EnumerationLiteral; +import org.eclipse.uml2.uml.InstanceSpecification; +import org.eclipse.uml2.uml.InstanceValue; +import org.eclipse.uml2.uml.LiteralBoolean; +import org.eclipse.uml2.uml.LiteralInteger; +import org.eclipse.uml2.uml.LiteralReal; +import org.eclipse.uml2.uml.LiteralString; +import org.eclipse.uml2.uml.LiteralUnlimitedNatural; +import org.eclipse.uml2.uml.OutputPin; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.ValueSpecification; +import org.eclipse.uml2.uml.ValueSpecificationAction; + +/** + * + * Pin of ValueSpecificationAction should be create and update automatically + * + */ +public class ValueSpecificationActionPinUpdater extends AbstractActionPinUpdater<ValueSpecificationAction> { + + /** + * @see org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.IPinUpdater#updatePins(org.eclipse.uml2.uml.ActivityNode) + * + * @param node + */ + @Override + public void updatePins(ValueSpecificationAction node) { + // 1] create result pin if it is not created yet + if (node != null) { + OutputPin result = node.getResult(); + if (result == null) { + result = UMLFactory.eINSTANCE.createOutputPin(); + result.setLower(1); + result.setUpper(1); + result.setName("result"); //$NON-NLS-1$ + } + // 2] type the result pin according to the value type + ValueSpecification valueSpecification = node.getValue(); + if (valueSpecification != null) { + if (valueSpecification instanceof LiteralInteger) { + result.setType(this.getUMLPrimitiveType("Integer", valueSpecification.getModel())); //$NON-NLS-1$ + } else if (valueSpecification instanceof LiteralUnlimitedNatural) { + result.setType(this.getUMLPrimitiveType("UnlimitedNatural", valueSpecification.getModel())); //$NON-NLS-1$ + } else if (valueSpecification instanceof LiteralReal) { + result.setType(this.getUMLPrimitiveType("Real", valueSpecification.getModel())); //$NON-NLS-1$ + } else if (valueSpecification instanceof LiteralString) { + result.setType(this.getUMLPrimitiveType("String", valueSpecification.getModel())); //$NON-NLS-1$ + } else if (valueSpecification instanceof LiteralBoolean) { + result.setType(this.getUMLPrimitiveType("Boolean", valueSpecification.getModel())); //$NON-NLS-1$ + } else if (valueSpecification instanceof InstanceValue) { + InstanceSpecification specification = ((InstanceValue) valueSpecification).getInstance(); + if (specification != null) { + // 3] case EnumerationLiteral + // the result pin is typed by the enumeration owning the EnumerationLiteral + if (specification instanceof EnumerationLiteral) { + result.setType(((EnumerationLiteral) specification).getEnumeration()); + } else { + // 4] case InstanceSpecification + // the result pin is typed by the classifier of the InstanceSpecification + // if there is more than one classifier the pin is typed by the common super classifer + if (specification.getClassifiers().size() == 1) { + result.setType(specification.getClassifiers().iterator().next()); + } else if (specification.getClassifiers().size() > 1) { + result.setType(getFirstCommonSuperClassifier(specification.getClassifiers())); + } + } + } + } + } + node.setResult(result); + } + } + +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/exception/EditPolicyConfigurationException.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/exception/EditPolicyConfigurationException.java index ec0051f14ff..2ac7bcef091 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/exception/EditPolicyConfigurationException.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/exception/EditPolicyConfigurationException.java @@ -1,44 +1,44 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.exception;
-
-/**
- * Exception raised when an edit policy was not correctly configure
- *
- * @author arthur daussy
- *
- */
-public class EditPolicyConfigurationException extends Exception {
-
- /**
- *
- */
- private static final long serialVersionUID = -7560556980743988409L;
-
- /**
- * Edit Policy class
- */
- private Class<?> editPolicyClass;
-
- public EditPolicyConfigurationException(String arg0, Class<?> editPolicyClass) {
- super(arg0);
- this.editPolicyClass = editPolicyClass;
- }
-
- @Override
- public String getMessage() {
- String detailMessage = super.getMessage();
- return "EditPolicy configuration error for class " + editPolicyClass.toString() + " :" + detailMessage;//////$NON-NLS-1$
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.exception; + +/** + * Exception raised when an edit policy was not correctly configure + * + * @author arthur daussy + * + */ +public class EditPolicyConfigurationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = -7560556980743988409L; + + /** + * Edit Policy class + */ + private Class<?> editPolicyClass; + + public EditPolicyConfigurationException(String arg0, Class<?> editPolicyClass) { + super(arg0); + this.editPolicyClass = editPolicyClass; + } + + @Override + public String getMessage() { + String detailMessage = super.getMessage(); + return "EditPolicy configuration error for class " + editPolicyClass.toString() + " :" + detailMessage;//////$NON-NLS-1$ + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/AbstractActionFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/AbstractActionFigure.java index afae9ec9a62..907e00abfe9 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/AbstractActionFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/AbstractActionFigure.java @@ -1,175 +1,175 @@ -/*****************************************************************************
- * 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:
- * Emilien Perico (Atos Origin) emilien.perico@atosorigin.com - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.draw2d.GridData;
-import org.eclipse.draw2d.GridLayout;
-import org.eclipse.draw2d.RoundedRectangle;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
-import org.eclipse.papyrus.infra.gmfdiag.common.figure.node.PapyrusWrappingLabel;
-import org.eclipse.papyrus.uml.diagram.common.figure.node.CenteredWrappedLabel;
-import org.eclipse.papyrus.uml.diagram.common.figure.node.IPapyrusNodeUMLElementFigure;
-import org.eclipse.papyrus.uml.diagram.common.helper.StereotypeFigureHelper;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * AbstractActionFigure is an abstract super class for Action figures in order
- * to manage stereotype display
- *
- * @generated
- */
-public abstract class AbstractActionFigure extends RoundedRectangle implements IPapyrusNodeUMLElementFigure {
-
- /** @generated */
- private boolean myUseLocalCoordinates = false;
-
- /** The helper which handles stereotype aspects */
- private StereotypeFigureHelper stereotypeHelper;
-
- /**
- * use StereotypeFigureHelper
- */
- public AbstractActionFigure() {
- GridLayout layoutThis = new GridLayout();
- layoutThis.numColumns = 1;
- layoutThis.makeColumnsEqualWidth = true;
- setLayoutManager(layoutThis);
- setCornerDimensions(new Dimension(getMapMode().DPtoLP(16), getMapMode().DPtoLP(16)));
- setLineWidth(1);
- // use StereotypeFigureHelper
- stereotypeHelper = new StereotypeFigureHelper(this) {
-
- // @Override
- // public IMapMode getMapMode() {
- // return AbstractActionFigure.this.getMapMode();
- // }
-
- @Override
- public Object getStereotypeRectangleConstraint() {
- GridData constraintStereotypeRect0 = new GridData();
- constraintStereotypeRect0.verticalAlignment = GridData.BEGINNING;
- constraintStereotypeRect0.horizontalAlignment = GridData.FILL;
- constraintStereotypeRect0.horizontalIndent = 0;
- constraintStereotypeRect0.horizontalSpan = 1;
- constraintStereotypeRect0.verticalSpan = 1;
- constraintStereotypeRect0.grabExcessHorizontalSpace = false;
- constraintStereotypeRect0.grabExcessVerticalSpace = false;
- return constraintStereotypeRect0;
- }
- };
- // createContents();
- }
-
- /**
- * Refresh the layout of the figure
- */
- protected void refreshLayout() {
- }
-
- /**
- * Sets the stereotypes for this figure.
- * <p>
- * This implementation checks if the specified string is null or not.
- * <ul>
- * <li>if the string is <code>null</code>, it removes the label representing the stereotypes.</li>
- * <li>if this is not <code>null</code>, it creates the stereotype label if needed and displays the specified string.</li>
- * </ul>
- * </p>
- *
- * @param stereotypes
- * the string representing the stereotypes to be displayed
- * @param image
- * the image representing the stereotypes to be displayed
- * @see org.eclipse.papyrus.uml.diagram.common.figure.node.IPapyrusUMLElementFigure#setStereotypeDisplay(java.lang.String, org.eclipse.swt.graphics.Image)
- */
- @Override
- public void setStereotypeDisplay(String stereotypes, Image image) {
- stereotypeHelper.setStereotypeDisplay(stereotypes, image);
- refreshLayout();
- }
-
- /**
- * Sets the stereotypes properties for this figure.
- * <p>
- * This implementation checks if the specified string is null or not.
- * <ul>
- * <li>if the string is <code>null</code>, it removes the label representing the stereotypes properties with brace.</li>
- * <li>if this is not <code>null</code>, it creates the stereotype properties label if needed and displays the specified string.</li>
- * </ul>
- * </p>
- *
- * @param stereotypeProperties
- * the string representing the stereotype properties to be
- * displayed
- */
- @Override
- public void setStereotypePropertiesInBrace(String stereotypeProperties) {
- stereotypeHelper.setStereotypePropertiesInBrace(stereotypeProperties);
- refreshLayout();
- }
-
- /**
- * displays the new string corresponding to the list of stereotypes.
- *
- * if the string is <code>null</code>, then the figure that displays the
- * stereotype label is removed from the NodeNamedElementFigure.
- *
- * @param stereotypeProperties
- * the string to be displayed.
- */
- @Override
- public void setStereotypePropertiesInCompartment(String stereotypeProperties) {
- stereotypeHelper.setStereotypePropertiesInCompartment(stereotypeProperties);
- refreshLayout();
- }
-
- /**
- * @generated
- */
- @Override
- protected boolean useLocalCoordinates() {
- return myUseLocalCoordinates;
- }
-
- /**
- * @generated
- */
- protected void setUseLocalCoordinates(boolean useLocalCoordinates) {
- myUseLocalCoordinates = useLocalCoordinates;
- }
-
- /**
- * Gets the stereotype label.
- *
- * @return the stereotype label
- * @unused
- * @deprecated
- */
- @Deprecated
- @Override
- public PapyrusWrappingLabel getStereotypesLabel() {
- return null;// fActionStereotypeLabel;
- }
-
- /**
- * Get the label of the action
- */
- public abstract CenteredWrappedLabel getActionLabel();
-
- /**
- * Get the map mode of the corresponding edit part
- */
- public abstract IMapMode getMapMode();
-}
+/***************************************************************************** + * 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: + * Emilien Perico (Atos Origin) emilien.perico@atosorigin.com - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.draw2d.GridData; +import org.eclipse.draw2d.GridLayout; +import org.eclipse.draw2d.RoundedRectangle; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode; +import org.eclipse.papyrus.infra.gmfdiag.common.figure.node.PapyrusWrappingLabel; +import org.eclipse.papyrus.uml.diagram.common.figure.node.CenteredWrappedLabel; +import org.eclipse.papyrus.uml.diagram.common.figure.node.IPapyrusNodeUMLElementFigure; +import org.eclipse.papyrus.uml.diagram.common.helper.StereotypeFigureHelper; +import org.eclipse.swt.graphics.Image; + +/** + * AbstractActionFigure is an abstract super class for Action figures in order + * to manage stereotype display + * + * @generated + */ +public abstract class AbstractActionFigure extends RoundedRectangle implements IPapyrusNodeUMLElementFigure { + + /** @generated */ + private boolean myUseLocalCoordinates = false; + + /** The helper which handles stereotype aspects */ + private StereotypeFigureHelper stereotypeHelper; + + /** + * use StereotypeFigureHelper + */ + public AbstractActionFigure() { + GridLayout layoutThis = new GridLayout(); + layoutThis.numColumns = 1; + layoutThis.makeColumnsEqualWidth = true; + setLayoutManager(layoutThis); + setCornerDimensions(new Dimension(getMapMode().DPtoLP(16), getMapMode().DPtoLP(16))); + setLineWidth(1); + // use StereotypeFigureHelper + stereotypeHelper = new StereotypeFigureHelper(this) { + + // @Override + // public IMapMode getMapMode() { + // return AbstractActionFigure.this.getMapMode(); + // } + + @Override + public Object getStereotypeRectangleConstraint() { + GridData constraintStereotypeRect0 = new GridData(); + constraintStereotypeRect0.verticalAlignment = GridData.BEGINNING; + constraintStereotypeRect0.horizontalAlignment = GridData.FILL; + constraintStereotypeRect0.horizontalIndent = 0; + constraintStereotypeRect0.horizontalSpan = 1; + constraintStereotypeRect0.verticalSpan = 1; + constraintStereotypeRect0.grabExcessHorizontalSpace = false; + constraintStereotypeRect0.grabExcessVerticalSpace = false; + return constraintStereotypeRect0; + } + }; + // createContents(); + } + + /** + * Refresh the layout of the figure + */ + protected void refreshLayout() { + } + + /** + * Sets the stereotypes for this figure. + * <p> + * This implementation checks if the specified string is null or not. + * <ul> + * <li>if the string is <code>null</code>, it removes the label representing the stereotypes.</li> + * <li>if this is not <code>null</code>, it creates the stereotype label if needed and displays the specified string.</li> + * </ul> + * </p> + * + * @param stereotypes + * the string representing the stereotypes to be displayed + * @param image + * the image representing the stereotypes to be displayed + * @see org.eclipse.papyrus.uml.diagram.common.figure.node.IPapyrusUMLElementFigure#setStereotypeDisplay(java.lang.String, org.eclipse.swt.graphics.Image) + */ + @Override + public void setStereotypeDisplay(String stereotypes, Image image) { + stereotypeHelper.setStereotypeDisplay(stereotypes, image); + refreshLayout(); + } + + /** + * Sets the stereotypes properties for this figure. + * <p> + * This implementation checks if the specified string is null or not. + * <ul> + * <li>if the string is <code>null</code>, it removes the label representing the stereotypes properties with brace.</li> + * <li>if this is not <code>null</code>, it creates the stereotype properties label if needed and displays the specified string.</li> + * </ul> + * </p> + * + * @param stereotypeProperties + * the string representing the stereotype properties to be + * displayed + */ + @Override + public void setStereotypePropertiesInBrace(String stereotypeProperties) { + stereotypeHelper.setStereotypePropertiesInBrace(stereotypeProperties); + refreshLayout(); + } + + /** + * displays the new string corresponding to the list of stereotypes. + * + * if the string is <code>null</code>, then the figure that displays the + * stereotype label is removed from the NodeNamedElementFigure. + * + * @param stereotypeProperties + * the string to be displayed. + */ + @Override + public void setStereotypePropertiesInCompartment(String stereotypeProperties) { + stereotypeHelper.setStereotypePropertiesInCompartment(stereotypeProperties); + refreshLayout(); + } + + /** + * @generated + */ + @Override + protected boolean useLocalCoordinates() { + return myUseLocalCoordinates; + } + + /** + * @generated + */ + protected void setUseLocalCoordinates(boolean useLocalCoordinates) { + myUseLocalCoordinates = useLocalCoordinates; + } + + /** + * Gets the stereotype label. + * + * @return the stereotype label + * @unused + * @deprecated + */ + @Deprecated + @Override + public PapyrusWrappingLabel getStereotypesLabel() { + return null;// fActionStereotypeLabel; + } + + /** + * Get the label of the action + */ + public abstract CenteredWrappedLabel getActionLabel(); + + /** + * Get the map mode of the corresponding edit part + */ + public abstract IMapMode getMapMode(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ActivityEdgeFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ActivityEdgeFigure.java index 18d48a108aa..7700df4de19 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ActivityEdgeFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ActivityEdgeFigure.java @@ -1,109 +1,109 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.draw2d.PolylineDecoration;
-import org.eclipse.draw2d.RotatableDecoration;
-import org.eclipse.draw2d.geometry.PointList;
-import org.eclipse.gmf.runtime.diagram.ui.util.MeasurementUnitHelper;
-import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
-import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
-import org.eclipse.gmf.runtime.notation.MeasurementUnit;
-import org.eclipse.papyrus.uml.diagram.common.figure.edge.UMLEdgeFigure;
-
-/**
- * Basic figure for Activity Edge figure
- *
- * @author arthur daussy
- *
- */
-public class ActivityEdgeFigure extends UMLEdgeFigure {
-
- /**
- * @generated
- */
- private WrappedLabel fEdgeName;
-
- /**
- * Since the Activity diagram is using Pixel unit we can use this as constant
- */
- private static IMapMode mapNode = MeasurementUnitHelper.getMapMode(MeasurementUnit.PIXEL_LITERAL);
-
- /**
- * @generated
- */
- private WrappedLabel fEdgeWeight;
-
- /**
- * call the super constructor
- */
- public ActivityEdgeFigure() {
- super();
- this.setLineWidth(1);
- setTargetDecoration(createTargetDecoration());
- }
-
- /**
- * create the content
- */
- @Override
- protected void createContents() {
- super.createContents();
- }
-
- @Override
- public void resetStyle() {
- super.resetStyle();
- setTargetDecoration(createTargetDecoration());
- }
-
- /**
- * Scale changed from default 7:3 to 5:2 to make a
- * smaller arrow
- */
- private RotatableDecoration createTargetDecoration() {
- PolylineDecoration df = new PolylineDecoration();
- df.setLineWidth(1);
- PointList pl = new PointList();
- pl.addPoint(mapNode.DPtoLP(-2), mapNode.DPtoLP(2));
- pl.addPoint(mapNode.DPtoLP(0), mapNode.DPtoLP(0));
- pl.addPoint(mapNode.DPtoLP(-2), mapNode.DPtoLP(-2));
- df.setTemplate(pl);
- df.setScale(mapNode.DPtoLP(5), mapNode.DPtoLP(2));
- return df;
- }
-
- /**
- *
- */
- public WrappedLabel getEdgeName() {
- return fEdgeName;
- }
-
- /**
- *
- */
- public WrappedLabel getEdgeWeight() {
- return fEdgeWeight;
- }
-
- /**
- * Get the stereotype label of super class
- */
- @Override
- public WrappingLabel getAppliedStereotypeLabel() {
- return super.getAppliedStereotypeLabel();
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.draw2d.PolylineDecoration; +import org.eclipse.draw2d.RotatableDecoration; +import org.eclipse.draw2d.geometry.PointList; +import org.eclipse.gmf.runtime.diagram.ui.util.MeasurementUnitHelper; +import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; +import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode; +import org.eclipse.gmf.runtime.notation.MeasurementUnit; +import org.eclipse.papyrus.uml.diagram.common.figure.edge.UMLEdgeFigure; + +/** + * Basic figure for Activity Edge figure + * + * @author arthur daussy + * + */ +public class ActivityEdgeFigure extends UMLEdgeFigure { + + /** + * @generated + */ + private WrappedLabel fEdgeName; + + /** + * Since the Activity diagram is using Pixel unit we can use this as constant + */ + private static IMapMode mapNode = MeasurementUnitHelper.getMapMode(MeasurementUnit.PIXEL_LITERAL); + + /** + * @generated + */ + private WrappedLabel fEdgeWeight; + + /** + * call the super constructor + */ + public ActivityEdgeFigure() { + super(); + this.setLineWidth(1); + setTargetDecoration(createTargetDecoration()); + } + + /** + * create the content + */ + @Override + protected void createContents() { + super.createContents(); + } + + @Override + public void resetStyle() { + super.resetStyle(); + setTargetDecoration(createTargetDecoration()); + } + + /** + * Scale changed from default 7:3 to 5:2 to make a + * smaller arrow + */ + private RotatableDecoration createTargetDecoration() { + PolylineDecoration df = new PolylineDecoration(); + df.setLineWidth(1); + PointList pl = new PointList(); + pl.addPoint(mapNode.DPtoLP(-2), mapNode.DPtoLP(2)); + pl.addPoint(mapNode.DPtoLP(0), mapNode.DPtoLP(0)); + pl.addPoint(mapNode.DPtoLP(-2), mapNode.DPtoLP(-2)); + df.setTemplate(pl); + df.setScale(mapNode.DPtoLP(5), mapNode.DPtoLP(2)); + return df; + } + + /** + * + */ + public WrappedLabel getEdgeName() { + return fEdgeName; + } + + /** + * + */ + public WrappedLabel getEdgeWeight() { + return fEdgeWeight; + } + + /** + * Get the stereotype label of super class + */ + @Override + public WrappingLabel getAppliedStereotypeLabel() { + return super.getAppliedStereotypeLabel(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ActivityFigureCN.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ActivityFigureCN.java index a785f66e2ef..a8772296af2 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ActivityFigureCN.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ActivityFigureCN.java @@ -1,27 +1,27 @@ -package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.geometry.Dimension;
-
-public class ActivityFigureCN extends ActivityFigure {
-
- private class ActivityLayoutManagerCN extends ActivityLayoutManager {
-
- /**
- * For preferred size computation considers only the name label size
- */
- @Override
- protected Dimension calculatePreferredSize(IFigure container, int wHint, int hHint) {
- return getNameLabel() != null ? getNameLabel().getPreferredSize().getCopy() : new Dimension(10, 10);
- }
- }
-
- /**
- * Overrides layout manager because child activity nodes have less restricted minimum sizes
- * see bug 465804: [Activity] Cannot resizing "nested" Activity (it only gets larger and larger)
- */
- public ActivityFigureCN() {
- super();
- setLayoutManager(new ActivityLayoutManagerCN());
- }
-}
+package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.geometry.Dimension; + +public class ActivityFigureCN extends ActivityFigure { + + private class ActivityLayoutManagerCN extends ActivityLayoutManager { + + /** + * For preferred size computation considers only the name label size + */ + @Override + protected Dimension calculatePreferredSize(IFigure container, int wHint, int hHint) { + return getNameLabel() != null ? getNameLabel().getPreferredSize().getCopy() : new Dimension(10, 10); + } + } + + /** + * Overrides layout manager because child activity nodes have less restricted minimum sizes + * see bug 465804: [Activity] Cannot resizing "nested" Activity (it only gets larger and larger) + */ + public ActivityFigureCN() { + super(); + setLayoutManager(new ActivityLayoutManagerCN()); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ExceptionHandlerFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ExceptionHandlerFigure.java index 13dadbc0beb..665e02fff92 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ExceptionHandlerFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ExceptionHandlerFigure.java @@ -1,68 +1,68 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.draw2d.PolylineDecoration;
-import org.eclipse.draw2d.RotatableDecoration;
-import org.eclipse.draw2d.geometry.PointList;
-import org.eclipse.gmf.runtime.diagram.ui.util.MeasurementUnitHelper;
-import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
-import org.eclipse.gmf.runtime.notation.MeasurementUnit;
-import org.eclipse.papyrus.infra.gmfdiag.common.figure.edge.PapyrusEdgeFigure;
-import org.eclipse.swt.graphics.LineAttributes;
-import org.eclipse.uml2.uml.ExceptionHandler;
-
-/**
- * Figure for {@link ExceptionHandler}
- *
- * @author arthur daussy
- *
- */
-public class ExceptionHandlerFigure extends PapyrusEdgeFigure {
-
- /**
- * Since the Activity diagram is using Pixel unit we can use this as constant
- */
- private static IMapMode mapNode = MeasurementUnitHelper.getMapMode(MeasurementUnit.PIXEL_LITERAL);
-
- /**
- * @generated
- */
- public ExceptionHandlerFigure() {
- setTargetDecoration(createTargetDecoration());
- setLineAttributes(new LineAttributes(2));
- }
-
- @Override
- public void resetStyle() {
- super.resetStyle();
- setTargetDecoration(createTargetDecoration());
- }
-
- /**
- * @generated
- */
- private RotatableDecoration createTargetDecoration() {
- PolylineDecoration df = new PolylineDecoration();
- PointList pl = new PointList();
- pl.addPoint(mapNode.DPtoLP(-2), mapNode.DPtoLP(2));
- pl.addPoint(mapNode.DPtoLP(0), mapNode.DPtoLP(0));
- pl.addPoint(mapNode.DPtoLP(-2), mapNode.DPtoLP(-2));
- df.setTemplate(pl);
- df.setScale(mapNode.DPtoLP(7), mapNode.DPtoLP(3));
- df.setLineAttributes(new LineAttributes(2));
- return df;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.draw2d.PolylineDecoration; +import org.eclipse.draw2d.RotatableDecoration; +import org.eclipse.draw2d.geometry.PointList; +import org.eclipse.gmf.runtime.diagram.ui.util.MeasurementUnitHelper; +import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode; +import org.eclipse.gmf.runtime.notation.MeasurementUnit; +import org.eclipse.papyrus.infra.gmfdiag.common.figure.edge.PapyrusEdgeFigure; +import org.eclipse.swt.graphics.LineAttributes; +import org.eclipse.uml2.uml.ExceptionHandler; + +/** + * Figure for {@link ExceptionHandler} + * + * @author arthur daussy + * + */ +public class ExceptionHandlerFigure extends PapyrusEdgeFigure { + + /** + * Since the Activity diagram is using Pixel unit we can use this as constant + */ + private static IMapMode mapNode = MeasurementUnitHelper.getMapMode(MeasurementUnit.PIXEL_LITERAL); + + /** + * @generated + */ + public ExceptionHandlerFigure() { + setTargetDecoration(createTargetDecoration()); + setLineAttributes(new LineAttributes(2)); + } + + @Override + public void resetStyle() { + super.resetStyle(); + setTargetDecoration(createTargetDecoration()); + } + + /** + * @generated + */ + private RotatableDecoration createTargetDecoration() { + PolylineDecoration df = new PolylineDecoration(); + PointList pl = new PointList(); + pl.addPoint(mapNode.DPtoLP(-2), mapNode.DPtoLP(2)); + pl.addPoint(mapNode.DPtoLP(0), mapNode.DPtoLP(0)); + pl.addPoint(mapNode.DPtoLP(-2), mapNode.DPtoLP(-2)); + df.setTemplate(pl); + df.setScale(mapNode.DPtoLP(7), mapNode.DPtoLP(3)); + df.setLineAttributes(new LineAttributes(2)); + return df; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/InputPinFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/InputPinFigure.java index da75282ceb4..81ec5d3d80b 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/InputPinFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/InputPinFigure.java @@ -1,22 +1,22 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.Tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-/**
- * subclasses to specify the pin is input
- *
- */
-
-public class InputPinFigure extends PinFigure {
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.Tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +/** + * subclasses to specify the pin is input + * + */ + +public class InputPinFigure extends PinFigure { +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LinkFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LinkFigure.java index ff3aaa96040..d7569ab6c37 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LinkFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LinkFigure.java @@ -1,26 +1,26 @@ -/*****************************************************************************
- * Copyright (c) 2010 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation
- */
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.papyrus.uml.diagram.common.figure.edge.DashedEdgeFigure;
-
-/**
- * this link is used to show a dashed line
- *
- */
-public class LinkFigure extends DashedEdgeFigure {
-
- public LinkFigure() {
- super(false);
- }
-}
+/***************************************************************************** + * Copyright (c) 2010 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation + */ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.papyrus.uml.diagram.common.figure.edge.DashedEdgeFigure; + +/** + * this link is used to show a dashed line + * + */ +public class LinkFigure extends DashedEdgeFigure { + + public LinkFigure() { + super(false); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LocalPostconditionConstraintFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LocalPostconditionConstraintFigure.java index 2f8ef385c90..fc1232faa15 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LocalPostconditionConstraintFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LocalPostconditionConstraintFigure.java @@ -1,27 +1,27 @@ -/*****************************************************************************
- * Copyright (c) 2010 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.papyrus.uml.diagram.common.figure.node.ConstraintFigure;
-
-/**
- * this is a figure with the tag local Postcondition
- *
- */
-public class LocalPostconditionConstraintFigure extends ConstraintFigure {
-
- public LocalPostconditionConstraintFigure() {
- super("LocalPostCondtion");
- }
-}
+/***************************************************************************** + * Copyright (c) 2010 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.papyrus.uml.diagram.common.figure.node.ConstraintFigure; + +/** + * this is a figure with the tag local Postcondition + * + */ +public class LocalPostconditionConstraintFigure extends ConstraintFigure { + + public LocalPostconditionConstraintFigure() { + super("LocalPostCondtion"); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LocalPreconditionConstraintFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LocalPreconditionConstraintFigure.java index 88a498a15a5..adeb2a24f56 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LocalPreconditionConstraintFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/LocalPreconditionConstraintFigure.java @@ -1,27 +1,27 @@ -/*****************************************************************************
- * Copyright (c) 2010 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.papyrus.uml.diagram.common.figure.node.ConstraintFigure;
-
-/**
- * this is a figure with the tag local Precondition
- *
- */
-public class LocalPreconditionConstraintFigure extends ConstraintFigure {
-
- public LocalPreconditionConstraintFigure() {
- super("LocalPreCondtion");
- }
-}
+/***************************************************************************** + * Copyright (c) 2010 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.papyrus.uml.diagram.common.figure.node.ConstraintFigure; + +/** + * this is a figure with the tag local Precondition + * + */ +public class LocalPreconditionConstraintFigure extends ConstraintFigure { + + public LocalPreconditionConstraintFigure() { + super("LocalPreCondtion"); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/OutputPinFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/OutputPinFigure.java index 6e9e4b4df72..432483df480 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/OutputPinFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/OutputPinFigure.java @@ -1,21 +1,21 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.Tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-/**
- * subclass to specify the pin is output
- *
- */
-public class OutputPinFigure extends PinFigure {
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.Tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +/** + * subclass to specify the pin is output + * + */ +public class OutputPinFigure extends PinFigure { +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ParameterExceptionFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ParameterExceptionFigure.java index 7eeadec7ae3..e5bd6597743 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ParameterExceptionFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/ParameterExceptionFigure.java @@ -1,58 +1,58 @@ -/*****************************************************************************
- * Copyright (c) 2015 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.draw2d.Graphics;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.draw2d.geometry.Rectangle;
-
-public class ParameterExceptionFigure extends org.eclipse.draw2d.Label {
-
- private static final int HEIGHT = 20;
-
- private static final int WIDTH = 21;
-
- @Override
- public void paint(Graphics graphics) {
- graphics.pushState();
-
- //triangle points
- Point p1 = new Point(bounds.x + bounds.width / 2,
- bounds.y);
- Point p2 = new Point(bounds.x + bounds.width,
- bounds.y + bounds.height - 1);
- Point p3 = new Point(bounds.x,
- bounds.y + bounds.height - 1);
-
- graphics.setForegroundColor(getForegroundColor());
- graphics.setLineWidth(1);
-
- graphics.drawLine(p1, p2);
- graphics.drawLine(p2, p3);
- graphics.drawLine(p3, p1);
-
- graphics.popState();
- super.paint(graphics);
- }
-
- @Override
- public void setSize(int w, int h) {
- super.setSize(WIDTH, HEIGHT);
- }
-
- @Override
- public void setBounds(Rectangle rect) {
- super.setBounds(new Rectangle(rect.x, rect.y, WIDTH, HEIGHT));
- }
-}
+/***************************************************************************** + * Copyright (c) 2015 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.draw2d.Graphics; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Rectangle; + +public class ParameterExceptionFigure extends org.eclipse.draw2d.Label { + + private static final int HEIGHT = 20; + + private static final int WIDTH = 21; + + @Override + public void paint(Graphics graphics) { + graphics.pushState(); + + //triangle points + Point p1 = new Point(bounds.x + bounds.width / 2, + bounds.y); + Point p2 = new Point(bounds.x + bounds.width, + bounds.y + bounds.height - 1); + Point p3 = new Point(bounds.x, + bounds.y + bounds.height - 1); + + graphics.setForegroundColor(getForegroundColor()); + graphics.setLineWidth(1); + + graphics.drawLine(p1, p2); + graphics.drawLine(p2, p3); + graphics.drawLine(p3, p1); + + graphics.popState(); + super.paint(graphics); + } + + @Override + public void setSize(int w, int h) { + super.setSize(WIDTH, HEIGHT); + } + + @Override + public void setBounds(Rectangle rect) { + super.setBounds(new Rectangle(rect.x, rect.y, WIDTH, HEIGHT)); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/PinFigure.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/PinFigure.java index a1b213db90f..86e4a1bb503 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/PinFigure.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/PinFigure.java @@ -1,41 +1,41 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) Patrick.Tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.draw2d.PolylineShape;
-import org.eclipse.draw2d.RectangleFigure;
-import org.eclipse.draw2d.geometry.Dimension;
-
-
-/**
- * figure of a pin
- */
-public class PinFigure extends RectangleFigure {
-
- private PolylineShape fOptionalArrowFigure;
-
- public PinFigure() {
- this.setPreferredSize(new Dimension(16, 16));
- createContents();
- }
-
- private void createContents() {
- fOptionalArrowFigure = new PolylineShape();
- this.add(fOptionalArrowFigure);
- }
-
- public PolylineShape getOptionalArrowFigure() {
- return fOptionalArrowFigure;
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) Patrick.Tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.draw2d.PolylineShape; +import org.eclipse.draw2d.RectangleFigure; +import org.eclipse.draw2d.geometry.Dimension; + + +/** + * figure of a pin + */ +public class PinFigure extends RectangleFigure { + + private PolylineShape fOptionalArrowFigure; + + public PinFigure() { + this.setPreferredSize(new Dimension(16, 16)); + createContents(); + } + + private void createContents() { + fOptionalArrowFigure = new PolylineShape(); + this.add(fOptionalArrowFigure); + } + + public PolylineShape getOptionalArrowFigure() { + return fOptionalArrowFigure; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/SimpleLabel.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/SimpleLabel.java index 7b65bd127b2..d910cde0154 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/SimpleLabel.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/SimpleLabel.java @@ -1,53 +1,53 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- * Arthur Daussy - Bug 354622 - [ActivityDiagram] Object Flows selection prevent selecting other close elements.
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.draw2d.LayoutManager;
-import org.eclipse.draw2d.PositionConstants;
-import org.eclipse.draw2d.text.FlowContext;
-import org.eclipse.draw2d.text.ParagraphTextLayout;
-import org.eclipse.draw2d.text.TextFlow;
-import org.eclipse.draw2d.text.TextLayout;
-import org.eclipse.papyrus.infra.gmfdiag.common.figure.node.PapyrusWrappingLabel;
-
-/**
- * This class is a {@link PapyrusWrappingLabel}, which default behavior is set
- * differently :
- *
- * The text is centered and does not wrap on several lines.
- */
-public class SimpleLabel extends PapyrusWrappingLabel {
-
- /**
- * Construct an empty wrapping label with customized alignment.
- */
- public SimpleLabel() {
- super();
- setTextJustification(PositionConstants.CENTER);
- setAlignment(PositionConstants.CENTER);
- setTextWrap(true);
- // ensure wrapping performed at line breaks only (no auto wrap)
- if (getTextFigure().getChildren().size() > 0) {
- Object textFigChild = getTextFigure().getChildren().get(0);
- LayoutManager layoutMgr = getTextFigure().getLayoutManager();
- if (textFigChild instanceof TextFlow && layoutMgr instanceof FlowContext) {
- TextFlow textFlow = (TextFlow) textFigChild;
- TextLayout layout = new ParagraphTextLayout(textFlow, ParagraphTextLayout.WORD_WRAP_HARD);
- layout.setFlowContext((FlowContext) layoutMgr);
- textFlow.setLayoutManager(layout);
- }
- }
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * Arthur Daussy - Bug 354622 - [ActivityDiagram] Object Flows selection prevent selecting other close elements. + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.draw2d.LayoutManager; +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.draw2d.text.FlowContext; +import org.eclipse.draw2d.text.ParagraphTextLayout; +import org.eclipse.draw2d.text.TextFlow; +import org.eclipse.draw2d.text.TextLayout; +import org.eclipse.papyrus.infra.gmfdiag.common.figure.node.PapyrusWrappingLabel; + +/** + * This class is a {@link PapyrusWrappingLabel}, which default behavior is set + * differently : + * + * The text is centered and does not wrap on several lines. + */ +public class SimpleLabel extends PapyrusWrappingLabel { + + /** + * Construct an empty wrapping label with customized alignment. + */ + public SimpleLabel() { + super(); + setTextJustification(PositionConstants.CENTER); + setAlignment(PositionConstants.CENTER); + setTextWrap(true); + // ensure wrapping performed at line breaks only (no auto wrap) + if (getTextFigure().getChildren().size() > 0) { + Object textFigChild = getTextFigure().getChildren().get(0); + LayoutManager layoutMgr = getTextFigure().getLayoutManager(); + if (textFigChild instanceof TextFlow && layoutMgr instanceof FlowContext) { + TextFlow textFlow = (TextFlow) textFigChild; + TextLayout layout = new ParagraphTextLayout(textFlow, ParagraphTextLayout.WORD_WRAP_HARD); + layout.setFlowContext((FlowContext) layoutMgr); + textFlow.setLayoutManager(layout); + } + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/WrappedLabel.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/WrappedLabel.java index c2c86fb66c7..c498b716807 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/WrappedLabel.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/figures/WrappedLabel.java @@ -1,37 +1,37 @@ -/*****************************************************************************
- * Copyright (c) 2009 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.figures;
-
-import org.eclipse.draw2d.PositionConstants;
-import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
-import org.eclipse.papyrus.infra.gmfdiag.common.figure.node.PapyrusWrappingLabel;
-
-/**
- * This class is a {@link WrappingLabel}, which default behavior is set
- * differently :
- *
- * The text is left aligned and automatically wraps on several lines.
- */
-public class WrappedLabel extends PapyrusWrappingLabel {
-
- /**
- * Construct an empty wrapping label with customized alignment.
- */
- public WrappedLabel() {
- super();
- setTextJustification(PositionConstants.LEFT);
- setAlignment(PositionConstants.LEFT);
- setTextWrap(true);
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.figures; + +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel; +import org.eclipse.papyrus.infra.gmfdiag.common.figure.node.PapyrusWrappingLabel; + +/** + * This class is a {@link WrappingLabel}, which default behavior is set + * differently : + * + * The text is left aligned and automatically wraps on several lines. + */ +public class WrappedLabel extends PapyrusWrappingLabel { + + /** + * Construct an empty wrapping label with customized alignment. + */ + public WrappedLabel() { + super(); + setTextJustification(PositionConstants.LEFT); + setAlignment(PositionConstants.LEFT); + setTextWrap(true); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/handlers/AbstractSynchronizePinsAndParameters.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/handlers/AbstractSynchronizePinsAndParameters.java index aa786d3336c..7e613d5a644 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/handlers/AbstractSynchronizePinsAndParameters.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/handlers/AbstractSynchronizePinsAndParameters.java @@ -1,57 +1,57 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- * Arthur Daussy - 371712 : [Activitydiagram] Papyrus should provide a way to manually resynchronize pins and parameters on Call Actions
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.handlers;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.eclipse.uml2.uml.CallAction;
-
-/**
- * Abstract handler to launch a Synchronization of pins on {@link CallAction}
- *
- * @author adaussy
- *
- */
-public abstract class AbstractSynchronizePinsAndParameters extends AbstractHandler {
-
- /**
- * Path the icon handler
- */
- public static final String REFRESH_PIN_ICON = "icons/obj16/RefreshPin.png";
-
- /**
- * Status code warning that an exception was ignored.
- * Set to 9 to be consistent with CommonUIStatusCodes.
- */
- public static final int IGNORED_EXCEPTION_WARNING = 9;
-
- /**
- * Get the icon which represent the action of manual synchronization of pins
- *
- * @return
- */
- protected static Image getIcon() {
- Image result = UMLDiagramEditorPlugin.getInstance().getImageRegistry().get(REFRESH_PIN_ICON);
- if (result == null) {
- ImageDescriptor image = AbstractUIPlugin.imageDescriptorFromPlugin(UMLDiagramEditorPlugin.ID, REFRESH_PIN_ICON);
- UMLDiagramEditorPlugin.getInstance().getImageRegistry().put(REFRESH_PIN_ICON, image);
- result = UMLDiagramEditorPlugin.getInstance().getImageRegistry().get(REFRESH_PIN_ICON);
- }
- return result;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * Arthur Daussy - 371712 : [Activitydiagram] Papyrus should provide a way to manually resynchronize pins and parameters on Call Actions + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.handlers; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.swt.graphics.Image; +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.eclipse.uml2.uml.CallAction; + +/** + * Abstract handler to launch a Synchronization of pins on {@link CallAction} + * + * @author adaussy + * + */ +public abstract class AbstractSynchronizePinsAndParameters extends AbstractHandler { + + /** + * Path the icon handler + */ + public static final String REFRESH_PIN_ICON = "icons/obj16/RefreshPin.png"; + + /** + * Status code warning that an exception was ignored. + * Set to 9 to be consistent with CommonUIStatusCodes. + */ + public static final int IGNORED_EXCEPTION_WARNING = 9; + + /** + * Get the icon which represent the action of manual synchronization of pins + * + * @return + */ + protected static Image getIcon() { + Image result = UMLDiagramEditorPlugin.getInstance().getImageRegistry().get(REFRESH_PIN_ICON); + if (result == null) { + ImageDescriptor image = AbstractUIPlugin.imageDescriptorFromPlugin(UMLDiagramEditorPlugin.ID, REFRESH_PIN_ICON); + UMLDiagramEditorPlugin.getInstance().getImageRegistry().put(REFRESH_PIN_ICON, image); + result = UMLDiagramEditorPlugin.getInstance().getImageRegistry().get(REFRESH_PIN_ICON); + } + return result; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityFigureDrawer.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityFigureDrawer.java index 46310a7630f..8bb402af7a5 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityFigureDrawer.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityFigureDrawer.java @@ -1,291 +1,291 @@ -/*****************************************************************************
- * Copyright (c) 2009 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.draw2d.AbstractPointListShape;
-import org.eclipse.draw2d.Polygon;
-import org.eclipse.draw2d.PolylineShape;
-import org.eclipse.draw2d.PositionConstants;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.gef.editparts.AbstractGraphicalEditPart;
-import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
-import org.eclipse.gmf.runtime.notation.Bounds;
-import org.eclipse.gmf.runtime.notation.Shape;
-
-/**
- * The ActivityFigureDrawer helps drawing representations for activity diagram
- * out of a Polyline figure
- */
-public class ActivityFigureDrawer {
-
- /**
- * The template for drawing a triangle figure
- */
- private static final List<Point> TRIANGLE_FIGURE = new ArrayList<Point>(3);
- static {
- TRIANGLE_FIGURE.add(new Point(0, 5));
- TRIANGLE_FIGURE.add(new Point(5, 5));
- TRIANGLE_FIGURE.add(new Point(3, 0));
- }
-
- /**
- * The template size point for translating a pin arrow figure
- */
- private static final Point TRIANGLE_FIGURE_SIZE = new Point(5, 5);
-
- /**
- * The template for drawing a rake figure
- */
- private static final List<Point> RAKE_FIGURE = new ArrayList<Point>(8);
- static {
- RAKE_FIGURE.add(new Point(0, 10));
- RAKE_FIGURE.add(new Point(0, 4));
- RAKE_FIGURE.add(new Point(5, 4));
- RAKE_FIGURE.add(new Point(5, 0));
- RAKE_FIGURE.add(new Point(5, 10));
- RAKE_FIGURE.add(new Point(5, 4));
- RAKE_FIGURE.add(new Point(10, 4));
- RAKE_FIGURE.add(new Point(10, 10));
- }
-
- /**
- * The template point for translating a rake figure
- */
- private static final Point RAKE_FIGURE_TRANSLATION = new Point(-16, -12);
-
- /**
- * The template for drawing an pin arrow figure turned right
- */
- private static final List<Point> RIGHT_PIN_ARROW_FIGURE = new ArrayList<Point>(8);
- static {
- RIGHT_PIN_ARROW_FIGURE.add(new Point(4, 2));
- RIGHT_PIN_ARROW_FIGURE.add(new Point(7, 4));
- RIGHT_PIN_ARROW_FIGURE.add(new Point(1, 4));
- RIGHT_PIN_ARROW_FIGURE.add(new Point(7, 4));
- RIGHT_PIN_ARROW_FIGURE.add(new Point(4, 6));
- }
-
- /**
- * The template for drawing a pin arrow figure turned left
- */
- private static final List<Point> LEFT_PIN_ARROW_FIGURE = new ArrayList<Point>(8);
- static {
- LEFT_PIN_ARROW_FIGURE.add(new Point(4, 2));
- LEFT_PIN_ARROW_FIGURE.add(new Point(1, 4));
- LEFT_PIN_ARROW_FIGURE.add(new Point(7, 4));
- LEFT_PIN_ARROW_FIGURE.add(new Point(1, 4));
- LEFT_PIN_ARROW_FIGURE.add(new Point(4, 6));
- }
-
- /**
- * The template for drawing a pin arrow figure turned up
- */
- private static final List<Point> UP_PIN_ARROW_FIGURE = new ArrayList<Point>(8);
- static {
- UP_PIN_ARROW_FIGURE.add(new Point(2, 4));
- UP_PIN_ARROW_FIGURE.add(new Point(4, 1));
- UP_PIN_ARROW_FIGURE.add(new Point(4, 7));
- UP_PIN_ARROW_FIGURE.add(new Point(4, 1));
- UP_PIN_ARROW_FIGURE.add(new Point(6, 4));
- }
-
- /**
- * The template for drawing a pin arrow figure turned down
- */
- private static final List<Point> DOWN_PIN_ARROW_FIGURE = new ArrayList<Point>(8);
- static {
- DOWN_PIN_ARROW_FIGURE.add(new Point(2, 4));
- DOWN_PIN_ARROW_FIGURE.add(new Point(4, 7));
- DOWN_PIN_ARROW_FIGURE.add(new Point(4, 1));
- DOWN_PIN_ARROW_FIGURE.add(new Point(4, 7));
- DOWN_PIN_ARROW_FIGURE.add(new Point(6, 4));
- }
-
- /**
- * The template size point for translating a pin arrow figure
- */
- private static final Point PIN_ARROW_FIGURE_SIZE = new Point(8, 8);
-
- /**
- * Get the direction opposite to the parameter one
- *
- * @param direction
- * {@link PositionConstants#NORTH}, {@link PositionConstants#EAST}, {@link PositionConstants#SOUTH} or {@link PositionConstants#WEST}
- * @return the direction at the opposite or {@link PositionConstants#NONE}
- */
- public static int getOppositeDirection(int direction) {
- switch (direction) {
- case PositionConstants.NORTH:
- return PositionConstants.SOUTH;
- case PositionConstants.EAST:
- return PositionConstants.WEST;
- case PositionConstants.SOUTH:
- return PositionConstants.NORTH;
- case PositionConstants.WEST:
- return PositionConstants.EAST;
- default:
- return PositionConstants.NONE;
- }
- }
-
- /**
- * Draw the triangle or refresh it
- *
- * @param triangle
- * figure which contains the triangle
- * @param iMapMode
- * the map mode to translate points
- * @param parentDimension
- * the dimension of the parent
- */
- public static void redrawTriangle(Polygon triangle, IMapMode iMapMode, Dimension parentDimension) {
- triangle.removeAllPoints();
- double xScale = parentDimension.preciseWidth() / TRIANGLE_FIGURE_SIZE.x;
- double yScale = parentDimension.preciseHeight() / TRIANGLE_FIGURE_SIZE.y;
- for (Point refPoint : TRIANGLE_FIGURE) {
- Point translatedPoint = new Point(refPoint).scale(xScale, yScale);
- iMapMode.DPtoLP(translatedPoint);
- triangle.addPoint(translatedPoint);
- }
- }
-
- /**
- * Draw the rake or refresh it
- *
- * @param rake
- * figure which contains the rake
- * @param iMapMode
- * the map mode to translate points
- * @param parentDimension
- * the dimension of the parent
- */
- public static void redrawRake(AbstractPointListShape rake, IMapMode iMapMode, Dimension parentDimension) {
- rake.removeAllPoints();
- Point translationPoint = new Point();
- if (!(rake instanceof PolylineShape)) {
- // do not translate for PolylineShape since bounds will be adapted
- new Point(RAKE_FIGURE_TRANSLATION);
- translationPoint.translate(parentDimension);
- }
- for (Point refPoint : RAKE_FIGURE) {
- Point translatedPoint = new Point(refPoint).translate(translationPoint);
- iMapMode.DPtoLP(translatedPoint);
- rake.addPoint(translatedPoint);
- }
- if (rake instanceof PolylineShape) {
- // adapt bounds for PolylineShape
- Point loc = rake.getParent().getBounds().getLocation().getCopy().translate(parentDimension).translate(RAKE_FIGURE_TRANSLATION);
- Rectangle b = new Rectangle(loc, new Dimension(-RAKE_FIGURE_TRANSLATION.x, -RAKE_FIGURE_TRANSLATION.y));
- ((PolylineShape) rake).setBounds(b);
- }
- }
-
- /**
- * Draw the pin arrow or refresh it
- *
- * @param arrow
- * figure which contains the arrow
- * @param iMapMode
- * the map mode to translate points
- * @param parentDimension
- * the dimension of the parent
- * @param direction
- * the direction to which the arrow is directed : {@link PositionConstants#SOUTH}, {@link PositionConstants#NORTH}, {@link PositionConstants#EAST}, {@link PositionConstants#WEST}
- */
- public static void redrawPinArrow(AbstractPointListShape arrow, IMapMode iMapMode, Dimension parentDimension, int direction) {
- arrow.removeAllPoints();
- List<Point> template;
- switch (direction) {
- case PositionConstants.NORTH:
- template = UP_PIN_ARROW_FIGURE;
- break;
- case PositionConstants.SOUTH:
- template = DOWN_PIN_ARROW_FIGURE;
- break;
- case PositionConstants.WEST:
- template = LEFT_PIN_ARROW_FIGURE;
- break;
- case PositionConstants.EAST:
- default:
- template = RIGHT_PIN_ARROW_FIGURE;
- break;
- }
- double xScale = parentDimension.preciseWidth() / PIN_ARROW_FIGURE_SIZE.x;
- double yScale = parentDimension.preciseHeight() / PIN_ARROW_FIGURE_SIZE.y;
- for (Point refPoint : template) {
- Point translatedPoint = new Point(refPoint).scale(xScale, yScale);
- iMapMode.DPtoLP(translatedPoint);
- arrow.addPoint(translatedPoint);
- }
- if (arrow instanceof PolylineShape) {
- // adapt bounds for PolylineShape
- ((PolylineShape) arrow).setBounds(arrow.getParent().getBounds());
- }
- }
-
- /**
- * Undraw the polyline figure
- *
- * @param figure
- * figure to undraw
- */
- public static void undrawFigure(AbstractPointListShape figure) {
- figure.removeAllPoints();
- }
-
- /**
- * Get the size of the edit part node
- *
- * @param editPart
- * edit part
- * @param dimensionChangeEvent
- * the change dimension event or null
- * @return the node size
- */
- public static Dimension getNodeSize(AbstractGraphicalEditPart editPart, Notification dimensionChangeEvent) {
- Bounds bounds = null;
- // if a bounds change is notified, size may have changed, otherwise, get
- // size from model
- // shape
- if (dimensionChangeEvent != null && dimensionChangeEvent.getNotifier() instanceof Bounds) {
- bounds = (Bounds) dimensionChangeEvent.getNotifier();
- } else if (editPart.getModel() instanceof Shape) {
- Shape shape = (Shape) editPart.getModel();
- if (shape.getLayoutConstraint() instanceof Bounds) {
- bounds = (Bounds) shape.getLayoutConstraint();
- }
- }
- Dimension size = null;
- if (bounds != null) {
- size = new Dimension(bounds.getWidth(), bounds.getHeight());
- }
- if (size == null || size.isEmpty()) {
- // recover the exact size from the figure
- Dimension preferredSize = editPart.getFigure().getPreferredSize(size.width, size.height);
- if (size.width <= 0) {
- size.width = preferredSize.width;
- }
- if (size.height <= 0) {
- size.height = preferredSize.height;
- }
- }
- return size;
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.draw2d.AbstractPointListShape; +import org.eclipse.draw2d.Polygon; +import org.eclipse.draw2d.PolylineShape; +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.gef.editparts.AbstractGraphicalEditPart; +import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode; +import org.eclipse.gmf.runtime.notation.Bounds; +import org.eclipse.gmf.runtime.notation.Shape; + +/** + * The ActivityFigureDrawer helps drawing representations for activity diagram + * out of a Polyline figure + */ +public class ActivityFigureDrawer { + + /** + * The template for drawing a triangle figure + */ + private static final List<Point> TRIANGLE_FIGURE = new ArrayList<Point>(3); + static { + TRIANGLE_FIGURE.add(new Point(0, 5)); + TRIANGLE_FIGURE.add(new Point(5, 5)); + TRIANGLE_FIGURE.add(new Point(3, 0)); + } + + /** + * The template size point for translating a pin arrow figure + */ + private static final Point TRIANGLE_FIGURE_SIZE = new Point(5, 5); + + /** + * The template for drawing a rake figure + */ + private static final List<Point> RAKE_FIGURE = new ArrayList<Point>(8); + static { + RAKE_FIGURE.add(new Point(0, 10)); + RAKE_FIGURE.add(new Point(0, 4)); + RAKE_FIGURE.add(new Point(5, 4)); + RAKE_FIGURE.add(new Point(5, 0)); + RAKE_FIGURE.add(new Point(5, 10)); + RAKE_FIGURE.add(new Point(5, 4)); + RAKE_FIGURE.add(new Point(10, 4)); + RAKE_FIGURE.add(new Point(10, 10)); + } + + /** + * The template point for translating a rake figure + */ + private static final Point RAKE_FIGURE_TRANSLATION = new Point(-16, -12); + + /** + * The template for drawing an pin arrow figure turned right + */ + private static final List<Point> RIGHT_PIN_ARROW_FIGURE = new ArrayList<Point>(8); + static { + RIGHT_PIN_ARROW_FIGURE.add(new Point(4, 2)); + RIGHT_PIN_ARROW_FIGURE.add(new Point(7, 4)); + RIGHT_PIN_ARROW_FIGURE.add(new Point(1, 4)); + RIGHT_PIN_ARROW_FIGURE.add(new Point(7, 4)); + RIGHT_PIN_ARROW_FIGURE.add(new Point(4, 6)); + } + + /** + * The template for drawing a pin arrow figure turned left + */ + private static final List<Point> LEFT_PIN_ARROW_FIGURE = new ArrayList<Point>(8); + static { + LEFT_PIN_ARROW_FIGURE.add(new Point(4, 2)); + LEFT_PIN_ARROW_FIGURE.add(new Point(1, 4)); + LEFT_PIN_ARROW_FIGURE.add(new Point(7, 4)); + LEFT_PIN_ARROW_FIGURE.add(new Point(1, 4)); + LEFT_PIN_ARROW_FIGURE.add(new Point(4, 6)); + } + + /** + * The template for drawing a pin arrow figure turned up + */ + private static final List<Point> UP_PIN_ARROW_FIGURE = new ArrayList<Point>(8); + static { + UP_PIN_ARROW_FIGURE.add(new Point(2, 4)); + UP_PIN_ARROW_FIGURE.add(new Point(4, 1)); + UP_PIN_ARROW_FIGURE.add(new Point(4, 7)); + UP_PIN_ARROW_FIGURE.add(new Point(4, 1)); + UP_PIN_ARROW_FIGURE.add(new Point(6, 4)); + } + + /** + * The template for drawing a pin arrow figure turned down + */ + private static final List<Point> DOWN_PIN_ARROW_FIGURE = new ArrayList<Point>(8); + static { + DOWN_PIN_ARROW_FIGURE.add(new Point(2, 4)); + DOWN_PIN_ARROW_FIGURE.add(new Point(4, 7)); + DOWN_PIN_ARROW_FIGURE.add(new Point(4, 1)); + DOWN_PIN_ARROW_FIGURE.add(new Point(4, 7)); + DOWN_PIN_ARROW_FIGURE.add(new Point(6, 4)); + } + + /** + * The template size point for translating a pin arrow figure + */ + private static final Point PIN_ARROW_FIGURE_SIZE = new Point(8, 8); + + /** + * Get the direction opposite to the parameter one + * + * @param direction + * {@link PositionConstants#NORTH}, {@link PositionConstants#EAST}, {@link PositionConstants#SOUTH} or {@link PositionConstants#WEST} + * @return the direction at the opposite or {@link PositionConstants#NONE} + */ + public static int getOppositeDirection(int direction) { + switch (direction) { + case PositionConstants.NORTH: + return PositionConstants.SOUTH; + case PositionConstants.EAST: + return PositionConstants.WEST; + case PositionConstants.SOUTH: + return PositionConstants.NORTH; + case PositionConstants.WEST: + return PositionConstants.EAST; + default: + return PositionConstants.NONE; + } + } + + /** + * Draw the triangle or refresh it + * + * @param triangle + * figure which contains the triangle + * @param iMapMode + * the map mode to translate points + * @param parentDimension + * the dimension of the parent + */ + public static void redrawTriangle(Polygon triangle, IMapMode iMapMode, Dimension parentDimension) { + triangle.removeAllPoints(); + double xScale = parentDimension.preciseWidth() / TRIANGLE_FIGURE_SIZE.x; + double yScale = parentDimension.preciseHeight() / TRIANGLE_FIGURE_SIZE.y; + for (Point refPoint : TRIANGLE_FIGURE) { + Point translatedPoint = new Point(refPoint).scale(xScale, yScale); + iMapMode.DPtoLP(translatedPoint); + triangle.addPoint(translatedPoint); + } + } + + /** + * Draw the rake or refresh it + * + * @param rake + * figure which contains the rake + * @param iMapMode + * the map mode to translate points + * @param parentDimension + * the dimension of the parent + */ + public static void redrawRake(AbstractPointListShape rake, IMapMode iMapMode, Dimension parentDimension) { + rake.removeAllPoints(); + Point translationPoint = new Point(); + if (!(rake instanceof PolylineShape)) { + // do not translate for PolylineShape since bounds will be adapted + new Point(RAKE_FIGURE_TRANSLATION); + translationPoint.translate(parentDimension); + } + for (Point refPoint : RAKE_FIGURE) { + Point translatedPoint = new Point(refPoint).translate(translationPoint); + iMapMode.DPtoLP(translatedPoint); + rake.addPoint(translatedPoint); + } + if (rake instanceof PolylineShape) { + // adapt bounds for PolylineShape + Point loc = rake.getParent().getBounds().getLocation().getCopy().translate(parentDimension).translate(RAKE_FIGURE_TRANSLATION); + Rectangle b = new Rectangle(loc, new Dimension(-RAKE_FIGURE_TRANSLATION.x, -RAKE_FIGURE_TRANSLATION.y)); + ((PolylineShape) rake).setBounds(b); + } + } + + /** + * Draw the pin arrow or refresh it + * + * @param arrow + * figure which contains the arrow + * @param iMapMode + * the map mode to translate points + * @param parentDimension + * the dimension of the parent + * @param direction + * the direction to which the arrow is directed : {@link PositionConstants#SOUTH}, {@link PositionConstants#NORTH}, {@link PositionConstants#EAST}, {@link PositionConstants#WEST} + */ + public static void redrawPinArrow(AbstractPointListShape arrow, IMapMode iMapMode, Dimension parentDimension, int direction) { + arrow.removeAllPoints(); + List<Point> template; + switch (direction) { + case PositionConstants.NORTH: + template = UP_PIN_ARROW_FIGURE; + break; + case PositionConstants.SOUTH: + template = DOWN_PIN_ARROW_FIGURE; + break; + case PositionConstants.WEST: + template = LEFT_PIN_ARROW_FIGURE; + break; + case PositionConstants.EAST: + default: + template = RIGHT_PIN_ARROW_FIGURE; + break; + } + double xScale = parentDimension.preciseWidth() / PIN_ARROW_FIGURE_SIZE.x; + double yScale = parentDimension.preciseHeight() / PIN_ARROW_FIGURE_SIZE.y; + for (Point refPoint : template) { + Point translatedPoint = new Point(refPoint).scale(xScale, yScale); + iMapMode.DPtoLP(translatedPoint); + arrow.addPoint(translatedPoint); + } + if (arrow instanceof PolylineShape) { + // adapt bounds for PolylineShape + ((PolylineShape) arrow).setBounds(arrow.getParent().getBounds()); + } + } + + /** + * Undraw the polyline figure + * + * @param figure + * figure to undraw + */ + public static void undrawFigure(AbstractPointListShape figure) { + figure.removeAllPoints(); + } + + /** + * Get the size of the edit part node + * + * @param editPart + * edit part + * @param dimensionChangeEvent + * the change dimension event or null + * @return the node size + */ + public static Dimension getNodeSize(AbstractGraphicalEditPart editPart, Notification dimensionChangeEvent) { + Bounds bounds = null; + // if a bounds change is notified, size may have changed, otherwise, get + // size from model + // shape + if (dimensionChangeEvent != null && dimensionChangeEvent.getNotifier() instanceof Bounds) { + bounds = (Bounds) dimensionChangeEvent.getNotifier(); + } else if (editPart.getModel() instanceof Shape) { + Shape shape = (Shape) editPart.getModel(); + if (shape.getLayoutConstraint() instanceof Bounds) { + bounds = (Bounds) shape.getLayoutConstraint(); + } + } + Dimension size = null; + if (bounds != null) { + size = new Dimension(bounds.getWidth(), bounds.getHeight()); + } + if (size == null || size.isEmpty()) { + // recover the exact size from the figure + Dimension preferredSize = editPart.getFigure().getPreferredSize(size.width, size.height); + if (size.width <= 0) { + size.width = preferredSize.width; + } + if (size.height <= 0) { + size.height = preferredSize.height; + } + } + return size; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityLinkMappingHelper.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityLinkMappingHelper.java index 3ca0273f5ab..ac2512c0a51 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityLinkMappingHelper.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityLinkMappingHelper.java @@ -1,104 +1,104 @@ -/*****************************************************************************
- * Copyright (c) 2009 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import java.util.Collection;
-import java.util.Collections;
-
-import org.eclipse.papyrus.uml.diagram.common.helper.ILinkMappingHelper;
-import org.eclipse.papyrus.uml.diagram.common.helper.LinkMappingHelper;
-import org.eclipse.papyrus.uml.diagram.common.helper.LinkMappingHelper.CommonSourceUMLSwitch;
-import org.eclipse.papyrus.uml.diagram.common.helper.LinkMappingHelper.CommonTargetUMLSwitch;
-import org.eclipse.uml2.uml.ActivityEdge;
-import org.eclipse.uml2.uml.ControlFlow;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.ObjectFlow;
-
-/**
- * Specialization of the link mapping helper for the Activity diagram
- */
-public class ActivityLinkMappingHelper implements ILinkMappingHelper {
-
- /**
- * SingletonHolder is loaded at the first execution of getInstance() method
- */
- private static class SingletonHolder {
-
- private final static ActivityLinkMappingHelper instance = new ActivityLinkMappingHelper();
- }
-
- /**
- * Gets the single instance of ClassLinkMappingHelper.
- *
- * @return single instance of ClassLinkMappingHelper
- */
- public static ActivityLinkMappingHelper getInstance() {
- return SingletonHolder.instance;
- }
-
- /**
- * private constructor
- */
- private ActivityLinkMappingHelper() {
- // do nothing
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Collection<?> getSource(Element link) {
- return LinkMappingHelper.getSource(link, new CommonSourceUMLSwitch() {
-
- @Override
- public Collection<?> caseActivityEdge(ActivityEdge object) {
- return Collections.singleton(object.getSource());
- }
-
- @Override
- public Collection<?> caseObjectFlow(ObjectFlow object) {
- return caseActivityEdge(object);
- }
-
- @Override
- public Collection<?> caseControlFlow(ControlFlow object) {
- return caseActivityEdge(object);
- }
- });
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Collection<?> getTarget(Element link) {
- return LinkMappingHelper.getTarget(link, new CommonTargetUMLSwitch() {
-
- @Override
- public Collection<?> caseActivityEdge(ActivityEdge object) {
- return Collections.singleton(object.getTarget());
- }
-
- @Override
- public Collection<?> caseObjectFlow(ObjectFlow object) {
- return caseActivityEdge(object);
- }
-
- @Override
- public Collection<?> caseControlFlow(ControlFlow object) {
- return caseActivityEdge(object);
- }
- });
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import java.util.Collection; +import java.util.Collections; + +import org.eclipse.papyrus.uml.diagram.common.helper.ILinkMappingHelper; +import org.eclipse.papyrus.uml.diagram.common.helper.LinkMappingHelper; +import org.eclipse.papyrus.uml.diagram.common.helper.LinkMappingHelper.CommonSourceUMLSwitch; +import org.eclipse.papyrus.uml.diagram.common.helper.LinkMappingHelper.CommonTargetUMLSwitch; +import org.eclipse.uml2.uml.ActivityEdge; +import org.eclipse.uml2.uml.ControlFlow; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.ObjectFlow; + +/** + * Specialization of the link mapping helper for the Activity diagram + */ +public class ActivityLinkMappingHelper implements ILinkMappingHelper { + + /** + * SingletonHolder is loaded at the first execution of getInstance() method + */ + private static class SingletonHolder { + + private final static ActivityLinkMappingHelper instance = new ActivityLinkMappingHelper(); + } + + /** + * Gets the single instance of ClassLinkMappingHelper. + * + * @return single instance of ClassLinkMappingHelper + */ + public static ActivityLinkMappingHelper getInstance() { + return SingletonHolder.instance; + } + + /** + * private constructor + */ + private ActivityLinkMappingHelper() { + // do nothing + } + + /** + * {@inheritDoc} + */ + @Override + public Collection<?> getSource(Element link) { + return LinkMappingHelper.getSource(link, new CommonSourceUMLSwitch() { + + @Override + public Collection<?> caseActivityEdge(ActivityEdge object) { + return Collections.singleton(object.getSource()); + } + + @Override + public Collection<?> caseObjectFlow(ObjectFlow object) { + return caseActivityEdge(object); + } + + @Override + public Collection<?> caseControlFlow(ControlFlow object) { + return caseActivityEdge(object); + } + }); + } + + /** + * {@inheritDoc} + */ + @Override + public Collection<?> getTarget(Element link) { + return LinkMappingHelper.getTarget(link, new CommonTargetUMLSwitch() { + + @Override + public Collection<?> caseActivityEdge(ActivityEdge object) { + return Collections.singleton(object.getTarget()); + } + + @Override + public Collection<?> caseObjectFlow(ObjectFlow object) { + return caseActivityEdge(object); + } + + @Override + public Collection<?> caseControlFlow(ControlFlow object) { + return caseActivityEdge(object); + } + }); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityParameterAndParameterSynchronizer.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityParameterAndParameterSynchronizer.java index c5616f71261..01801251a4c 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityParameterAndParameterSynchronizer.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/ActivityParameterAndParameterSynchronizer.java @@ -1,280 +1,280 @@ -/*****************************************************************************
- * 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:
- * Emilien Perico (Atos Origin) emilien.perico@atosorigin.com - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.emf.common.command.Command;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature.Setting;
-import org.eclipse.emf.edit.command.AddCommand;
-import org.eclipse.emf.edit.command.RemoveCommand;
-import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.emf.validation.AbstractModelConstraint;
-import org.eclipse.emf.validation.EMFEventType;
-import org.eclipse.emf.validation.IValidationContext;
-import org.eclipse.gmf.runtime.common.core.util.Log;
-import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin;
-import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIStatusCodes;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.papyrus.infra.ui.util.EditorUtils;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.ConfirmActivityParameterNodeAndParameterSyncDialog;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndLinkDialog;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.uml2.common.util.CacheAdapter;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.ActivityParameterNode;
-import org.eclipse.uml2.uml.NamedElement;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * ActivityParameterAndParameterSynchronizer is a validator (see corresponding
- * extensions) to synchronize ActivityParameterNode with its Parameter
- *
- */
-public class ActivityParameterAndParameterSynchronizer extends AbstractModelConstraint {
-
- /** The label provider */
- private static final ILabelProvider labelProvider = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory());
-
- /** The activity parameter nodes to remove with parameter */
- private Set<ActivityParameterNode> nodesToRemove = new HashSet<ActivityParameterNode>();
-
- /**
- * {@inheritDoc}
- */
- @SuppressWarnings("restriction")
- @Override
- public IStatus validate(IValidationContext ctx) {
- try {
- EObject eObject = ctx.getTarget();
- if (eObject instanceof Activity) {
- return handleActivityModification((Activity) eObject, ctx);
- } else if (eObject instanceof ActivityParameterNode) {
- return handleActivityParameterNodeModification((ActivityParameterNode) eObject, ctx);
- } else if (eObject instanceof Parameter) {
- return handleParameterModification((Parameter) eObject, ctx);
- }
- return ctx.createSuccessStatus();
- } catch (RuntimeException rte) {
- // avoid throwing uncaught exception which would disable the
- // constraint
- Log.warning(DiagramUIPlugin.getInstance(), DiagramUIStatusCodes.IGNORED_EXCEPTION_WARNING, "Unexpected exception during Activity Parameter Node and Parameter synchronization : ", rte);
- // ensure that the constraint's failure does not prevent
- // modification
- return ctx.createSuccessStatus();
- }
- }
-
- /**
- * Handle activity parameter node modification to forbid activity parameter
- * node type modification
- *
- * @param eObject
- * @param ctx
- * @return the status
- */
- private IStatus handleActivityParameterNodeModification(ActivityParameterNode eObject, IValidationContext ctx) {
- if (EMFEventType.SET.equals(ctx.getEventType()) && UMLPackage.eINSTANCE.getTypedElement_Type().equals(ctx.getFeature())) {
- // does not allow type change for activity parameter node, display a
- // message to inform the user
- final Parameter parameter = eObject.getParameter();
- if (parameter != null) {
- final String elementLabel = labelProvider.getText(parameter);
- final String message = NLS.bind(CustomMessages.ActivityParameterAndParameterSynchronizer_UnauthorizedModificationRedirection, elementLabel);
- SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() {
-
- @Override
- protected Void openDialog() {
- WarningAndLinkDialog dialog = new WarningAndLinkDialog(new Shell(Display.getDefault()), CustomMessages.ActivityParameterAndParameterSynchronizer_UnauthorizedModificationTitle, message, parameter, elementLabel);
- dialog.open();
- return null;
- }
- };
- opener.execute();
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Handle parameter modification to synchronize the type of the associated
- * activity parameter nodes
- *
- * @param eObject
- * @param ctx
- * @return the status
- */
- private IStatus handleParameterModification(Parameter eObject, IValidationContext ctx) {
- if (EMFEventType.SET.equals(ctx.getEventType()) && UMLPackage.eINSTANCE.getTypedElement_Type().equals(ctx.getFeature())) {
- // change the type of all the associated activity parameter node
- for (ActivityParameterNode node : getActivityParameterNodesFromParameter(eObject)) {
- node.setType(node.getParameter().getType());
- }
- } else if (EMFEventType.SET.equals(ctx.getEventType()) && UMLPackage.eINSTANCE.getNamedElement_Name().equals(ctx.getFeature())) {
- // set the name of all the unnamed associated activity parameter
- // nodes
- for (ActivityParameterNode node : getActivityParameterNodesFromParameter(eObject)) {
- if (node.getName() == null || "".equals(node.getName())) {
- node.setName(eObject.getName());
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Handle activity modification - add parameter node: set the type with the
- * associated parameter type - remove parameter: remove all the associated
- * activity parameter nodes
- *
- * @param eObject
- * @param ctx
- * @return the status
- */
- private IStatus handleActivityModification(Activity eObject, IValidationContext ctx) {
- // initialize type when an activity parameter node is created
- if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof ActivityParameterNode) {
- ActivityParameterNode activityParameterNode = (ActivityParameterNode) ctx.getFeatureNewValue();
- // The type of an activity parameter node is the same as the type of
- // its parameter.
- activityParameterNode.setType(activityParameterNode.getParameter().getType());
- }
- // constraint: the nodes of an activity must include one
- // ActivityParameterNode for each parameter
- if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof Parameter) {
- Parameter parameter = (Parameter) ctx.getFeatureNewValue();
- if (getActivityParameterNodesFromParameter(parameter).isEmpty()) {
- ActivityParameterNode apn = UMLFactory.eINSTANCE.createActivityParameterNode();
- apn.setParameter(parameter);
- apn.setName(parameter.getName());
- apn.setType(parameter.getType());
- Command cmd = getAddActivityParameterNodesCmd(eObject, apn);
- if (cmd.canExecute()) {
- cmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- }
- // parameter deletion
- else if (((EMFEventType.REMOVE.equals(ctx.getEventType()) && ctx.getFeatureNewValue() instanceof Parameter) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType()))) {
- nodesToRemove.clear();
- // remove associated activity parameter nodes with the parameter
- for (Notification n : ctx.getAllEvents()) {
- if (Notification.SET == n.getEventType() && UMLPackage.eINSTANCE.getActivityParameterNode_Parameter().equals(n.getFeature()) && n.getNotifier() instanceof ActivityParameterNode) {
- nodesToRemove.add((ActivityParameterNode) n.getNotifier());
- }
- // first request is to remove the activity parameter node, it
- // must not be remove because of parameter deletion
- if (Notification.REMOVE == n.getEventType() && n.getOldValue() instanceof ActivityParameterNode) {
- nodesToRemove.remove(n.getOldValue());
- }
- }
- if (!nodesToRemove.isEmpty()) {
- if (askForValidation(nodesToRemove)) {
- Command cmd = getRemoveActivityParameterNodesCmd(eObject, nodesToRemove);
- if (cmd.canExecute()) {
- cmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- } else {
- return ctx.createFailureStatus();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Gets the associated activity parameter nodes from a specified parameter.
- *
- * @param parameter
- * the parameter
- * @return the activity parameter nodes
- */
- private Set<ActivityParameterNode> getActivityParameterNodesFromParameter(Parameter parameter) {
- Set<ActivityParameterNode> references = new HashSet<ActivityParameterNode>();
- if (parameter != null) {
- Collection<Setting> inverseReferences = CacheAdapter.getInstance().getNonNavigableInverseReferences(parameter);
- for (Setting ref : inverseReferences) {
- if (UMLPackage.eINSTANCE.getActivityParameterNode_Parameter().equals(ref.getEStructuralFeature()) && ref.getEObject().eContainer() != null) {
- references.add((ActivityParameterNode) ref.getEObject());
- }
- }
- }
- return references;
- }
-
- /**
- * Command to remove the activity parameter nodes that's not have associated
- * parameter.
- *
- * @param owner
- * the activity that owns the nodes
- * @param nodes
- * the nodes
- * @return the remove command
- */
- private Command getRemoveActivityParameterNodesCmd(Activity owner, Set<ActivityParameterNode> nodes) {
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- return RemoveCommand.create(editingdomain, owner, UMLPackage.eINSTANCE.getActivity_Node(), nodes);
- }
-
- /**
- * Gets the adds the activity parameter nodes command.
- *
- * @param owner
- * the owner
- * @param node
- * the node
- * @return the adds the activity parameter nodes command
- */
- private Command getAddActivityParameterNodesCmd(Activity owner, ActivityParameterNode node) {
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- return AddCommand.create(editingdomain, owner, UMLPackage.eINSTANCE.getActivity_Node(), node);
- }
-
- /**
- * Ask the user to validate all the implied modifications (parameters and
- * activity parameter nodes)
- *
- * @param parameterNodes
- * the list of impacted activityParameterNodes
- * @return whether the user validates the modifications
- */
- protected boolean askForValidation(final Set<? extends NamedElement> parameterNodes) {
- SafeDialogOpenerDuringValidation<Boolean> opener = new SafeDialogOpenerDuringValidation<Boolean>() {
-
- @Override
- protected Boolean openDialog() {
- return ConfirmActivityParameterNodeAndParameterSyncDialog.openConfirmFromParameter(Display.getDefault().getActiveShell(), parameterNodes, labelProvider);
- }
- };
- return opener.execute();
- }
-}
+/***************************************************************************** + * 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: + * Emilien Perico (Atos Origin) emilien.perico@atosorigin.com - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature.Setting; +import org.eclipse.emf.edit.command.AddCommand; +import org.eclipse.emf.edit.command.RemoveCommand; +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.emf.validation.AbstractModelConstraint; +import org.eclipse.emf.validation.EMFEventType; +import org.eclipse.emf.validation.IValidationContext; +import org.eclipse.gmf.runtime.common.core.util.Log; +import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin; +import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIStatusCodes; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.osgi.util.NLS; +import org.eclipse.papyrus.infra.ui.util.EditorUtils; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.ConfirmActivityParameterNodeAndParameterSyncDialog; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndLinkDialog; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.uml2.common.util.CacheAdapter; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.ActivityParameterNode; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * ActivityParameterAndParameterSynchronizer is a validator (see corresponding + * extensions) to synchronize ActivityParameterNode with its Parameter + * + */ +public class ActivityParameterAndParameterSynchronizer extends AbstractModelConstraint { + + /** The label provider */ + private static final ILabelProvider labelProvider = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()); + + /** The activity parameter nodes to remove with parameter */ + private Set<ActivityParameterNode> nodesToRemove = new HashSet<ActivityParameterNode>(); + + /** + * {@inheritDoc} + */ + @SuppressWarnings("restriction") + @Override + public IStatus validate(IValidationContext ctx) { + try { + EObject eObject = ctx.getTarget(); + if (eObject instanceof Activity) { + return handleActivityModification((Activity) eObject, ctx); + } else if (eObject instanceof ActivityParameterNode) { + return handleActivityParameterNodeModification((ActivityParameterNode) eObject, ctx); + } else if (eObject instanceof Parameter) { + return handleParameterModification((Parameter) eObject, ctx); + } + return ctx.createSuccessStatus(); + } catch (RuntimeException rte) { + // avoid throwing uncaught exception which would disable the + // constraint + Log.warning(DiagramUIPlugin.getInstance(), DiagramUIStatusCodes.IGNORED_EXCEPTION_WARNING, "Unexpected exception during Activity Parameter Node and Parameter synchronization : ", rte); + // ensure that the constraint's failure does not prevent + // modification + return ctx.createSuccessStatus(); + } + } + + /** + * Handle activity parameter node modification to forbid activity parameter + * node type modification + * + * @param eObject + * @param ctx + * @return the status + */ + private IStatus handleActivityParameterNodeModification(ActivityParameterNode eObject, IValidationContext ctx) { + if (EMFEventType.SET.equals(ctx.getEventType()) && UMLPackage.eINSTANCE.getTypedElement_Type().equals(ctx.getFeature())) { + // does not allow type change for activity parameter node, display a + // message to inform the user + final Parameter parameter = eObject.getParameter(); + if (parameter != null) { + final String elementLabel = labelProvider.getText(parameter); + final String message = NLS.bind(CustomMessages.ActivityParameterAndParameterSynchronizer_UnauthorizedModificationRedirection, elementLabel); + SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() { + + @Override + protected Void openDialog() { + WarningAndLinkDialog dialog = new WarningAndLinkDialog(new Shell(Display.getDefault()), CustomMessages.ActivityParameterAndParameterSynchronizer_UnauthorizedModificationTitle, message, parameter, elementLabel); + dialog.open(); + return null; + } + }; + opener.execute(); + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Handle parameter modification to synchronize the type of the associated + * activity parameter nodes + * + * @param eObject + * @param ctx + * @return the status + */ + private IStatus handleParameterModification(Parameter eObject, IValidationContext ctx) { + if (EMFEventType.SET.equals(ctx.getEventType()) && UMLPackage.eINSTANCE.getTypedElement_Type().equals(ctx.getFeature())) { + // change the type of all the associated activity parameter node + for (ActivityParameterNode node : getActivityParameterNodesFromParameter(eObject)) { + node.setType(node.getParameter().getType()); + } + } else if (EMFEventType.SET.equals(ctx.getEventType()) && UMLPackage.eINSTANCE.getNamedElement_Name().equals(ctx.getFeature())) { + // set the name of all the unnamed associated activity parameter + // nodes + for (ActivityParameterNode node : getActivityParameterNodesFromParameter(eObject)) { + if (node.getName() == null || "".equals(node.getName())) { + node.setName(eObject.getName()); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Handle activity modification - add parameter node: set the type with the + * associated parameter type - remove parameter: remove all the associated + * activity parameter nodes + * + * @param eObject + * @param ctx + * @return the status + */ + private IStatus handleActivityModification(Activity eObject, IValidationContext ctx) { + // initialize type when an activity parameter node is created + if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof ActivityParameterNode) { + ActivityParameterNode activityParameterNode = (ActivityParameterNode) ctx.getFeatureNewValue(); + // The type of an activity parameter node is the same as the type of + // its parameter. + activityParameterNode.setType(activityParameterNode.getParameter().getType()); + } + // constraint: the nodes of an activity must include one + // ActivityParameterNode for each parameter + if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof Parameter) { + Parameter parameter = (Parameter) ctx.getFeatureNewValue(); + if (getActivityParameterNodesFromParameter(parameter).isEmpty()) { + ActivityParameterNode apn = UMLFactory.eINSTANCE.createActivityParameterNode(); + apn.setParameter(parameter); + apn.setName(parameter.getName()); + apn.setType(parameter.getType()); + Command cmd = getAddActivityParameterNodesCmd(eObject, apn); + if (cmd.canExecute()) { + cmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + } + // parameter deletion + else if (((EMFEventType.REMOVE.equals(ctx.getEventType()) && ctx.getFeatureNewValue() instanceof Parameter) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType()))) { + nodesToRemove.clear(); + // remove associated activity parameter nodes with the parameter + for (Notification n : ctx.getAllEvents()) { + if (Notification.SET == n.getEventType() && UMLPackage.eINSTANCE.getActivityParameterNode_Parameter().equals(n.getFeature()) && n.getNotifier() instanceof ActivityParameterNode) { + nodesToRemove.add((ActivityParameterNode) n.getNotifier()); + } + // first request is to remove the activity parameter node, it + // must not be remove because of parameter deletion + if (Notification.REMOVE == n.getEventType() && n.getOldValue() instanceof ActivityParameterNode) { + nodesToRemove.remove(n.getOldValue()); + } + } + if (!nodesToRemove.isEmpty()) { + if (askForValidation(nodesToRemove)) { + Command cmd = getRemoveActivityParameterNodesCmd(eObject, nodesToRemove); + if (cmd.canExecute()) { + cmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } else { + return ctx.createFailureStatus(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Gets the associated activity parameter nodes from a specified parameter. + * + * @param parameter + * the parameter + * @return the activity parameter nodes + */ + private Set<ActivityParameterNode> getActivityParameterNodesFromParameter(Parameter parameter) { + Set<ActivityParameterNode> references = new HashSet<ActivityParameterNode>(); + if (parameter != null) { + Collection<Setting> inverseReferences = CacheAdapter.getInstance().getNonNavigableInverseReferences(parameter); + for (Setting ref : inverseReferences) { + if (UMLPackage.eINSTANCE.getActivityParameterNode_Parameter().equals(ref.getEStructuralFeature()) && ref.getEObject().eContainer() != null) { + references.add((ActivityParameterNode) ref.getEObject()); + } + } + } + return references; + } + + /** + * Command to remove the activity parameter nodes that's not have associated + * parameter. + * + * @param owner + * the activity that owns the nodes + * @param nodes + * the nodes + * @return the remove command + */ + private Command getRemoveActivityParameterNodesCmd(Activity owner, Set<ActivityParameterNode> nodes) { + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + return RemoveCommand.create(editingdomain, owner, UMLPackage.eINSTANCE.getActivity_Node(), nodes); + } + + /** + * Gets the adds the activity parameter nodes command. + * + * @param owner + * the owner + * @param node + * the node + * @return the adds the activity parameter nodes command + */ + private Command getAddActivityParameterNodesCmd(Activity owner, ActivityParameterNode node) { + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + return AddCommand.create(editingdomain, owner, UMLPackage.eINSTANCE.getActivity_Node(), node); + } + + /** + * Ask the user to validate all the implied modifications (parameters and + * activity parameter nodes) + * + * @param parameterNodes + * the list of impacted activityParameterNodes + * @return whether the user validates the modifications + */ + protected boolean askForValidation(final Set<? extends NamedElement> parameterNodes) { + SafeDialogOpenerDuringValidation<Boolean> opener = new SafeDialogOpenerDuringValidation<Boolean>() { + + @Override + protected Boolean openDialog() { + return ConfirmActivityParameterNodeAndParameterSyncDialog.openConfirmFromParameter(Display.getDefault().getActiveShell(), parameterNodes, labelProvider); + } + }; + return opener.execute(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/CustomAcceptEventActionEditHelper.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/CustomAcceptEventActionEditHelper.java index 4ab8da174e0..870955a3770 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/CustomAcceptEventActionEditHelper.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/CustomAcceptEventActionEditHelper.java @@ -1,51 +1,51 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) patrick.tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import org.eclipse.uml2.uml.AcceptEventAction;
-import org.eclipse.uml2.uml.Event;
-import org.eclipse.uml2.uml.TimeEvent;
-import org.eclipse.uml2.uml.Trigger;
-
-/**
- * this class contains a util method use for AccepEventAction
- */
-public class CustomAcceptEventActionEditHelper {
-
- /**
- * Test whether the action may be considered as a time event action
- *
- * @param action
- * the action to test
- * @return true if action is a time event action
- */
- public static boolean isAcceptTimeEventAction(AcceptEventAction action) {
- if (action.getTriggers() != null) {
- boolean hasTimeEvent = false;
- for (Trigger trigger : action.getTriggers()) {
- if (trigger != null) {
- Event event = trigger.getEvent();
- if (event instanceof TimeEvent) {
- hasTimeEvent = true;
- } else {
- return false;
- }
- }
- }
- // only time events have been encountered, but maybe no event at all.
- return hasTimeEvent;
- }
- return false;
- }
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) patrick.tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import org.eclipse.uml2.uml.AcceptEventAction; +import org.eclipse.uml2.uml.Event; +import org.eclipse.uml2.uml.TimeEvent; +import org.eclipse.uml2.uml.Trigger; + +/** + * this class contains a util method use for AccepEventAction + */ +public class CustomAcceptEventActionEditHelper { + + /** + * Test whether the action may be considered as a time event action + * + * @param action + * the action to test + * @return true if action is a time event action + */ + public static boolean isAcceptTimeEventAction(AcceptEventAction action) { + if (action.getTriggers() != null) { + boolean hasTimeEvent = false; + for (Trigger trigger : action.getTriggers()) { + if (trigger != null) { + Event event = trigger.getEvent(); + if (event instanceof TimeEvent) { + hasTimeEvent = true; + } else { + return false; + } + } + } + // only time events have been encountered, but maybe no event at all. + return hasTimeEvent; + } + return false; + } }
\ No newline at end of file diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/CustomObjectFlowEditHelper.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/CustomObjectFlowEditHelper.java index a7733b602ee..54b42be03bf 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/CustomObjectFlowEditHelper.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/CustomObjectFlowEditHelper.java @@ -1,114 +1,114 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST.
- *
- *
- * 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:
- * Patrick Tessier (CEA LIST) patrick.tessier@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import org.eclipse.uml2.uml.AcceptEventAction;
-import org.eclipse.uml2.uml.Action;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.InputPin;
-import org.eclipse.uml2.uml.OpaqueAction;
-import org.eclipse.uml2.uml.OutputPin;
-
-/**
- * this edit helper contains util method in order to manage ObjectFlow
- */
-public class CustomObjectFlowEditHelper {
-
- /**
- * Return whether we can create a new object flow starting from this action by adding an intermediate output pin at it.
- *
- * @param action
- * the action to start from
- * @return whether action accept new output pin
- */
- public static boolean canStartNewObjectFlow(Action action) {
- // CallOperationAction and CallBehaviorAction have pre-defined pins which are all represented.
- // SendObjectAction have only two input pins which are all represented.
- // SendSignalAction has only pre-defined input pins which are all represented.
- return (action instanceof OpaqueAction) || (action instanceof AcceptEventAction);
- }
-
- /**
- * Return whether we can create a new object flow ending to this action by adding an intermediate input pin at it.
- *
- * @param action
- * the action to end to
- * @return whether action accept new input pin
- */
- public static boolean canEndNewObjectFlow(Action action) {
- // CallOperationAction and CallBehaviorAction have pre-defined pins which are all represented.
- // SendObjectAction have only two input pins which are all represented.
- // SendSignalAction has only pre-defined input pins which are all represented.
- // AcceptEventAction has no input pin
- return action instanceof OpaqueAction;
- }
-
- /**
- * Return whether a pin must be inserted to create a new object flow starting from this activity node.
- *
- * @param node
- * the activity node to start from
- * @return whether a pin must can inserted to create an object flow from this node
- */
- public static boolean insertPinForStartingNewObjectFlow(ActivityNode node) {
- if (node instanceof Action) {
- return canStartNewObjectFlow((Action) node);
- }
- return false;
- }
-
- /**
- * Return whether a pin must be inserted to create a new object flow ending to this activity node.
- *
- * @param node
- * the activity node to end to
- * @return whether a pin must can inserted to create an object flow to this node
- */
- public static boolean insertPinForEndingNewObjectFlow(ActivityNode node) {
- if (node instanceof Action) {
- return canEndNewObjectFlow((Action) node);
- }
- return false;
- }
-
- /**
- * Insert the created output pin in the parent action
- *
- * @param parentAction
- * action to insert pin in
- * @param outputPin
- * output pin to insert
- */
- public static void insertOutputPin(Action parentAction, OutputPin outputPin) {
- if (parentAction instanceof OpaqueAction) {
- ((OpaqueAction) parentAction).getOutputValues().add(outputPin);
- } else if (parentAction instanceof AcceptEventAction) {
- ((AcceptEventAction) parentAction).getResults().add(outputPin);
- }
- }
-
- /**
- * Insert the created input pin in the parent action
- *
- * @param parentAction
- * action to insert pin in
- * @param inputPin
- * input pin to insert
- */
- public static void insertInputPin(Action parentAction, InputPin inputPin) {
- if (parentAction instanceof OpaqueAction) {
- ((OpaqueAction) parentAction).getInputValues().add(inputPin);
- }
- }
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST. + * + * + * 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: + * Patrick Tessier (CEA LIST) patrick.tessier@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import org.eclipse.uml2.uml.AcceptEventAction; +import org.eclipse.uml2.uml.Action; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.InputPin; +import org.eclipse.uml2.uml.OpaqueAction; +import org.eclipse.uml2.uml.OutputPin; + +/** + * this edit helper contains util method in order to manage ObjectFlow + */ +public class CustomObjectFlowEditHelper { + + /** + * Return whether we can create a new object flow starting from this action by adding an intermediate output pin at it. + * + * @param action + * the action to start from + * @return whether action accept new output pin + */ + public static boolean canStartNewObjectFlow(Action action) { + // CallOperationAction and CallBehaviorAction have pre-defined pins which are all represented. + // SendObjectAction have only two input pins which are all represented. + // SendSignalAction has only pre-defined input pins which are all represented. + return (action instanceof OpaqueAction) || (action instanceof AcceptEventAction); + } + + /** + * Return whether we can create a new object flow ending to this action by adding an intermediate input pin at it. + * + * @param action + * the action to end to + * @return whether action accept new input pin + */ + public static boolean canEndNewObjectFlow(Action action) { + // CallOperationAction and CallBehaviorAction have pre-defined pins which are all represented. + // SendObjectAction have only two input pins which are all represented. + // SendSignalAction has only pre-defined input pins which are all represented. + // AcceptEventAction has no input pin + return action instanceof OpaqueAction; + } + + /** + * Return whether a pin must be inserted to create a new object flow starting from this activity node. + * + * @param node + * the activity node to start from + * @return whether a pin must can inserted to create an object flow from this node + */ + public static boolean insertPinForStartingNewObjectFlow(ActivityNode node) { + if (node instanceof Action) { + return canStartNewObjectFlow((Action) node); + } + return false; + } + + /** + * Return whether a pin must be inserted to create a new object flow ending to this activity node. + * + * @param node + * the activity node to end to + * @return whether a pin must can inserted to create an object flow to this node + */ + public static boolean insertPinForEndingNewObjectFlow(ActivityNode node) { + if (node instanceof Action) { + return canEndNewObjectFlow((Action) node); + } + return false; + } + + /** + * Insert the created output pin in the parent action + * + * @param parentAction + * action to insert pin in + * @param outputPin + * output pin to insert + */ + public static void insertOutputPin(Action parentAction, OutputPin outputPin) { + if (parentAction instanceof OpaqueAction) { + ((OpaqueAction) parentAction).getOutputValues().add(outputPin); + } else if (parentAction instanceof AcceptEventAction) { + ((AcceptEventAction) parentAction).getResults().add(outputPin); + } + } + + /** + * Insert the created input pin in the parent action + * + * @param parentAction + * action to insert pin in + * @param inputPin + * input pin to insert + */ + public static void insertInputPin(Action parentAction, InputPin inputPin) { + if (parentAction instanceof OpaqueAction) { + ((OpaqueAction) parentAction).getInputValues().add(inputPin); + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/IPinToParameterLinkCommand.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/IPinToParameterLinkCommand.java index 465af4280c6..8c3da3e9713 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/IPinToParameterLinkCommand.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/IPinToParameterLinkCommand.java @@ -1,37 +1,37 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import org.eclipse.emf.ecore.EAnnotation;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.Pin;
-
-/**
- * Constant used to create link between {@link Pin} and {@link Parameter}
- *
- * @author arthur daussy
- *
- */
-public interface IPinToParameterLinkCommand {
-
- /**
- * Name of the {@link EAnnotation} use to store the link between a {@link Pin} and a {@link Parameter}
- */
- public static final String PIN_TO_PARAMETER_LINK = "PinToParameterLink";
-
- /**
- * ID use to inform the user that no link exist between a {@link Pin} and a {@link Parameter}
- */
- public static final String NO_PARAMETER_ID = "NO_PARAMETER_ID";
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import org.eclipse.emf.ecore.EAnnotation; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.Pin; + +/** + * Constant used to create link between {@link Pin} and {@link Parameter} + * + * @author arthur daussy + * + */ +public interface IPinToParameterLinkCommand { + + /** + * Name of the {@link EAnnotation} use to store the link between a {@link Pin} and a {@link Parameter} + */ + public static final String PIN_TO_PARAMETER_LINK = "PinToParameterLink"; + + /** + * ID use to inform the user that no link exist between a {@link Pin} and a {@link Parameter} + */ + public static final String NO_PARAMETER_ID = "NO_PARAMETER_ID"; +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/PinAndParameterSynchronizeValidator.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/PinAndParameterSynchronizeValidator.java index b3dc423f6ed..a6a8ba63316 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/PinAndParameterSynchronizeValidator.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/PinAndParameterSynchronizeValidator.java @@ -1,27 +1,27 @@ -/*****************************************************************************
- * Copyright (c) 2011 AtoS.
- *
- * 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:
- * Tristan FAURE (AtoS) tristan.faure@atos.net - Initial API and implementation
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation to specify on methods which ones are used for validation
- *
- * @author tristan.faure@atos.net
- */
-@Target(ElementType.METHOD)
-@Retention(RetentionPolicy.RUNTIME)
-public @interface PinAndParameterSynchronizeValidator {
-}
+/***************************************************************************** + * Copyright (c) 2011 AtoS. + * + * 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: + * Tristan FAURE (AtoS) tristan.faure@atos.net - Initial API and implementation + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation to specify on methods which ones are used for validation + * + * @author tristan.faure@atos.net + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface PinAndParameterSynchronizeValidator { +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/PinAndParameterSynchronizer.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/PinAndParameterSynchronizer.java index f1e05b7fd9d..c1beb33a2d9 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/PinAndParameterSynchronizer.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/PinAndParameterSynchronizer.java @@ -1,2968 +1,2968 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- * Olivier Melois (Atos) : olivier.melois@atos.net - 371712
- * Arthur Daussy (Atos) : arthur.daussy@atos.net - 371712
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.emf.common.command.Command;
-import org.eclipse.emf.common.command.CompoundCommand;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EAnnotation;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.emf.ecore.EStructuralFeature.Setting;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-import org.eclipse.emf.ecore.xmi.XMIResource;
-import org.eclipse.emf.edit.command.AddCommand;
-import org.eclipse.emf.edit.command.CopyCommand;
-import org.eclipse.emf.edit.command.RemoveCommand;
-import org.eclipse.emf.edit.command.SetCommand;
-import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.emf.validation.AbstractModelConstraint;
-import org.eclipse.emf.validation.EMFEventType;
-import org.eclipse.emf.validation.IValidationContext;
-import org.eclipse.emf.workspace.WorkspaceEditingDomainFactory;
-import org.eclipse.gmf.runtime.common.core.util.Log;
-import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin;
-import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIStatusCodes;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.window.Window;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.papyrus.infra.core.services.ServiceException;
-import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForEObject;
-import org.eclipse.papyrus.infra.ui.util.EditorUtils;
-import org.eclipse.papyrus.uml.diagram.activity.commands.CreatePinToParameterLinkEAnnotation;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.ConfirmPinAndParameterSyncDialog;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndCreateAttributeDialog;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndCreateParameterDialog;
-import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndLinkDialog;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.BroadcastSignalActionEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.handlers.SynchronizePinsParametersHandler;
-import org.eclipse.papyrus.uml.diagram.activity.helper.datastructure.LinkPinToParameter;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.uml2.common.util.CacheAdapter;
-import org.eclipse.uml2.uml.Action;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.AddStructuralFeatureValueAction;
-import org.eclipse.uml2.uml.AddVariableValueAction;
-import org.eclipse.uml2.uml.Behavior;
-import org.eclipse.uml2.uml.BroadcastSignalAction;
-import org.eclipse.uml2.uml.CallAction;
-import org.eclipse.uml2.uml.CallBehaviorAction;
-import org.eclipse.uml2.uml.CallOperationAction;
-import org.eclipse.uml2.uml.Classifier;
-import org.eclipse.uml2.uml.CreateObjectAction;
-import org.eclipse.uml2.uml.DestroyObjectAction;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.InputPin;
-import org.eclipse.uml2.uml.InvocationAction;
-import org.eclipse.uml2.uml.LiteralInteger;
-import org.eclipse.uml2.uml.NamedElement;
-import org.eclipse.uml2.uml.ObjectNode;
-import org.eclipse.uml2.uml.Operation;
-import org.eclipse.uml2.uml.OutputPin;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.ParameterDirectionKind;
-import org.eclipse.uml2.uml.Pin;
-import org.eclipse.uml2.uml.Property;
-import org.eclipse.uml2.uml.ReadStructuralFeatureAction;
-import org.eclipse.uml2.uml.ReadVariableAction;
-import org.eclipse.uml2.uml.SendObjectAction;
-import org.eclipse.uml2.uml.SendSignalAction;
-import org.eclipse.uml2.uml.Signal;
-import org.eclipse.uml2.uml.StructuralFeature;
-import org.eclipse.uml2.uml.StructuralFeatureAction;
-import org.eclipse.uml2.uml.Type;
-import org.eclipse.uml2.uml.TypedElement;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-import org.eclipse.uml2.uml.ValueSpecification;
-import org.eclipse.uml2.uml.Variable;
-
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
-/**
- * The PinAndParameterSynchronizer is a validator (see corresponding extensions)
- * which ensure Pins and their corresponding (if a correspondance can be
- * established) Parameters are correctly synchronized
- *
- */
-public class PinAndParameterSynchronizer extends AbstractModelConstraint {
-
- private static final String RESULT_IN_READ_VARIABLE_ACTION = "result";
-
- private static final String VALUE_IN_ADD_VARIABLE_VALUE_ACTION = "value";
-
- private static final String INSERT_AT_IN_ADD_VARIABLE_VALUE_ACTION = "insertAt";
-
- private static final String TARGET_IN_DESTROY_OBJECT_ACTION = "target";
-
- private static final String VALUE_PIN_IN_STRUCTURAL_FEATURE_VALUE_ACTION = VALUE_IN_ADD_VARIABLE_VALUE_ACTION;
-
- private static final String RESULT_PIN_READ_SRTUCTURAL_ACTION = "result";
-
- private static final String OBJECT_PIN_IN_READS_STRUCTURAL_ACTION = "object";
-
- /** The label provider */
- private static final ILabelProvider labelProvider = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory());
-
- /** The constant to initialize target pin name */
- private static final String TARGET_PIN_INITIALIZATION_NAME = "target";
-
- /** The constant to initialize request pin name */
- private static final String REQUEST_PIN_INITIALIZATION_NAME = "request";
-
- /** The constant to initialize result pin name */
- private static final String RESULT_PIN_INITIALIZATION_NAME = "result";
-
- /**
- * Validate modification and update associated elements if necessary
- *
- * @see org.eclipse.emf.validation.AbstractModelConstraint#validate(org.eclipse.emf.validation.IValidationContext)
- *
- * @param ctx
- * validation context
- * @return status
- */
- @Override
- public IStatus validate(IValidationContext ctx) {
- try {
- EObject eObject = ctx.getTarget();
- // handle action creation separately not to confuse with case when
- // Behavior is modified
- /*********
- * Done
- *********/
- if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof CallBehaviorAction) {
- // CallBehaviorAction created
- CompoundCommand cmd = getResetPinsCmd((CallAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof CallOperationAction) {
- // CallOperationAction created
- CompoundCommand cmd = getResetPinsCmd((CallAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof SendSignalAction) {
- // SendSignalAction created
- CompoundCommand cmd = getResetPinsCmd((SendSignalAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof SendObjectAction) {
- // SendObjectAction created
- CompoundCommand cmd = getResetPinsCmd((SendObjectAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof DestroyObjectAction) {
- // SendObjectAction created
- CompoundCommand cmd = getResetPinsCmd((DestroyObjectAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && (ctx.getFeatureNewValue() instanceof AddStructuralFeatureValueAction)) {
- // CreateObject Action created
- CompoundCommand cmd = getResetPinsCmd((AddStructuralFeatureValueAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof ReadStructuralFeatureAction) {
- // SendObjectAction created
- CompoundCommand cmd = getResetPinsCmd((ReadStructuralFeatureAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof AddVariableValueAction) {
- // SendObjectAction created
- CompoundCommand cmd = getResetPinsCmd((AddVariableValueAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof ReadVariableAction) {
- // SendObjectAction created
- CompoundCommand cmd = getResetPinsCmd((ReadVariableAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof BroadcastSignalAction) {
- // SendObjectAction created
- CompoundCommand cmd = getResetPinsCmd((InvocationAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- /*********
- * Done
- *********/
- } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof CreateObjectAction) {
- // CreateObject Action created
- CompoundCommand cmd = getResetPinsCmd((CreateObjectAction) ctx.getFeatureNewValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- }
- /*********
- * Done
- *********/
- // handle Operation move for redefining target pin type
- if ((EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) && UMLPackage.eINSTANCE.getOperation_Class().equals(ctx.getFeature()) && eObject instanceof Operation) {
- // Operation moved
- CompoundCommand cmd = getUpdateTargetPinsType((Operation) eObject);
- if (!cmd.isEmpty() && cmd.canExecute()) {
- if (askForValidation(getCallingActions((Operation) eObject))) {
- cmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- }
- /*********
- * Done
- *********/
- if (eObject instanceof ValueSpecification) {
- // the value specification may be in an upperValue or lowerValue
- // replace values with appropriate ones
- EObject topValueSpec = eObject;
- while (topValueSpec.eContainer() instanceof ValueSpecification) {
- topValueSpec = topValueSpec.eContainer();
- }
- eObject = topValueSpec.eContainer();
- }
- /*********
- * Done
- *********/
- if (eObject instanceof Pin) {
- // special case for CallOperationAction target pin : no
- // synchronization, but type
- Element owner = ((Pin) eObject).getOwner();
- Pin target = null;
- if (owner instanceof CallOperationAction) {
- target = ((CallOperationAction) owner).getTarget();
- }
- if (target != null && target.equals(eObject)) {
- return handleTargetPinModification((Pin) eObject, ctx);
- } else {
- // Pin is modified, report modification on
- // Parameter/Property
- return handlePinModification((Pin) eObject, ctx);
- }
- /*********
- * Done
- *********/
- } else if (eObject instanceof Parameter) {
- // Parameter is modified, report modification on Pins
- return handleParameterModification((Parameter) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof Property) {
- // Property is modified, report modification on Pins
- return handlePropertyModification((Property) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof CallOperationAction) {
- // action is modified, ensure deleted/added Pin impact a
- // Parameter
- return handleCallOperationActionModification((CallOperationAction) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof Operation) {
- // Operation is modified, ensure deleted/added Parameter impact
- // Pins
- return handleOperationModification((Operation) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof CallBehaviorAction) {
- // action is modified, ensure deleted/added Pin impact a
- // Parameter
- return handleCallBehaviorActionModification((CallBehaviorAction) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof Behavior) {
- // Behavior is modified, ensure deleted/added Parameter impact
- // Pins
- return handleBehaviorModification((Behavior) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof SendSignalAction) {
- // action is modified, ensure deleted/added Pin impact a
- // Property
- return handleSendSignalActionModification((SendSignalAction) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof Signal) {
- // Signal is modified, ensure deleted/added Property impact Pins
- return handleSignalModification((Signal) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof SendObjectAction) {
- // action is modified, ensure deleted/added Pin are authorized
- return handleSendObjectActionModification((SendObjectAction) eObject, ctx);
- /*********
- * Done
- *********/
- } else if (eObject instanceof BroadcastSignalAction) {
- // action is modified, ensure deleted/added Pin impact a
- // Property
- return handleBroadcastSignalActionModification((BroadcastSignalAction) eObject, ctx);
- }
- return ctx.createSuccessStatus();
- } catch (RuntimeException rte) {
- // avoid throwing uncaught exception which would disable the
- // constraint
- Log.warning(DiagramUIPlugin.getInstance(), DiagramUIStatusCodes.IGNORED_EXCEPTION_WARNING, "Unexpected exception during Pin and Parameter synchronization : ", rte);
- // ensure that the constraint's failure does not prevent
- // modification
- return ctx.createSuccessStatus();
- }
- }
-
- /**
- * Test if the Pin feature impacts the parameter or if the Parameter feature
- * impacts pins
- *
- * @param modifiedFeature
- * the feature to test
- * @return true if the feature impacts the associated Parameter or Pin
- * objects
- */
- protected boolean testPinOrParameterOrPropertyFeature(EStructuralFeature modifiedFeature) {
- boolean type = UMLPackage.eINSTANCE.getTypedElement_Type().equals(modifiedFeature);
- boolean ordering = UMLPackage.eINSTANCE.getMultiplicityElement_IsOrdered().equals(modifiedFeature);
- boolean multiplicity = UMLPackage.eINSTANCE.getMultiplicityElement_IsUnique().equals(modifiedFeature) || UMLPackage.eINSTANCE.getMultiplicityElement_Lower().equals(modifiedFeature)
- || UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue().equals(modifiedFeature) || UMLPackage.eINSTANCE.getMultiplicityElement_Upper().equals(modifiedFeature)
- || UMLPackage.eINSTANCE.getMultiplicityElement_UpperValue().equals(modifiedFeature);
- boolean inAValueSpecification = modifiedFeature != null && ValueSpecification.class.isAssignableFrom(modifiedFeature.getContainerClass());
- return type || ordering || multiplicity || inAValueSpecification;
- }
-
- /**
- * Test if the Action feature impacts the number of Pins and Parameters
- *
- * @param modifiedFeature
- * the feature to test
- * @return true if the feature impacts the number of Parameters or Pins
- */
- protected boolean testActionFeature(EStructuralFeature modifiedFeature) {
- boolean input = UMLPackage.eINSTANCE.getInvocationAction_Argument().equals(modifiedFeature) || UMLPackage.eINSTANCE.getCallOperationAction_Target().equals(modifiedFeature);
- boolean output = UMLPackage.eINSTANCE.getCallAction_Result().equals(modifiedFeature);
- return input || output;
- }
-
- /**
- * Ensure target Pin modification is correct
- *
- * @param pin
- * modified pin
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleTargetPinModification(Pin pin, IValidationContext ctx) {
- // the type of the target pin can not be modified.
- if (UMLPackage.eINSTANCE.getTypedElement_Type().equals(ctx.getFeature())) {
- Element owner = pin.getOwner();
- if (owner instanceof CallOperationAction && ((CallOperationAction) owner).getOperation() != null) {
- proposeNavigation(((CallOperationAction) owner).getOperation());
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Propose the user to create a parameter in the given element
- *
- * @param element
- * element to navigate to or to create a parameter in
- * @param preferredPinClass
- * the direction to select as default (or null)
- */
- protected boolean proposeParameterCreation(final NamedElement element, final EClass preferredPinClass) {
- final String elementLabel = labelProvider.getText(element);
- final String message = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UnauthorizedModification, elementLabel);
- final ParameterDirectionKind preferredDirection;
- if (UMLPackage.eINSTANCE.getOutputPin().isSuperTypeOf(preferredPinClass)) {
- preferredDirection = ParameterDirectionKind.OUT_LITERAL;
- } else {
- preferredDirection = ParameterDirectionKind.IN_LITERAL;
- }
- SafeDialogOpenerDuringValidation<Boolean> opener = new SafeDialogOpenerDuringValidation<Boolean>() {
-
- @Override
- protected Boolean openDialog() {
- WarningAndCreateParameterDialog dialog = new WarningAndCreateParameterDialog(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UnauthorizedModificationTitle, message, element, labelProvider, preferredDirection);
- boolean result = dialog.open() == Window.OK;
- if (result) {
- Parameter parameter = dialog.getParameter();
- handleParameterCreatedDuringValidation(parameter, preferredPinClass);
- }
- return result;
- }
- };
- return opener.execute();
- }
-
- /**
- * Correct the model to add required pins, taking in account the parameter
- * which has just been created with no validation feedback.
- *
- * @param parameter
- * the created parameter
- * @param preferredPinClass
- * the EClass the user would like to create a pin of
- */
- protected void handleParameterCreatedDuringValidation(Parameter parameter, EClass preferredPinClass) {
- if (parameter != null) {
- Map<Integer, TypedElement> empty = Collections.emptyMap();
- CompoundCommand globalCmd = new CompoundCommand();
- // explore referencing actions
- List<InvocationAction> callingActions = getCallingActions(parameter.getOwner());
- switch (parameter.getDirection()) {
- case IN_LITERAL:
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- int index = action.getArguments().size();
- CompoundCommand cmd = getAddPinsCmd(action, Collections.singletonMap(index, (TypedElement) parameter), empty, preferredPinClass);
- globalCmd.append(cmd);
- }
- }
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- int index = ((CallAction) action).getResults().size();
- CompoundCommand cmd = getAddPinsCmd(action, empty, Collections.singletonMap(index, (TypedElement) parameter), preferredPinClass);
- globalCmd.append(cmd);
- }
- }
- break;
- case INOUT_LITERAL:
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- int indexIn = action.getArguments().size();
- int indexOut = ((CallAction) action).getResults().size();
- CompoundCommand cmd = getAddPinsCmd(action, Collections.singletonMap(indexIn, (TypedElement) parameter), Collections.singletonMap(indexOut, (TypedElement) parameter), preferredPinClass);
- globalCmd.append(cmd);
- }
- }
- break;
- }
- if (!globalCmd.isEmpty() && globalCmd.canExecute()) {
- globalCmd.execute();
- }
- }
- }
-
- /**
- * Propose the user to create an attribute in the given element
- *
- * @param element
- * element to navigate to or to create an attribute in
- * @param preferredPinClass
- * the direction to select as default (or null)
- */
- protected boolean proposeAttributeCreation(final NamedElement element, final EClass preferredPinClass) {
- final String elementLabel = labelProvider.getText(element);
- final String message = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UnauthorizedModification, elementLabel);
- SafeDialogOpenerDuringValidation<Boolean> opener = new SafeDialogOpenerDuringValidation<Boolean>() {
-
- @Override
- protected Boolean openDialog() {
- WarningAndCreateAttributeDialog dialog = new WarningAndCreateAttributeDialog(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UnauthorizedModificationTitle, message, element, labelProvider);
- boolean result = dialog.open() == Window.OK;
- if (result) {
- Property attribute = dialog.getAttribute();
- handlePropertyCreatedDuringValidation(attribute, preferredPinClass);
- }
- return result;
- }
- };
- return opener.execute();
- }
-
- /**
- * Correct the model to add required pins, taking in account the property
- * which has just been created with no validation feedback.
- *
- * @param property
- * the created property
- * @param preferredPinClass
- * the EClass the user would like to create a pin of
- */
- protected void handlePropertyCreatedDuringValidation(Property property, EClass preferredPinClass) {
- if (property != null) {
- Map<Integer, Parameter> empty = Collections.emptyMap();
- CompoundCommand globalCmd = new CompoundCommand();
- // explore referencing actions
- List<InvocationAction> callingActions = getCallingActions(property.getOwner());
- for (InvocationAction action : callingActions) {
- if (action instanceof SendSignalAction || action instanceof BroadcastSignalActionEditPart) {
- int index = action.getArguments().size();
- CompoundCommand cmd = getAddPinsCmd(action, Collections.singletonMap(index, property), preferredPinClass);
- globalCmd.append(cmd);
- }
- }
- if (!globalCmd.isEmpty() && globalCmd.canExecute()) {
- globalCmd.execute();
- }
- }
- }
-
- /**
- * Propose the user to navigate to the given element
- *
- * @param element
- * element to navigate to
- */
- protected void proposeNavigation(final NamedElement element) {
- final String elementLabel = labelProvider.getText(element);
- final String message = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UnauthorizedModificationRedirection, elementLabel);
- SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() {
-
- @Override
- protected Void openDialog() {
- WarningAndLinkDialog dialog = new WarningAndLinkDialog(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UnauthorizedModificationTitle, message, element, elementLabel);
- dialog.open();
- return null;
- }
- };
- opener.execute();
- }
-
- /**
- * Ensure Pin modification is in accordance with associated Parameter
- *
- * @param pin
- * modified pin (not a target pin)
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handlePinModification(Pin pin, IValidationContext ctx) {
- if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) {
- if (testPinOrParameterOrPropertyFeature(ctx.getFeature())) {
- NamedElement invoked = getInvokedObject(pin);
- if (invoked != null) {
- proposeNavigation(invoked);
- return ctx.createFailureStatus();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure Parameter modification is reported on associated Pins
- *
- * @param parameter
- * modified parameter
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleParameterModification(Parameter parameter, IValidationContext ctx) {
- if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) {
- if (testPinOrParameterOrPropertyFeature(ctx.getFeature())) {
- // Update corresponding pins
- CompoundCommand cmd = getUpdatePinsCmd(getPins(parameter), parameter.getType(), parameter.isOrdered(), parameter.isUnique(), parameter.getLower(), parameter.getLowerValue(), parameter.getUpper(), parameter.getUpperValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- if (askForValidation(getCallingActions(parameter.getOwner()))) {
- cmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- } else if (UMLPackage.eINSTANCE.getParameter_Direction().equals(ctx.getFeature())) {
- // Remove/Add corresponding pins with type in accordance to
- // direction
- for (Notification event : ctx.getAllEvents()) {
- if (UMLPackage.eINSTANCE.getParameter_Direction().equals(event.getFeature()) || UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(event.getFeature())) {
- return changePinsBecauseOfParameterDirection(parameter, event, ctx);
- }
- }
- } else if (UMLPackage.eINSTANCE.getNamedElement_Name().equals(ctx.getFeature())) {
- // Synchronize the pin name if not set yet
- CompoundCommand cmd = getSetPinsNamesCmd(getPins(parameter), parameter.getName());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- if (askForValidation(getCallingActions(parameter.getOwner()))) {
- cmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure Property modification is reported on associated Pins
- *
- * @param property
- * modified property
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handlePropertyModification(Property property, IValidationContext ctx) {
- if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) {
- if (testPinOrParameterOrPropertyFeature(ctx.getFeature())) {
- // Update corresponding pins
- CompoundCommand cmd = getUpdatePinsCmd(getPins(property), property.getType(), property.isOrdered(), property.isUnique(), property.getLower(), property.getLowerValue(), property.getUpper(), property.getUpperValue());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- if (askForValidation(getCallingActions(property.getOwner()))) {
- cmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- } else if (UMLPackage.eINSTANCE.getNamedElement_Name().equals(ctx.getFeature())) {
- // Synchronize the pin name if not set yet
- CompoundCommand cmd = getSetPinsNamesCmd(getPins(property), property.getName());
- if (!cmd.isEmpty() && cmd.canExecute()) {
- if (askForValidation(getCallingActions(property.getOwner()))) {
- cmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Change the Pins because parameter's direction has changed
- *
- * @param parameter
- * the modified parameter
- * @param event
- * the direction change event
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus changePinsBecauseOfParameterDirection(TypedElement parameter, Notification event, IValidationContext ctx) {
- // constants used for type safety
- List<Integer> emptyList = Collections.emptyList();
- Map<Integer, TypedElement> emptyMap = Collections.emptyMap();
- Object oldDir = event.getOldValue();
- Object newDir = event.getNewValue();
- int inIndex = getIndex(parameter, true);
- int outIndex = getIndex(parameter, false);
- CompoundCommand globalCmd = new CompoundCommand();
- List<InvocationAction> callingActions = getCallingActions(parameter.getOwner());
- if (ParameterDirectionKind.IN_LITERAL.equals(oldDir)) {
- if (ParameterDirectionKind.OUT_LITERAL.equals(newDir) || ParameterDirectionKind.RETURN_LITERAL.equals(newDir)) {
- // explore referencing actions to remove in and add out
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- CompoundCommand cmd = getRemovePinsCmd((CallAction) action, Collections.singletonList(inIndex), emptyList);
- globalCmd.append(cmd);
- cmd = getAddPinsCmd(action, emptyMap, Collections.singletonMap(outIndex, parameter), null);
- globalCmd.append(cmd);
- }
- }
- } else if (ParameterDirectionKind.INOUT_LITERAL.equals(newDir)) {
- // explore referencing actions to add out
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- CompoundCommand cmd = getAddPinsCmd(action, emptyMap, Collections.singletonMap(outIndex, parameter), null);
- globalCmd.append(cmd);
- }
- }
- }
- } else if (ParameterDirectionKind.OUT_LITERAL.equals(oldDir) || ParameterDirectionKind.RETURN_LITERAL.equals(oldDir)) {
- if (ParameterDirectionKind.IN_LITERAL.equals(newDir)) {
- // explore referencing actions to remove out and add in
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- CompoundCommand cmd = getRemovePinsCmd((CallAction) action, emptyList, Collections.singletonList(outIndex));
- globalCmd.append(cmd);
- cmd = getAddPinsCmd(action, Collections.singletonMap(inIndex, parameter), emptyMap, null);
- globalCmd.append(cmd);
- }
- }
- } else if (ParameterDirectionKind.INOUT_LITERAL.equals(newDir)) {
- // explore referencing actions to add in
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- CompoundCommand cmd = getAddPinsCmd(action, Collections.singletonMap(inIndex, parameter), emptyMap, null);
- globalCmd.append(cmd);
- }
- }
- }
- } else if (ParameterDirectionKind.INOUT_LITERAL.equals(oldDir)) {
- if (ParameterDirectionKind.IN_LITERAL.equals(newDir)) {
- // explore referencing actions to remove out
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- CompoundCommand cmd = getRemovePinsCmd((CallAction) action, emptyList, Collections.singletonList(outIndex));
- globalCmd.append(cmd);
- }
- }
- } else if (ParameterDirectionKind.OUT_LITERAL.equals(newDir) || ParameterDirectionKind.RETURN_LITERAL.equals(newDir)) {
- // explore referencing actions to remove in
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- CompoundCommand cmd = getRemovePinsCmd((CallAction) action, Collections.singletonList(inIndex), emptyList);
- globalCmd.append(cmd);
- }
- }
- }
- }
- if (!globalCmd.isEmpty() && globalCmd.canExecute()) {
- if (askForValidation(callingActions)) {
- globalCmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Get the list of actions invoking this element
- *
- * @param element
- * an Operation or a Behavior or a Signal
- * @return list of InvocationAction
- */
- protected static List<InvocationAction> getCallingActions(Element element) {
- // explore referencing actions
- Set<InvocationAction> callingActions = new HashSet<InvocationAction>();
- if (element instanceof Behavior || element instanceof Operation) {
- Collection<Setting> references = CacheAdapter.getInstance().getNonNavigableInverseReferences(element);
- for (Setting ref : references) {
- EObject action = ref.getEObject();
- // parameter's owner is action's called Operation
- boolean operationCase = UMLPackage.eINSTANCE.getCallOperationAction_Operation().equals(ref.getEStructuralFeature());
- // parameter's owner is action's called Behavior
- boolean behaviorCase = UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior().equals(ref.getEStructuralFeature());
- if ((operationCase || behaviorCase) && action instanceof CallAction && action.eContainer() != null) {
- callingActions.add((CallAction) action);
- }
- }
- } else if (element instanceof Signal) {
- Collection<Setting> references = CacheAdapter.getInstance().getNonNavigableInverseReferences(element);
- for (Setting ref : references) {
- EObject action = ref.getEObject();
- // parameter's owner is action's sent Signal
- boolean signalCase = UMLPackage.eINSTANCE.getSendSignalAction_Signal().equals(ref.getEStructuralFeature());
- if (signalCase && action instanceof SendSignalAction && action.eContainer() != null) {
- callingActions.add((SendSignalAction) action);
- }
- }
- }
- return new ArrayList<InvocationAction>(callingActions);
- }
-
- /**
- * Ensure CallOperationAction modification is reported on associated
- * Operation
- *
- * @param action
- * modified action
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleCallOperationActionModification(CallOperationAction action, IValidationContext ctx) {
- if (testTransformPinCase(ctx)) {
- return ctx.createSuccessStatus();
- } else if (testCustomModificationToValidPins(action, ctx)) {
- return ctx.createSuccessStatus();
- } else if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) {
- if (testActionFeature(ctx.getFeature()) && action.getOperation() != null) {
- if (action.getOperation() != null) {
- if (canCreateParameterFromCallAction(action)) {
- Object pin = ctx.getFeatureNewValue();
- boolean parameterCreated = proposeParameterCreation(action.getOperation(), ((EObject) pin).eClass());
- if (parameterCreated) {
- // remove the user-created value
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- Command cmd = RemoveCommand.create(editingdomain, ctx.getFeatureNewValue());
- cmd.execute();
- return ctx.createSuccessStatus();
- }
- } else {
- /*
- * No modification of parameters is allowed from the
- * CallOperationAction. This means we can not add Pins
- */
- proposeNavigation(action.getOperation());
- }
- return ctx.createFailureStatus();
- }
- }
- } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) {
- if (testActionFeature(ctx.getFeature()) && action.getOperation() != null) {
- /*
- * Yet, no modification of parameters is allowed from the
- * CallOperationAction. This means we can not remove Pins
- */
- if (action.getOperation() != null) {
- proposeNavigation(action.getOperation());
- return ctx.createFailureStatus();
- }
- }
- } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getCallOperationAction_Operation().equals(ctx.getFeature())) {
- /*
- * The operation changes, so must the pins
- */
- CompoundCommand cmd = getResetPinsCmd(action);
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- }
- if (UMLPackage.eINSTANCE.getCallOperationAction_Target().equals(ctx.getFeature())) {
- /*
- * Try to remove or assign target pin. This must not be
- * authorized.
- */
- final String msg = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UndeleteablePinMessage, UMLPackage.eINSTANCE.getCallOperationAction_Target().getName());
- SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() {
-
- @Override
- protected Void openDialog() {
- MessageDialog.openWarning(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UndeleteablePinTitle, msg);
- return null;
- }
- };
- opener.execute();
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * @param node
- * @param ctx
- * @return
- */
- protected boolean testCustomModificationToValidPins(ActivityNode node, IValidationContext ctx) {
- // reflexive code to call each validation method matching the given object in : UMLValidationHelper.class
- // the method call rach public and static method
- IStatus status = null;
- Class<? extends UMLValidationHelper> aClass = UMLValidationHelper.class;
- Method[] methods = aClass.getDeclaredMethods();
- for (Method m : methods) {
- if (Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers()) && m.getReturnType() == IStatus.class) {
- if (m.isAnnotationPresent(PinAndParameterSynchronizeValidator.class) && m.getParameterTypes().length == 2) {
- if (m.getParameterTypes()[0].isInstance(node)) {
- try {
- status = (IStatus) m.invoke(aClass, node, ctx);
- if (status != null && !status.isOK()) {
- break;
- }
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- return status == null || status.isOK();
- }
-
- /**
- * Ensure CallBehaviorAction modification is reported on associated Behavior
- *
- * @param action
- * modified action
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleCallBehaviorActionModification(CallBehaviorAction action, IValidationContext ctx) {
- if (testTransformPinCase(ctx)) {
- return ctx.createSuccessStatus();
- } else if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) {
- if (testActionFeature(ctx.getFeature()) && action.getBehavior() != null) {
- if (action.getBehavior() != null) {
- if (canCreateParameterFromCallAction(action)) {
- Object pin = ctx.getFeatureNewValue();
- boolean parameterCreated = proposeParameterCreation(action.getBehavior(), ((EObject) pin).eClass());
- if (parameterCreated) {
- // remove the user-created value
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- Command cmd = RemoveCommand.create(editingdomain, ctx.getFeatureNewValue());
- cmd.execute();
- return ctx.createSuccessStatus();
- }
- } else {
- /*
- * No modification of parameters is allowed from the
- * CallBehaviorAction. This means we can not add Pins
- */
- proposeNavigation(action.getBehavior());
- }
- return ctx.createFailureStatus();
- }
- }
- } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) {
- if (testActionFeature(ctx.getFeature()) && action.getBehavior() != null) {
- /*
- * Yet, no modification of parameters is allowed from the
- * CallBehaviorAction. This means we can not remove Pins
- */
- if (action.getBehavior() != null) {
- proposeNavigation(action.getBehavior());
- return ctx.createFailureStatus();
- }
- }
- } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior().equals(ctx.getFeature())) {
- /*
- * The behavior changes, so must the pins
- */
- CompoundCommand cmd = getResetPinsCmd(action);
- if (action.getBehavior() != null) {
- String behaviorName = action.getBehavior().getName();
- if (behaviorName != null && !"".equals(behaviorName)) {
- // By the way, update the CallBehaviorAction name
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- cmd.append(SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getNamedElement_Name(), behaviorName));
- }
- }
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Test if a parameter can be created from a call action, after appropriate
- * warnings
- *
- * @param action
- * the call action
- * @return true if we can create a parameter
- */
- protected boolean canCreateParameterFromCallAction(CallAction action) {
- return true;
- }
-
- /**
- * Test if an attribute can be created from a send signal action, after
- * appropriate warnings
- *
- * @param action
- * the send signal action
- * @return true if we can create an attribute
- */
- protected boolean canCreateAttributesFromSendSignalAction(SendSignalAction action) {
- return true;
- }
-
- /**
- * Ensure BroadcastSignalAction modification is reported on associated
- * Signal
- *
- * @param action
- * modified action
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleBroadcastSignalActionModification(BroadcastSignalAction action, IValidationContext ctx) {
- if (testTransformPinCase(ctx)) {
- return ctx.createSuccessStatus();
- } else if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) {
- if (testActionFeature(ctx.getFeature()) && action.getSignal() != null) {
- if (action.getSignal() != null) {
- Object pin = ctx.getFeatureNewValue();
- boolean attributeCreated = proposeAttributeCreation(action.getSignal(), ((EObject) pin).eClass());
- if (attributeCreated) {
- // remove the user-created value
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- Command cmd = RemoveCommand.create(editingdomain, ctx.getFeatureNewValue());
- cmd.execute();
- return ctx.createSuccessStatus();
- }
- return ctx.createFailureStatus();
- }
- }
- } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) {
- if (testActionFeature(ctx.getFeature()) && action.getSignal() != null) {
- /*
- * Yet, no modification of attributes is allowed from the
- * BroadcastSignalAction. This means we can not remove Pins
- */
- if (action.getSignal() != null) {
- proposeNavigation(action.getSignal());
- return ctx.createFailureStatus();
- }
- }
- } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getBroadcastSignalAction_Signal().equals(ctx.getFeature())) {
- /*
- * The signal changes, so must the pins
- */
- CompoundCommand cmd = getResetPinsCmd(action);
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure SendSignalAction modification is reported on associated Signal
- *
- * @param action
- * modified action
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleSendSignalActionModification(SendSignalAction action, IValidationContext ctx) {
- if (testTransformPinCase(ctx)) {
- return ctx.createSuccessStatus();
- } else if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) {
- if (testActionFeature(ctx.getFeature()) && action.getSignal() != null) {
- if (action.getSignal() != null) {
- if (canCreateAttributesFromSendSignalAction(action)) {
- Object pin = ctx.getFeatureNewValue();
- boolean attributeCreated = proposeAttributeCreation(action.getSignal(), ((EObject) pin).eClass());
- if (attributeCreated) {
- // remove the user-created value
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- Command cmd = RemoveCommand.create(editingdomain, ctx.getFeatureNewValue());
- cmd.execute();
- return ctx.createSuccessStatus();
- }
- } else {
- /*
- * No modification of attributes is allowed from the
- * SendSignalAction. This means we can not add Pins
- */
- proposeNavigation(action.getSignal());
- }
- return ctx.createFailureStatus();
- }
- }
- } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) {
- if (testActionFeature(ctx.getFeature()) && action.getSignal() != null) {
- /*
- * Yet, no modification of attributes is allowed from the
- * SendSignalAction. This means we can not remove Pins
- */
- if (action.getSignal() != null) {
- proposeNavigation(action.getSignal());
- return ctx.createFailureStatus();
- }
- }
- } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getSendSignalAction_Signal().equals(ctx.getFeature())) {
- /*
- * The signal changes, so must the pins
- */
- CompoundCommand cmd = getResetPinsCmd(action);
- if (!cmd.isEmpty() && cmd.canExecute()) {
- cmd.execute();
- }
- }
- if (UMLPackage.eINSTANCE.getSendSignalAction_Target().equals(ctx.getFeature())) {
- /*
- * Try to remove or assign target pin. This must not be
- * authorized.
- */
- final String msg = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UndeleteablePinMessage, UMLPackage.eINSTANCE.getSendSignalAction_Target().getName());
- SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() {
-
- @Override
- protected Void openDialog() {
- MessageDialog.openWarning(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UndeleteablePinTitle, msg);
- return null;
- }
- };
- opener.execute();
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure SendObjectAction modification is authorized
- *
- * @param action
- * modified action
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleSendObjectActionModification(SendObjectAction action, IValidationContext ctx) {
- if (testTransformPinCase(ctx)) {
- return ctx.createSuccessStatus();
- } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getSendObjectAction_Target().equals(ctx.getFeature())) {
- /*
- * Try to remove or assign target pin. This must not be
- * authorized.
- */
- final String msg = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UndeleteablePinMessage, UMLPackage.eINSTANCE.getSendObjectAction_Target().getName());
- SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() {
-
- @Override
- protected Void openDialog() {
- MessageDialog.openWarning(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UndeleteablePinTitle, msg);
- return null;
- }
- };
- opener.execute();
- return ctx.createFailureStatus();
- }
- if (UMLPackage.eINSTANCE.getSendObjectAction_Request().equals(ctx.getFeature())) {
- /*
- * Try to remove or assign target pin. This must not be
- * authorized.
- */
- final String msg = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UndeleteablePinMessage, UMLPackage.eINSTANCE.getSendObjectAction_Request().getName());
- SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() {
-
- @Override
- protected Void openDialog() {
- MessageDialog.openWarning(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UndeleteablePinTitle, msg);
- return null;
- }
- };
- opener.execute();
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Test whether the executing operation is a transform into on a pin
- *
- * @param ctx
- * the validation context
- * @return true if we are executing a transform into on a pin
- */
- protected boolean testTransformPinCase(IValidationContext ctx) {
- List<Notification> events = ctx.getAllEvents();
- Object removed = null;
- Object added = null;
- if (events.size() == 1) {
- Notification set = events.get(0);
- if (Notification.SET == set.getEventType()) {
- removed = set.getOldValue();
- added = set.getNewValue();
- }
- } else if (events.size() == 2) {
- Notification remove = events.get(0);
- Notification add = events.get(1);
- if (Notification.REMOVE == remove.getEventType() && Notification.ADD == add.getEventType()) {
- if (remove.getPosition() == add.getPosition() && add.getFeature().equals(remove.getFeature())) {
- removed = remove.getOldValue();
- added = add.getNewValue();
- }
- } else if (Notification.REMOVE_MANY == remove.getEventType() && Notification.ADD_MANY == add.getEventType()) {
- if (Notification.NO_INDEX == remove.getPosition() && add.getFeature().equals(remove.getFeature())) {
- if (remove.getOldValue() instanceof List<?> && add.getNewValue() instanceof List<?>) {
- ArrayList<Object> removeList = new ArrayList<Object>((List<?>) remove.getOldValue());
- removeList.removeAll((List<?>) add.getNewValue());
- ArrayList<Object> addList = new ArrayList<Object>((List<?>) add.getNewValue());
- addList.removeAll((List<?>) remove.getOldValue());
- if (removeList.size() == 1 && addList.size() == 1) {
- removed = removeList.get(0);
- added = addList.get(0);
- }
- }
- }
- }
- }
- // check that replacing pin object is similar before concluding a
- // transform into
- if (removed instanceof Pin && added instanceof Pin) {
- Pin removedPin = (Pin) removed;
- Pin addedPin = (Pin) added;
- boolean similars = true;
- // test name
- similars &= removedPin.getName() == null || removedPin.getName().equals(addedPin.getName());
- // test type
- similars &= EcoreUtil.equals(removedPin.getType(), addedPin.getType());
- // test is ordered
- similars &= removedPin.isOrdered() == addedPin.isOrdered();
- // test multiplicity : is unique
- similars &= removedPin.isUnique() == addedPin.isUnique();
- // test multiplicity : lower value
- similars &= EcoreUtil.equals(removedPin.getLowerValue(), addedPin.getLowerValue());
- // test multiplicity : upper value
- similars &= EcoreUtil.equals(removedPin.getUpperValue(), addedPin.getUpperValue());
- return similars;
- }
- return false;
- }
-
- /**
- * Ensure Operation modification is reported on associated actions
- *
- * @param operation
- * modified operation
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleOperationModification(Operation operation, IValidationContext ctx) {
- if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(ctx.getFeature())) {
- return handleParametersAdded(operation, ctx);
- }
- } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(ctx.getFeature())) {
- return handleParametersRemoved(operation, ctx);
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure Behavior modification is reported on associated actions
- *
- * @param behavior
- * modified behavior
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleBehaviorModification(Behavior behavior, IValidationContext ctx) {
- if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getBehavior_OwnedParameter().equals(ctx.getFeature())) {
- return handleParametersAdded(behavior, ctx);
- }
- } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getBehavior_OwnedParameter().equals(ctx.getFeature())) {
- return handleParametersRemoved(behavior, ctx);
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure Signal modification is reported on associated actions
- *
- * @param signal
- * modified signal
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleSignalModification(Signal signal, IValidationContext ctx) {
- if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getSignal_OwnedAttribute().equals(ctx.getFeature())) {
- return handleAttributesAdded(signal, ctx);
- }
- } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) {
- if (UMLPackage.eINSTANCE.getSignal_OwnedAttribute().equals(ctx.getFeature())) {
- return handleAttributesRemoved(signal, ctx);
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure Pins corresponding to parameters are removed
- *
- * @param element
- * modified operation or behavior
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleParametersRemoved(NamedElement element, IValidationContext ctx) {
- // construct the list of removed indexes and their direction
- Map<Integer, ParameterDirectionKind> removedParameterIndexes = new HashMap<Integer, ParameterDirectionKind>();
- for (Notification event : ctx.getAllEvents()) {
- if (UMLPackage.eINSTANCE.getBehavior_OwnedParameter().equals(event.getFeature()) || UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(event.getFeature())) {
- Object removedValue = event.getOldValue();
- if (removedValue instanceof Parameter) {
- // handle parameter direction
- ParameterDirectionKind dir = ((Parameter) removedValue).getDirection();
- removedParameterIndexes.put(event.getPosition(), dir);
- } else if (removedValue instanceof List<?>) {
- List<?> col = (List<?>) removedValue;
- if (!col.isEmpty()) {
- for (int i = 0; i < col.size(); i++) {
- Object object = col.get(i);
- if (object instanceof Parameter) {
- removedParameterIndexes.put(i, ((Parameter) object).getDirection());
- }
- }
- }
- }
- }
- }
- List<Parameter> newParameters = Collections.emptyList();
- if (element instanceof Behavior) {
- newParameters = ((Behavior) element).getOwnedParameters();
- } else if (element instanceof Operation) {
- newParameters = ((Operation) element).getOwnedParameters();
- }
- List<Integer> removedInputPinIndexes = new LinkedList<Integer>();
- List<Integer> removedOutputPinIndexes = new LinkedList<Integer>();
- Iterator<Parameter> parametersIterator = newParameters.iterator();
- // iterate on the virtual list of old parameters
- // (correspondingParameterIndex) to deduce
- // pins indexes
- int correspondingParameterIndex = 0;
- int correspondingInputPinIndex = 0;
- int correspondingOutputPinIndex = 0;
- while (removedParameterIndexes.containsKey(correspondingParameterIndex) || parametersIterator.hasNext()) {
- if (removedParameterIndexes.containsKey(correspondingParameterIndex)) {
- // parameter removed, pin(s) removed
- switch (removedParameterIndexes.get(correspondingParameterIndex)) {
- case IN_LITERAL:
- removedInputPinIndexes.add(correspondingInputPinIndex);
- correspondingInputPinIndex++;
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- removedOutputPinIndexes.add(correspondingOutputPinIndex);
- correspondingOutputPinIndex++;
- break;
- case INOUT_LITERAL:
- // in-out parameter has two pins
- removedInputPinIndexes.add(correspondingInputPinIndex);
- correspondingInputPinIndex++;
- removedOutputPinIndexes.add(correspondingOutputPinIndex);
- correspondingOutputPinIndex++;
- break;
- }
- } else {
- // parameter not removed, pin(s) not removed
- Parameter nextParam = parametersIterator.next();
- switch (nextParam.getDirection()) {
- case IN_LITERAL:
- correspondingInputPinIndex++;
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- correspondingOutputPinIndex++;
- break;
- case INOUT_LITERAL:
- // in-out parameter has two pins
- correspondingInputPinIndex++;
- correspondingOutputPinIndex++;
- break;
- }
- }
- // explore next parameter
- correspondingParameterIndex++;
- }
- CompoundCommand globalCmd = new CompoundCommand();
- // explore referencing actions
- List<InvocationAction> callingActions = getCallingActions(element);
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- CompoundCommand cmd = getRemovePinsCmd((CallAction) action, removedInputPinIndexes, removedOutputPinIndexes);
- globalCmd.append(cmd);
- }
- }
- if (!globalCmd.isEmpty() && globalCmd.canExecute()) {
- if (askForValidation(callingActions)) {
- globalCmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure Pins corresponding to parameters are added
- *
- * @param element
- * modified operation or behavior
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleParametersAdded(NamedElement element, IValidationContext ctx) {
- // construct the list of added indexes and their direction
- List<Parameter> addedParameters = new LinkedList<Parameter>();
- for (Notification event : ctx.getAllEvents()) {
- if (UMLPackage.eINSTANCE.getBehavior_OwnedParameter().equals(event.getFeature()) || UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(event.getFeature())) {
- Object addedValue = event.getNewValue();
- if (addedValue instanceof Parameter) {
- addedParameters.add((Parameter) addedValue);
- } else if (addedValue instanceof List<?>) {
- List<?> col = (List<?>) addedValue;
- if (!col.isEmpty()) {
- for (int i = 0; i < col.size(); i++) {
- Object object = col.get(i);
- if (object instanceof Parameter) {
- addedParameters.add((Parameter) object);
- }
- }
- }
- }
- }
- }
- List<Parameter> newParameters = Collections.emptyList();
- if (element instanceof Behavior) {
- newParameters = ((Behavior) element).getOwnedParameters();
- } else if (element instanceof Operation) {
- newParameters = ((Operation) element).getOwnedParameters();
- }
- Map<Integer, TypedElement> addedInputPinMap = new HashMap<Integer, TypedElement>();
- Map<Integer, TypedElement> addedOutputPinMap = new HashMap<Integer, TypedElement>();
- // iterate on the list of new parameters to deduce pins indexes
- int correspondingInputPinIndex = 0;
- int correspondingOutputPinIndex = 0;
- for (Parameter param : newParameters) {
- if (addedParameters.contains(param)) {
- // parameter added, pin(s) to add
- switch (param.getDirection()) {
- case IN_LITERAL:
- addedInputPinMap.put(correspondingInputPinIndex, param);
- correspondingInputPinIndex++;
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- addedOutputPinMap.put(correspondingOutputPinIndex, param);
- correspondingOutputPinIndex++;
- break;
- case INOUT_LITERAL:
- // in-out parameter has two pins
- addedInputPinMap.put(correspondingInputPinIndex, param);
- correspondingInputPinIndex++;
- addedOutputPinMap.put(correspondingOutputPinIndex, param);
- correspondingOutputPinIndex++;
- break;
- }
- } else {
- // parameter not added, pin already exists
- switch (param.getDirection()) {
- case IN_LITERAL:
- correspondingInputPinIndex++;
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- correspondingOutputPinIndex++;
- break;
- case INOUT_LITERAL:
- // in-out parameter has two pins
- correspondingInputPinIndex++;
- correspondingOutputPinIndex++;
- break;
- }
- }
- // explore next parameter
- }
- CompoundCommand globalCmd = new CompoundCommand();
- // explore referencing actions
- List<InvocationAction> callingActions = getCallingActions(element);
- for (InvocationAction action : callingActions) {
- if (action instanceof CallAction) {
- CompoundCommand cmd = getAddPinsCmd(action, addedInputPinMap, addedOutputPinMap, null);
- globalCmd.append(cmd);
- }
- }
- if (!globalCmd.isEmpty() && globalCmd.canExecute()) {
- if (askForValidation(callingActions)) {
- globalCmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure Pins corresponding to parameters are removed
- *
- * @param element
- * modified signal
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleAttributesRemoved(Signal element, IValidationContext ctx) {
- // construct the list of removed indexes and their direction
- Set<Integer> removedAttributeIndexes = new HashSet<Integer>();
- for (Notification event : ctx.getAllEvents()) {
- if (UMLPackage.eINSTANCE.getSignal_OwnedAttribute().equals(event.getFeature())) {
- Object removedValue = event.getOldValue();
- if (removedValue instanceof Property) {
- removedAttributeIndexes.add(event.getPosition());
- } else if (removedValue instanceof List<?>) {
- List<?> col = (List<?>) removedValue;
- if (!col.isEmpty()) {
- for (int i = 0; i < col.size(); i++) {
- Object object = col.get(i);
- if (object instanceof Property) {
- removedAttributeIndexes.add(i);
- }
- }
- }
- }
- }
- }
- // deduce pins indexes from old attributes indexes
- List<Integer> removedInputPinIndexes = new LinkedList<Integer>(removedAttributeIndexes);
- CompoundCommand globalCmd = new CompoundCommand();
- // explore referencing actions
- List<InvocationAction> callingActions = getCallingActions(element);
- for (InvocationAction action : callingActions) {
- if (action instanceof SendSignalAction) {
- CompoundCommand cmd = getRemovePinsCmd((SendSignalAction) action, removedInputPinIndexes);
- globalCmd.append(cmd);
- }
- }
- if (!globalCmd.isEmpty() && globalCmd.canExecute()) {
- if (askForValidation(callingActions)) {
- globalCmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Ensure Pins corresponding to attributes are added
- *
- * @param element
- * modified signal
- * @param ctx
- * validation context
- * @return status
- */
- protected IStatus handleAttributesAdded(Signal element, IValidationContext ctx) {
- // construct the list of added indexes and their direction
- List<Property> addedAttributes = new LinkedList<Property>();
- for (Notification event : ctx.getAllEvents()) {
- if (UMLPackage.eINSTANCE.getSignal_OwnedAttribute().equals(event.getFeature())) {
- Object addedValue = event.getNewValue();
- if (addedValue instanceof Property) {
- addedAttributes.add((Property) addedValue);
- } else if (addedValue instanceof List<?>) {
- List<?> col = (List<?>) addedValue;
- if (!col.isEmpty()) {
- for (int i = 0; i < col.size(); i++) {
- Object object = col.get(i);
- if (object instanceof Property) {
- addedAttributes.add((Property) object);
- }
- }
- }
- }
- }
- }
- List<Property> newAttributes = Collections.emptyList();
- if (element instanceof Signal) {
- newAttributes = element.getOwnedAttributes();
- }
- Map<Integer, Property> addedInputPinMap = new HashMap<Integer, Property>();
- // iterate on the list of added attributes to deduce pins indexes
- for (Property param : addedAttributes) {
- if (newAttributes.contains(param)) {
- addedInputPinMap.put(newAttributes.indexOf(param), param);
- }
- }
- CompoundCommand globalCmd = new CompoundCommand();
- // explore referencing actions
- List<InvocationAction> callingActions = getCallingActions(element);
- for (InvocationAction action : callingActions) {
- if (action instanceof SendSignalAction) {
- CompoundCommand cmd = getAddPinsCmd(action, addedInputPinMap, null);
- globalCmd.append(cmd);
- }
- }
- if (!globalCmd.isEmpty() && globalCmd.canExecute()) {
- if (askForValidation(callingActions)) {
- globalCmd.execute();
- } else {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Get the command to update type of target input pins referring the
- * operation
- *
- * @param operation
- * the operation which parent type has changed
- * @return the command
- */
- protected CompoundCommand getUpdateTargetPinsType(Operation operation) {
- CompoundCommand globalCmd = new CompoundCommand();
- // get operation parent type
- Type type = null;
- Element owner = operation.getOwner();
- if (owner instanceof Type) {
- type = (Type) owner;
- }
- if (type != null) {// Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- // explore referencing actions
- for (InvocationAction action : getCallingActions(operation)) {// operation
- // is
- // action's
- // called
- // Operation
- if (action instanceof CallOperationAction) {
- InputPin targetPin = ((CallOperationAction) action).getTarget();
- if (targetPin != null) {
- Command cmd = SetCommand.create(editingdomain, targetPin, UMLPackage.eINSTANCE.getTypedElement_Type(), type);
- globalCmd.append(cmd);
- }
- }
- }
- }
- return globalCmd;
- }
-
- /**
- * Get the command to remove pins linked with parameter at the given indexes
- *
- * @param action
- * the CallOperationAction or CallBehaviorAction (no effect
- * otherwise)
- * @param removedInputPinsIndexes
- * the indexes of input pins to remove (except target)
- * @param removedOutputPinsIndexes
- * the indexes of output pins to remove
- * @return the command to remove corresponding Pins
- */
- protected CompoundCommand getRemovePinsCmd(CallAction action, List<Integer> removedInputPinsIndexes, List<Integer> removedOutputPinsIndexes) {
- CompoundCommand globalCmd = new CompoundCommand();
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- if (action instanceof CallBehaviorAction || action instanceof CallOperationAction) {
- ArrayList<InputPin> removedIn = new ArrayList<InputPin>(removedInputPinsIndexes.size());
- for (int i : removedInputPinsIndexes) {
- if (i < action.getArguments().size()) {
- removedIn.add(action.getArguments().get(i));
- }
- }
- if (!removedIn.isEmpty()) {
- Command cmd = RemoveCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getInvocationAction_Argument(), removedIn);
- globalCmd.append(cmd);
- }
- ArrayList<OutputPin> removedOut = new ArrayList<OutputPin>(removedInputPinsIndexes.size());
- for (int i : removedOutputPinsIndexes) {
- if (i < action.getResults().size()) {
- removedOut.add(action.getResults().get(i));
- }
- }
- if (!removedOut.isEmpty()) {
- Command cmd = RemoveCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getCallAction_Result(), removedOut);
- globalCmd.append(cmd);
- }
- }
- return globalCmd;
- }
-
- /**
- * Get the command to remove pins linked with attribute at the given indexes
- *
- * @param action
- * the SendSignalAction
- * @param removedInputPinsIndexes
- * the indexes of input pins to remove (except target)
- * @return the command to remove corresponding Pins
- */
- protected CompoundCommand getRemovePinsCmd(SendSignalAction action, List<Integer> removedInputPinsIndexes) {
- CompoundCommand globalCmd = new CompoundCommand();
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- if (action instanceof SendSignalAction) {
- ArrayList<InputPin> removedIn = new ArrayList<InputPin>(removedInputPinsIndexes.size());
- for (int i : removedInputPinsIndexes) {
- if (i < action.getArguments().size()) {
- removedIn.add(action.getArguments().get(i));
- }
- }
- if (!removedIn.isEmpty()) {
- Command cmd = RemoveCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getInvocationAction_Argument(), removedIn);
- globalCmd.append(cmd);
- }
- }
- return globalCmd;
- }
-
- /**
- * Get the command to add pins linked with parameter at the given indexes
- *
- * @param invocationAction
- * the CallBehaviorAction or CallOperationAction (no effect
- * otherwise)
- * @param addedInputPinMap
- * the indexes of input pins to add and parameters to copy
- * @param addedOutputPinMap
- * the indexes of output pins to add and parameters to copy
- * @param preferredPinClass
- * the EClass to use to create a new pin whenever possible (or
- * null)
- * @return the command to add corresponding Pins
- */
- protected static CompoundCommand getAddPinsCmd(InvocationAction invocationAction, Map<Integer, TypedElement> addedInputPinMap, Map<Integer, TypedElement> addedOutputPinMap, EClass preferredPinClass) {
- CompoundCommand globalCmd = new CompoundCommand();
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- if (invocationAction instanceof CallBehaviorAction || invocationAction instanceof CallOperationAction || invocationAction instanceof SendSignalAction || invocationAction instanceof BroadcastSignalAction) {
- /*
- * An element can not be added at an index bigger than the size.
- * Hence, add commands must be sorted according to the decreasing
- * index and the index must be adapted taking in account elements
- * that will be added. We use a bucket sort on indexes of both maps.
- */
- int nextKey = addedInputPinMap.size() + invocationAction.getArguments().size();
- int numberOfPinsToAdd = addedInputPinMap.size();
- while (numberOfPinsToAdd > 0) {
- if (addedInputPinMap.containsKey(nextKey)) {
- numberOfPinsToAdd--;
- InputPin pin = createInputPin(addedInputPinMap.get(nextKey), preferredPinClass);
- // index at which pin is added must take in account other
- // pins added after
- int addIndex = nextKey - numberOfPinsToAdd;
- Command cmd = AddCommand.create(editingdomain, invocationAction, UMLPackage.eINSTANCE.getInvocationAction_Argument(), pin, addIndex);
- LinkPinToParameter link = new LinkPinToParameter(pin, addedInputPinMap.get(nextKey));
- CreatePinToParameterLinkEAnnotation linkCommand = new CreatePinToParameterLinkEAnnotation(EditorUtils.getTransactionalEditingDomain(), link);
- globalCmd.append(cmd);
- if (linkCommand != null && linkCommand.canExecute()) {
- globalCmd.append(linkCommand);
- }
- }
- nextKey--;
- }
- if (invocationAction instanceof CallAction) {
- CallAction callAction = (CallAction) invocationAction;
- nextKey = addedOutputPinMap.size() + callAction.getResults().size();
- numberOfPinsToAdd = addedOutputPinMap.size();
- while (numberOfPinsToAdd > 0) {
- if (addedOutputPinMap.containsKey(nextKey)) {
- numberOfPinsToAdd--;
- OutputPin pin = createOutputPin(addedOutputPinMap.get(nextKey));
- // index at which pin is added must take in account other
- // pins added after
- int addIndex = nextKey - numberOfPinsToAdd;
- Command cmd = AddCommand.create(editingdomain, callAction, UMLPackage.eINSTANCE.getCallAction_Result(), pin, addIndex);
- globalCmd.append(cmd);
- LinkPinToParameter link = new LinkPinToParameter(pin, addedOutputPinMap.get(nextKey));
- CreatePinToParameterLinkEAnnotation linkCommand = new CreatePinToParameterLinkEAnnotation(EditorUtils.getTransactionalEditingDomain(), link);
- if (linkCommand != null) {
- globalCmd.append(linkCommand);
- }
- }
- nextKey--;
- }
- }
- }
- return globalCmd;
- }
-
- /**
- * Get the command to add pins linked with properties at the given indexes
- *
- * @param action
- * the SendSignalAction
- * @param addedInputPinMap
- * the indexes of input pins to add and properties to copy
- * @param preferredPinClass
- * the EClass to use to create a new pin whenever possible (or
- * null)
- * @return the command to add corresponding Pins
- */
- public static CompoundCommand getAddPinsCmd(InvocationAction action, Map<Integer, Property> addedInputPinMap, EClass preferredPinClass) {
- CompoundCommand globalCmd = new CompoundCommand();
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- /*
- * An element can not be added at an index bigger than the size. Hence,
- * add commands must be sorted according to the decreasing index and the
- * index must be adapted taking in account elements that will be added.
- * We use a bucket sort on indexes of both maps.
- */
- int nextKey = addedInputPinMap.size() + action.getArguments().size();
- int numberOfPinsToAdd = addedInputPinMap.size();
- while (numberOfPinsToAdd > 0) {
- if (addedInputPinMap.containsKey(nextKey)) {
- numberOfPinsToAdd--;
- InputPin pin = createInputPin(addedInputPinMap.get(nextKey), preferredPinClass);
- // index at which pin is added must take in account other pins
- // added after
- int addIndex = nextKey - numberOfPinsToAdd;
- Command cmd = AddCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getInvocationAction_Argument(), pin, addIndex);
- globalCmd.append(cmd);
- LinkPinToParameter link = new LinkPinToParameter(pin, addedInputPinMap.get(nextKey));
- CreatePinToParameterLinkEAnnotation linkCommand = new CreatePinToParameterLinkEAnnotation(WorkspaceEditingDomainFactory.INSTANCE.getEditingDomain(action.eResource().getResourceSet()), link);
- if (linkCommand != null && linkCommand.canExecute()) {
- globalCmd.append(linkCommand);
- }
- }
- nextKey--;
- }
- return globalCmd;
- }
-
- /**
- * Create an output pin with valued copied from the parameter
- *
- * @param typedElement
- * the reference parameter
- */
- protected static OutputPin createOutputPin(TypedElement typedElement) {
- OutputPin pin = UMLFactory.eINSTANCE.createOutputPin();
- assignUpperBound(pin);
- // Initialize name
- pin.setName(typedElement.getName());
- // Synchronize type
- pin.setType(typedElement.getType());
- if (typedElement instanceof Property) {
- Property property = (Property) typedElement;
- // Synchronize is ordered
- pin.setIsOrdered(property.isOrdered());
- // Synchronize mutliplicity : is unique
- pin.setIsUnique(property.isUnique());
- // Synchronize mutliplicity : lower value
- ValueSpecification lowerValue = property.getLowerValue();
- if (lowerValue != null) {
- // use a copy command for new value
- Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(lowerValue));
- copy.execute();
- Collection<?> result = copy.getResult();
- Object valueToAffect = null;
- if (!result.isEmpty()) {
- valueToAffect = result.iterator().next();
- }
- if (valueToAffect instanceof ValueSpecification) {
- pin.setLowerValue((ValueSpecification) valueToAffect);
- }
- }
- // Synchronize mutliplicity : upper value
- ValueSpecification upperValue = property.getUpperValue();
- if (upperValue != null) {
- // use a copy command for new value
- Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(upperValue));
- copy.execute();
- Collection<?> result = copy.getResult();
- Object valueToAffect = null;
- if (!result.isEmpty()) {
- valueToAffect = result.iterator().next();
- }
- if (valueToAffect instanceof ValueSpecification) {
- pin.setUpperValue((ValueSpecification) valueToAffect);
- }
- }
- }
- return pin;
- }
-
- /**
- * Create a target input pin, eventually from a given operation
- *
- * @param operation
- * the invoked operation or null
- */
- protected static InputPin createTargetPin(Operation operation) {
- InputPin pin = UMLFactory.eINSTANCE.createInputPin();
- assignUpperBound(pin);
- if (operation != null) {
- Element owningType = operation.getOwner();
- if (owningType instanceof Type) {
- pin.setType((Type) owningType);
- }
- }
- pin.setName(TARGET_PIN_INITIALIZATION_NAME);
- return pin;
- }
-
- /**
- * Create a result input pin, eventually from a given operation
- *
- * @param classifier
- * the to set the output type
- */
- protected OutputPin createResultPin(Classifier classifier) {
- OutputPin pin = UMLFactory.eINSTANCE.createOutputPin();
- assignUpperBound(pin);
- if (classifier != null) {
- pin.setType(classifier);
- }
- pin.setName(RESULT_PIN_INITIALIZATION_NAME);
- return pin;
- }
-
- /**
- * Create a result input pin, eventually from a given operation
- *
- * @param var
- * the to set the output type
- */
- protected OutputPin createResultPin(Variable var) {
- OutputPin pin = UMLFactory.eINSTANCE.createOutputPin();
- assignUpperBound(pin);
- if (var != null) {
- pin.setType(var.getType());
- }
- pin.setName(RESULT_IN_READ_VARIABLE_ACTION);
- return pin;
- }
-
- /**
- * Create a request input pin
- *
- * @param operation
- * the invoked operation or null
- */
- public static InputPin createRequestPin() {
- InputPin pin = UMLFactory.eINSTANCE.createInputPin();
- assignUpperBound(pin);
- pin.setName(REQUEST_PIN_INITIALIZATION_NAME);
- return pin;
- }
-
- /**
- * Create an input pin with valued copied from the property
- *
- * @param typedElement
- * the reference property
- * @param preferredPinClass
- * the EClass to use to create a new pin whenever possible (or
- * null)
- */
- public static InputPin createInputPin(TypedElement typedElement, EClass preferredPinClass) {
- InputPin pin;
- if (UMLPackage.eINSTANCE.getValuePin().equals(preferredPinClass)) {
- pin = UMLFactory.eINSTANCE.createValuePin();
- } else if (UMLPackage.eINSTANCE.getActionInputPin().equals(preferredPinClass)) {
- pin = UMLFactory.eINSTANCE.createActionInputPin();
- } else {
- pin = UMLFactory.eINSTANCE.createInputPin();
- }
- assignUpperBound(pin);
- // Initialize name
- pin.setName(typedElement.getName());
- // Synchronize type
- pin.setType(typedElement.getType());
- if (pin instanceof Property) {
- Property property = (Property) pin;
- // Synchronize is ordered
- pin.setIsOrdered(property.isOrdered());
- // Synchronize multiplicity : is unique
- pin.setIsUnique(property.isUnique());
- // Synchronize multiplicity : lower value
- ValueSpecification lowerValue = property.getLowerValue();
- if (lowerValue != null) {
- // use a copy command for new value
- Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(lowerValue));
- copy.execute();
- Collection<?> result = copy.getResult();
- Object valueToAffect = null;
- if (!result.isEmpty()) {
- valueToAffect = result.iterator().next();
- }
- if (valueToAffect instanceof ValueSpecification) {
- pin.setLowerValue((ValueSpecification) valueToAffect);
- }
- }
- // Synchronize multiplicity : upper value
- ValueSpecification upperValue = property.getUpperValue();
- if (upperValue != null) {
- // use a copy command for new value
- Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(upperValue));
- copy.execute();
- Collection<?> result = copy.getResult();
- Object valueToAffect = null;
- if (!result.isEmpty()) {
- valueToAffect = result.iterator().next();
- }
- if (valueToAffect instanceof ValueSpecification) {
- pin.setUpperValue((ValueSpecification) valueToAffect);
- }
- }
- }
- return pin;
- }
-
- /**
- * Create an input pin with valued copied from the parameter
- *
- * @param parameter
- * the reference parameter
- * @param preferredPinClass
- * the EClass to use to create a new pin whenever possible (or
- * null)
- */
- protected static InputPin createInputPin(Parameter parameter, EClass preferredPinClass) {
- InputPin pin;
- if (UMLPackage.eINSTANCE.getValuePin().equals(preferredPinClass)) {
- pin = UMLFactory.eINSTANCE.createValuePin();
- } else if (UMLPackage.eINSTANCE.getActionInputPin().equals(preferredPinClass)) {
- pin = UMLFactory.eINSTANCE.createActionInputPin();
- } else {
- pin = UMLFactory.eINSTANCE.createInputPin();
- }
- assignUpperBound(pin);
- // Initialize name
- pin.setName(parameter.getName());
- // Synchronize type
- pin.setType(parameter.getType());
- // Synchronize is ordered
- pin.setIsOrdered(parameter.isOrdered());
- // Synchronize multiplicity : is unique
- pin.setIsUnique(parameter.isUnique());
- // Synchronize multiplicity : lower value
- ValueSpecification lowerValue = parameter.getLowerValue();
- if (lowerValue != null) {
- // use a copy command for new value
- Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(lowerValue));
- copy.execute();
- Collection<?> result = copy.getResult();
- Object valueToAffect = null;
- if (!result.isEmpty()) {
- valueToAffect = result.iterator().next();
- }
- if (valueToAffect instanceof ValueSpecification) {
- pin.setLowerValue((ValueSpecification) valueToAffect);
- }
- }
- // Synchronize multiplicity : upper value
- ValueSpecification upperValue = parameter.getUpperValue();
- if (upperValue != null) {
- // use a copy command for new value
- Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(upperValue));
- copy.execute();
- Collection<?> result = copy.getResult();
- Object valueToAffect = null;
- if (!result.isEmpty()) {
- valueToAffect = result.iterator().next();
- }
- if (valueToAffect instanceof ValueSpecification) {
- pin.setUpperValue((ValueSpecification) valueToAffect);
- }
- }
- return pin;
- }
-
- /**
- * Get the command to reset all pins of the action.
- *
- * @param action
- * action to reinitialize pins (AddStructuralFeatureValueAction)
- * @return command
- */
- protected CompoundCommand getResetPinsCmd(AddStructuralFeatureValueAction action) {
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- CompoundCommand globalCmd = new CompoundCommand();
- if (action.getValue() == null) {
- InputPin valuePin = createValuePinInAddStructuralFeatureAction(action);
- Command cmdValuePin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getWriteStructuralFeatureAction_Value(), valuePin);
- globalCmd.append(cmdValuePin);
- }
- if (action.getObject() == null) {
- InputPin objectPin = createObjectPinInStructuralFeatureAction(action);
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getStructuralFeatureAction_Object(), objectPin);
- globalCmd.append(cmd);
- }
- if (action.getResult() == null) {
- OutputPin resultPin = createResultPinInStructuralAction(action);
- Command cmdResultPin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getWriteStructuralFeatureAction_Result(), resultPin);
- globalCmd.append(cmdResultPin);
- }
- return globalCmd;
- }
-
- /**
- * Get the command to reset all pins of the action.
- *
- * @param action
- * action to reinitialize pins (ReadVariableAction)
- * @return command
- */
- // Get the editing domain
- protected CompoundCommand getResetPinsCmd(ReadVariableAction action) {
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- CompoundCommand globalCmd = new CompoundCommand();
- if (action.getResult() == null) {
- OutputPin resultPin = createResultPin(action.getVariable());
- Command cmdResultPin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getReadVariableAction_Result(), resultPin);
- globalCmd.append(cmdResultPin);
- }
- return globalCmd;
- }
-
- // /**
- // * Get the command to reset all pins of the action.
- // *
- // * @param action
- // * action to reinitialize pins (BroadcastSignalAction)
- // * @return command
- // */
- // protected CompoundCommand getResetPinsCmd(BroadcastSignalAction action) {
- // // Get the editing domain
- // TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- // CompoundCommand globalCmd = new CompoundCommand();
- // if(action.getSignal() != null) {
- // if(action.getArguments().isEmpty()) {
- // EList<Property> properties = action.getSignal().getAllAttributes();
- // for(Property argument : properties) {
- // InputPin argPin = UMLFactory.eINSTANCE.createInputPin();
- // assignUpperBound(argPin);
- // argPin.setName(argument.getName());
- // argPin.setType(argument.getType());
- // Command cmdArg = AddCommand.create(editingdomain, action, UMLPackage.Literals.INVOCATION_ACTION__ARGUMENT, Arrays.asList(argPin));
- // globalCmd.append(cmdArg);
- // }
- // }
- // }
- // return globalCmd;
- // }
- /**
- * Get the command to reset all pins of the action.
- *
- * @param action
- * action to reinitialize pins (AddVariableValueAction)
- * @return command
- */
- protected CompoundCommand getResetPinsCmd(AddVariableValueAction action) {
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- CompoundCommand globalCmd = new CompoundCommand();
- if (action.getValue() == null) {
- InputPin valuePin = createValuePinInAddVariableValueAction(action.getVariable());
- Command cmdValuePin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getWriteVariableAction_Value(), valuePin);
- globalCmd.append(cmdValuePin);
- }
- if (action.getInsertAt() == null) {
- InputPin insertAtPin = UMLFactory.eINSTANCE.createInputPin();
- assignUpperBound(insertAtPin);
- insertAtPin.setName(INSERT_AT_IN_ADD_VARIABLE_VALUE_ACTION);
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getAddVariableValueAction_InsertAt(), insertAtPin);
- globalCmd.append(cmd);
- }
- return globalCmd;
- }
-
- /**
- * Get the command to reset all pins of the action.
- *
- * @param action
- * action to reinitialize pins (AddStructuralFeatureValueAction)
- * @return command
- */
- public static CompoundCommand getResetPinsCmd(DestroyObjectAction action) {
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- CompoundCommand globalCmd = new CompoundCommand();
- if (action.getTarget() == null) {
- InputPin targetPin = UMLFactory.eINSTANCE.createInputPin();
- assignUpperBound(targetPin);
- targetPin.setName(TARGET_IN_DESTROY_OBJECT_ACTION);
- Command cmdTargetPin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getDestroyObjectAction_Target(), targetPin);
- globalCmd.append(cmdTargetPin);
- }
- return globalCmd;
- }
-
- /**
- * Create a Pin value for a Structural feature action
- *
- * @param action
- * @return
- */
- public static InputPin createValuePinInAddStructuralFeatureAction(StructuralFeatureAction action) {
- InputPin pin = UMLFactory.eINSTANCE.createInputPin();
- assignUpperBound(pin);
- if (action != null) {
- StructuralFeature feature = action.getStructuralFeature();
- if (feature != null && feature.getType() != null) {
- Type owningType = feature.getType();
- if (owningType instanceof Type) {
- pin.setType(owningType);
- }
- }
- }
- pin.setName(VALUE_PIN_IN_STRUCTURAL_FEATURE_VALUE_ACTION);
- return pin;
- }
-
- /**
- * Create a Pin value for a Structural feature action
- *
- * @param action
- * @return
- */
- protected InputPin createValuePinInAddVariableValueAction(Variable var) {
- InputPin pin = UMLFactory.eINSTANCE.createInputPin();
- assignUpperBound(pin);
- if (var != null) {
- Type owningType = var.getType();
- if (owningType instanceof Type) {
- pin.setType(owningType);
- }
- }
- pin.setName(VALUE_IN_ADD_VARIABLE_VALUE_ACTION);
- return pin;
- }
-
- /**
- * Get the command to reset all pins of the action.
- *
- * @param action
- * action to reinitialize pins (SendObjectAction)
- * @return command
- */
- public static CompoundCommand getResetPinsCmd(SendObjectAction action) {
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- CompoundCommand globalCmd = new CompoundCommand();
- // add target pin
- if (action.getTarget() == null) {
- InputPin targetPin = createTargetPin(null);
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getSendObjectAction_Target(), targetPin);
- globalCmd.append(cmd);
- }
- // add request pin
- if (action.getRequest() == null) {
- InputPin requestPin = createRequestPin();
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getSendObjectAction_Request(), requestPin);
- globalCmd.append(cmd);
- }
- return globalCmd;
- }
-
- /**
- * Get the command to reset all pins of the action.
- *
- * @param action
- * action to reinitialize pins (ReadStructuralFeatureAction)
- * @return command
- */
- protected CompoundCommand getResetPinsCmd(ReadStructuralFeatureAction action) {
- // Get the editing domain
- TransactionalEditingDomain editingdomain;
- try {
- editingdomain = ServiceUtilsForEObject.getInstance().getTransactionalEditingDomain(action);
- } catch (ServiceException ex) {
- Log.error(DiagramUIPlugin.getInstance(), DiagramUIStatusCodes.IGNORED_EXCEPTION_WARNING, ex.getMessage(), ex);
- return null;
- }
- CompoundCommand globalCmd = new CompoundCommand();
- // add result pin
- if (action.getResult() == null) {
- OutputPin resultPin = createResultPinInStructuralAction(action);
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getReadStructuralFeatureAction_Result(), resultPin);
- globalCmd.append(cmd);
- }
- // add object pin
- if (action.getObject() == null) {
- InputPin objectPin = createObjectPinInStructuralFeatureAction(action);
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getStructuralFeatureAction_Object(), objectPin);
- globalCmd.append(cmd);
- }
- return globalCmd;
- }
-
- /**
- * Create the object pin of an ReadStructuralAction
- *
- * @param action
- * @return
- */
- public static InputPin createObjectPinInStructuralFeatureAction(StructuralFeatureAction action) {
- InputPin pin = UMLFactory.eINSTANCE.createInputPin();
- assignUpperBound(pin);
- if (action != null) {
- Type type = getTypeFromStructuralFeature(action);
- if (type != null) {
- pin.setType(type);
- }
- }
- pin.setName(OBJECT_PIN_IN_READS_STRUCTURAL_ACTION);
- return pin;
- }
-
- public static Type getTypeFromStructuralFeature(StructuralFeatureAction action) {
- Type type = null;
- StructuralFeature feature = action.getStructuralFeature();
- if (feature != null) {
- Element owner = feature.getOwner();
- if (owner != null) {
- if (feature.getFeaturingClassifiers().contains(owner)) {
- type = ((Type) owner);
- }
- }
- }
- return type;
- }
-
- /**
- * Create a simple output pin for a ReadStructura feature FIXME set type
- *
- * @param action
- * @return
- */
- public static OutputPin createResultPinInStructuralAction(StructuralFeatureAction action) {
- OutputPin pin = UMLFactory.eINSTANCE.createOutputPin();
- assignUpperBound(pin);
- Type type = getTypeFromStructuralFeature(action);
- if (type != null) {
- pin.setType(type);
- }
- pin.setName(RESULT_PIN_READ_SRTUCTURAL_ACTION);
- return pin;
- }
-
- private static void assignUpperBound(ObjectNode node) {
- LiteralInteger literal = UMLFactory.eINSTANCE.createLiteralInteger();
- literal.setValue(1);
- node.setUpperBound(literal);
- }
-
- /**
- * Get the command to reset all pins of the action.
- *
- * @param action
- * action to reinitialize pins (SendObjectAction)
- * @return command
- */
- protected CompoundCommand getResetPinsCmd(CreateObjectAction action) {
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- CompoundCommand globalCmd = new CompoundCommand();
- // add target pin
- if (action.getResult() == null) {
- OutputPin resultPin = createResultPin((Classifier) null);
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getCreateObjectAction_Result(), resultPin);
- globalCmd.append(cmd);
- }
- return globalCmd;
- }
-
- // /**
- // * Get the command to reset all pins of the action.
- // *
- // * @param action
- // * action to reinitialize pins (SendSignalAction)
- // * @return command
- // */
- // public static CompoundCommand getResetPinsCmd(InvocationAction action) {
- // if(!(action instanceof SendSignalAction || action instanceof BroadcastSignalAction)) {
- // return null;
- // }
- // // Get the editing domain
- // TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- // CompoundCommand globalCmd = new CompoundCommand();
- // // remove argument pins
- // if(!action.getArguments().isEmpty()) {
- // Command cmd = RemoveCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getInvocationAction_Argument(), action.getArguments());
- // globalCmd.append(cmd);
- // }
- // // recover attributes
- // List<Property> attributes = Collections.emptyList();
- // Signal signal = action instanceof SendSignalAction ? ((SendSignalAction)action).getSignal() : ((BroadcastSignalAction)action).getSignal();
- // if(signal != null) {
- // attributes = signal.getOwnedAttributes();
- // }
- // // add pins corresponding to attributes
- // Map<Integer, Property> inParameters = new HashMap<Integer, Property>();
- // int inIndex = 0;
- // for(Property att : attributes) {
- // inParameters.put(inIndex, att);
- // inIndex++;
- // }
- // if(!inParameters.isEmpty()) {
- // Command cmd = getAddPinsCmd(action, inParameters, null);
- // globalCmd.append(cmd);
- // }
- // if(action instanceof SendSignalAction) {
- // SendSignalAction sendSignalAction = (SendSignalAction)action;
- // // add target pin
- // if(sendSignalAction.getTarget() == null) {
- // InputPin targetPin = createTargetPin(null);
- // Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getSendSignalAction_Target(), targetPin);
- // globalCmd.append(cmd);
- // }
- // }
- // return globalCmd;
- // }
- /**
- * Retrieve the parameter linked
- *
- * @param p
- * Pin where the EAnnotaion is stored
- * @param xmiResource
- * @return
- */
- public static TypedElement getLinkedParemeter(Pin p, XMIResource xmiResource) {
- if (p != null && xmiResource != null) {
- EAnnotation eAnnotation = p.getEAnnotation(IPinToParameterLinkCommand.PIN_TO_PARAMETER_LINK);
- if (eAnnotation != null && !eAnnotation.getDetails().isEmpty()) {
- String id = eAnnotation.getDetails().get(0).getValue();
- EObject pa = xmiResource.getEObject(id);
- if (pa instanceof TypedElement) {
- return (TypedElement) pa;
- }
- }
- }
- return null;
- }
-
- /**
- * Get the command to reset all pins of the action.
- *
- * @param action
- * action to reinitialize pins (CallOperationAction or
- * CallBehaviorAction)
- * @return command
- */
- public static CompoundCommand getResetPinsCmd(InvocationAction action) {
- // Getting the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- CompoundCommand globalCmd = new CompoundCommand();
- Element behaviorStructural = null;
- List<? extends TypedElement> parameters = Collections.emptyList();
- if (action instanceof CallBehaviorAction) {
- behaviorStructural = ((CallBehaviorAction) action).getBehavior();
- if (behaviorStructural != null) {
- parameters = ((Behavior) behaviorStructural).getOwnedParameters();
- } else {
- return globalCmd;
- }
- } else if (action instanceof CallOperationAction) {
- behaviorStructural = ((CallOperationAction) action).getOperation();
- if (behaviorStructural != null) {
- parameters = ((Operation) behaviorStructural).getOwnedParameters();
- } else {
- return globalCmd;
- }
- } else if (action instanceof SendSignalAction) {
- behaviorStructural = ((SendSignalAction) action).getSignal();
- if (behaviorStructural != null) {
- parameters = ((Signal) behaviorStructural).getOwnedAttributes();
- } else {
- return globalCmd;
- }
- } else if (action instanceof BroadcastSignalAction) {
- Signal signal = ((BroadcastSignalAction) action).getSignal();
- if (signal != null) {
- behaviorStructural = signal;
- parameters = ((Signal) behaviorStructural).getOwnedAttributes();
- } else {
- parameters = Collections.emptyList();
- }
- }
- XMIResource xmiResource = getXMIResource(behaviorStructural);
- // Removing input pins that are not up to date.
- Collection<TypedElement> parameterWhichPinNotDeleted = new ArrayList<TypedElement>();
- Iterable<? extends Pin> allPins = Lists.newArrayList(action.getArguments());
- if (action instanceof CallAction) {
- allPins = Iterables.concat(allPins, ((CallAction) action).getResults());
- }
- List<Command> removesCommand = Lists.newArrayList();
- for (Pin pin : allPins) {
- if (SynchronizePinsParametersHandler.isUpToDate(pin, xmiResource)) {
- TypedElement pa = getLinkedParemeter(pin, xmiResource);
- parameterWhichPinNotDeleted.add(pa);
- } else {
- EReference feature = null;
- if (pin instanceof InputPin) {
- feature = UMLPackage.eINSTANCE.getInvocationAction_Argument();
- } else if (pin instanceof OutputPin) {
- feature = UMLPackage.eINSTANCE.getCallAction_Result();
- }
- // Removing the pin.
- Command cmd = RemoveCommand.create(editingdomain, action, feature, pin);
- if (cmd.canExecute()) {
- removesCommand.add(cmd);
- }
- }
- }
- // Splitting parameters
- Map<Integer, TypedElement> inParams = new HashMap<Integer, TypedElement>();
- Map<Integer, TypedElement> outParams = new HashMap<Integer, TypedElement>();
- splitParameters(parameters, parameterWhichPinNotDeleted, inParams, outParams, action);
- // Creating new pins.
- if (!inParams.isEmpty() || !outParams.isEmpty()) {
- Command cmd = getAddPinsCmd(action, inParams, outParams, null);
- globalCmd.append(cmd);
- }
- /*
- * Append remove command after create command since create command calculate index of new pins before removing those pins
- */
- for (Command rmComand : removesCommand) {
- globalCmd.append(rmComand);
- }
- /*
- * No need to reset this pin
- */
- if (action instanceof CallOperationAction) {
- // add target pin
- Operation operation = ((CallOperationAction) action).getOperation();
- if (operation != null) {
- InputPin targetPin = createTargetPin(operation);
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getCallOperationAction_Target(), targetPin);
- globalCmd.append(cmd);
- }
- } else if (action instanceof SendSignalAction) {
- SendSignalAction sendSignalAction = (SendSignalAction) action;
- // add target pin
- if (sendSignalAction.getTarget() == null) {
- InputPin targetPin = createTargetPin(null);
- Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getSendSignalAction_Target(), targetPin);
- globalCmd.append(cmd);
- }
- }
- return globalCmd;
- }
-
- /**
- * Split a list of parameters in two lists : in and out parameters. If a parameter is to be ignored, then "null" is added to the
- * corresponding list instead.
- */
- public static void splitParameters(List<? extends TypedElement> allParams, Collection<? extends TypedElement> paramsToIgnore, Map<Integer, TypedElement> inParams, Map<Integer, TypedElement> outParams, Action action) {
- if (action instanceof CallAction) {
- Integer inIndex = 0;
- Integer outIndex = 0;
- for (TypedElement typeElem : allParams) {
- if (typeElem instanceof Parameter) {
- Parameter param = (Parameter) typeElem;
- ParameterDirectionKind direction = param.getDirection();
- // In
- if (direction == ParameterDirectionKind.IN_LITERAL || direction == ParameterDirectionKind.INOUT_LITERAL) {
- if (!paramsToIgnore.contains(param)) {
- inParams.put(inIndex, param);
- }
- inIndex++;
- }
- // Out
- if (direction == ParameterDirectionKind.OUT_LITERAL || direction == ParameterDirectionKind.INOUT_LITERAL || direction == ParameterDirectionKind.RETURN_LITERAL) {
- if (!paramsToIgnore.contains(param)) {
- outParams.put(outIndex, param);
- }
- outIndex++;
- }
- }
- }
- } else if (action instanceof InvocationAction) {
- Integer inIndex = 0;
- for (TypedElement typeElem : allParams) {
- if (!paramsToIgnore.contains(typeElem)) {
- inParams.put(inIndex, typeElem);
- }
- inIndex++;
- }
- }
- }
-
- /**
- * Retrieves the XMIResource
- *
- * @param behaviorStructural
- * @return
- */
- public static XMIResource getXMIResource(Element behaviorStructural) {
- XMIResource xmiResource = null;
- if (behaviorStructural != null) {
- Resource resource = behaviorStructural.eResource();
- if (resource instanceof XMIResource) {
- xmiResource = (XMIResource) resource;
- }
- }
- return xmiResource;
- }
-
- /**
- * Get the command to update a pins list with the name if not set yet
- *
- * @param pins
- * the list of pins to update
- * @param name
- * the new name set on parameter
- * @return the command to execute
- */
- protected CompoundCommand getSetPinsNamesCmd(List<Pin> pins, String name) {
- CompoundCommand globalCmd = new CompoundCommand();
- if (pins == null || name == null || "".equals(name)) {
- return globalCmd;
- }
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- for (Pin pin : pins) {
- // erase the name only if null (not set, the user may have set an
- // empty string name)
- if (pin.getName() == null) {
- // add the command
- Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getNamedElement_Name(), name);
- globalCmd.append(cmd);
- }
- }
- return globalCmd;
- }
-
- /**
- * Get the command to update a pins list with given values
- *
- * @param pins
- * the list of pins to update
- * @param type
- * the new type value
- * @param ordered
- * the new isOrdered value
- * @param unique
- * the new isUnique value
- * @param lower
- * the new lower value
- * @param lowerValue
- * the new lowerValue value
- * @param upper
- * the new upper value
- * @param upperValue
- * the new upperValue value
- * @return the command to execute
- */
- protected CompoundCommand getUpdatePinsCmd(List<Pin> pins, Type type, boolean ordered, boolean unique, int lower, ValueSpecification lowerValue, int upper, ValueSpecification upperValue) {
- CompoundCommand globalCmd = new CompoundCommand();
- if (pins == null) {
- return globalCmd;
- }
- // Get the editing domain
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- for (Pin pin : pins) {
- if (!EcoreUtil.equals(pin.getType(), type)) {
- // add the command
- Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getTypedElement_Type(), type);
- globalCmd.append(cmd);
- }
- if (pin.isOrdered() != ordered) {
- // add the command
- Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getMultiplicityElement_IsOrdered(), ordered);
- globalCmd.append(cmd);
- }
- if (pin.isUnique() != unique) {
- // add the command
- Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getMultiplicityElement_IsUnique(), unique);
- globalCmd.append(cmd);
- }
- // UMLPackage.eINSTANCE.getMultiplicityElement_Lower() is derived
- // from
- // UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue()
- if (!EcoreUtil.equals(pin.getLowerValue(), lowerValue)) {
- Object affectedvalue = null;
- // Execute a copy command then add the set command
- if (lowerValue != null) {
- Command copy = CopyCommand.create(editingdomain, Collections.singleton(lowerValue));
- copy.execute();
- Collection<?> result = copy.getResult();
- if (!result.isEmpty()) {
- affectedvalue = result.iterator().next();
- }
- }
- Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue(), affectedvalue);
- globalCmd.append(cmd);
- }
- // UMLPackage.eINSTANCE.getMultiplicityElement_Upper() is derived
- // from
- // UMLPackage.eINSTANCE.getMultiplicityElement_UpperValue()
- if (!EcoreUtil.equals(pin.getUpperValue(), upperValue)) {
- Object affectedvalue = null;
- // Execute a copy command then add the set command
- if (upperValue != null) {
- Command copy = CopyCommand.create(editingdomain, Collections.singleton(upperValue));
- copy.execute();
- Collection<?> result = copy.getResult();
- if (!result.isEmpty()) {
- affectedvalue = result.iterator().next();
- }
- }
- Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getMultiplicityElement_UpperValue(), affectedvalue);
- globalCmd.append(cmd);
- }
- }
- return globalCmd;
- }
-
- /**
- * Get the object invoked by the pin's parent action
- *
- * @return invoked operation, invoked behavior or null
- */
- static protected NamedElement getInvokedObject(Pin pin) {
- Element action = pin.getOwner();
- if (action instanceof CallOperationAction) {
- Operation operation = ((CallOperationAction) action).getOperation();
- return operation;
- } else if (action instanceof CallBehaviorAction) {
- Behavior behavior = ((CallBehaviorAction) action).getBehavior();
- return behavior;
- } else if (action instanceof SendSignalAction) {
- Signal signal = ((SendSignalAction) action).getSignal();
- return signal;
- }
- return null;
- }
-
- /**
- * Get all Pins associated to the property (provided no pin or property has
- * been added without synchronization)
- *
- * @param property
- * the property
- * @return the list of associated pins
- */
- static protected List<Pin> getPins(Property property) {
- Element owner = property.getOwner();
- if (owner instanceof Signal) {
- // initialize listOfPins
- List<Pin> listOfPins = new LinkedList<Pin>();
- // get index of pins
- int inIndex = ((Signal) owner).getAttributes().indexOf(property);
- List<InvocationAction> callingActions = getCallingActions(owner);
- // inspect each referencing action
- for (InvocationAction action : callingActions) {
- // owner is action's sent Signal
- Pin pin = ((SendSignalAction) action).getArguments().get(inIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- }
- return listOfPins;
- }
- return Collections.emptyList();
- }
-
- /**
- * Get all Pins associated to the parameter (provided no pin or parameter
- * has been added without synchronization)
- *
- * @param parameter
- * the parameter
- * @return the list of associated pins
- */
- static protected List<Pin> getPins(Parameter parameter) {
- Element owner = parameter.getOwner();
- List<InvocationAction> callingActions = getCallingActions(owner);
- // initialize listOfPins
- List<Pin> listOfPins = new LinkedList<Pin>();
- // get index of pins
- int inIndex = -1;
- int outIndex = -1;
- switch (parameter.getDirection()) {
- case IN_LITERAL:
- inIndex = getIndex(parameter, true);
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- outIndex = getIndex(parameter, false);
- break;
- case INOUT_LITERAL:
- inIndex = getIndex(parameter, true);
- outIndex = getIndex(parameter, false);
- break;
- }
- if (owner instanceof Operation) {
- // inspect each referencing action
- for (InvocationAction action : callingActions) {
- // owner is action's called Operation
- switch (parameter.getDirection()) {
- case IN_LITERAL:
- Pin pin = ((CallOperationAction) action).getArguments().get(inIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- pin = ((CallOperationAction) action).getResults().get(outIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- break;
- case INOUT_LITERAL:
- pin = ((CallOperationAction) action).getArguments().get(inIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- pin = ((CallOperationAction) action).getResults().get(outIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- break;
- }
- }
- return listOfPins;
- } else if (owner instanceof Behavior) {
- // inspect each referencing action
- for (InvocationAction action : callingActions) {
- // owner is action's called Behavior
- switch (parameter.getDirection()) {
- case IN_LITERAL:
- Pin pin = ((CallBehaviorAction) action).getArguments().get(inIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- pin = ((CallBehaviorAction) action).getResults().get(outIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- break;
- case INOUT_LITERAL:
- pin = ((CallBehaviorAction) action).getArguments().get(inIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- pin = ((CallBehaviorAction) action).getResults().get(outIndex);
- if (pin != null) {
- listOfPins.add(pin);
- }
- break;
- }
- }
- return listOfPins;
- }
- return Collections.emptyList();
- }
-
- /**
- * Get the index (considering Parameters in or out parameters only) at which
- * the parameter appears in its container. For convenience with Pin mapping,
- * in-out parameters counted are in both solution. Note that this count does
- * not take in account the searched for parameter direction. This means that
- * this method works even if the searched parameter has a different
- * direction than the one specified in in (usefull when direction changes).
- *
- * @param typedElement
- * the searched parameter
- * @param in
- * if true, compute position in Parameters of direction in, if
- * false, of direction out
- * @return the position in which the parameter appears (0 based) or -1 if
- * failed
- */
- static protected int getIndex(TypedElement typedElement, boolean in) {
- if (typedElement == null) {
- return -1;
- }
- Element owner = typedElement.getOwner();
- List<Parameter> parametersList = Collections.emptyList();
- if (owner instanceof Operation) {
- parametersList = ((Operation) owner).getOwnedParameters();
- } else if (owner instanceof Behavior) {
- parametersList = ((Behavior) owner).getOwnedParameters();
- }
- int index = 0;
- for (Parameter param : parametersList) {
- if (param.equals(typedElement)) {
- return index;
- }
- if (in && (ParameterDirectionKind.IN_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.INOUT_LITERAL.equals(param.getDirection()))) {
- index++;
- } else if (!in && (ParameterDirectionKind.OUT_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.RETURN_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.INOUT_LITERAL.equals(param.getDirection()))) {
- index++;
- }
- }
- return -1;
- }
-
- /**
- * Ask the user to validate all the implied modifications (parameters and
- * all associated pins)
- *
- * @param listOfActions
- * the list of impacted calling actions
- * @return whether the user validates the modifications
- */
- protected boolean askForValidation(final List<? extends NamedElement> listOfActions) {
- SafeDialogOpenerDuringValidation<Boolean> opener = new SafeDialogOpenerDuringValidation<Boolean>() {
-
- @Override
- protected Boolean openDialog() {
- return ConfirmPinAndParameterSyncDialog.openConfirmFromParameter(Display.getDefault().getActiveShell(), listOfActions, labelProvider);
- }
- };
- return opener.execute();
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * Olivier Melois (Atos) : olivier.melois@atos.net - 371712 + * Arthur Daussy (Atos) : arthur.daussy@atos.net - 371712 + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.common.command.CompoundCommand; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EAnnotation; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.EStructuralFeature.Setting; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.emf.ecore.xmi.XMIResource; +import org.eclipse.emf.edit.command.AddCommand; +import org.eclipse.emf.edit.command.CopyCommand; +import org.eclipse.emf.edit.command.RemoveCommand; +import org.eclipse.emf.edit.command.SetCommand; +import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.emf.validation.AbstractModelConstraint; +import org.eclipse.emf.validation.EMFEventType; +import org.eclipse.emf.validation.IValidationContext; +import org.eclipse.emf.workspace.WorkspaceEditingDomainFactory; +import org.eclipse.gmf.runtime.common.core.util.Log; +import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIPlugin; +import org.eclipse.gmf.runtime.diagram.ui.internal.DiagramUIStatusCodes; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.ILabelProvider; +import org.eclipse.jface.window.Window; +import org.eclipse.osgi.util.NLS; +import org.eclipse.papyrus.infra.core.services.ServiceException; +import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForEObject; +import org.eclipse.papyrus.infra.ui.util.EditorUtils; +import org.eclipse.papyrus.uml.diagram.activity.commands.CreatePinToParameterLinkEAnnotation; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.ConfirmPinAndParameterSyncDialog; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndCreateAttributeDialog; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndCreateParameterDialog; +import org.eclipse.papyrus.uml.diagram.activity.edit.dialogs.WarningAndLinkDialog; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.BroadcastSignalActionEditPart; +import org.eclipse.papyrus.uml.diagram.activity.handlers.SynchronizePinsParametersHandler; +import org.eclipse.papyrus.uml.diagram.activity.helper.datastructure.LinkPinToParameter; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.uml2.common.util.CacheAdapter; +import org.eclipse.uml2.uml.Action; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.AddStructuralFeatureValueAction; +import org.eclipse.uml2.uml.AddVariableValueAction; +import org.eclipse.uml2.uml.Behavior; +import org.eclipse.uml2.uml.BroadcastSignalAction; +import org.eclipse.uml2.uml.CallAction; +import org.eclipse.uml2.uml.CallBehaviorAction; +import org.eclipse.uml2.uml.CallOperationAction; +import org.eclipse.uml2.uml.Classifier; +import org.eclipse.uml2.uml.CreateObjectAction; +import org.eclipse.uml2.uml.DestroyObjectAction; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.InputPin; +import org.eclipse.uml2.uml.InvocationAction; +import org.eclipse.uml2.uml.LiteralInteger; +import org.eclipse.uml2.uml.NamedElement; +import org.eclipse.uml2.uml.ObjectNode; +import org.eclipse.uml2.uml.Operation; +import org.eclipse.uml2.uml.OutputPin; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.ParameterDirectionKind; +import org.eclipse.uml2.uml.Pin; +import org.eclipse.uml2.uml.Property; +import org.eclipse.uml2.uml.ReadStructuralFeatureAction; +import org.eclipse.uml2.uml.ReadVariableAction; +import org.eclipse.uml2.uml.SendObjectAction; +import org.eclipse.uml2.uml.SendSignalAction; +import org.eclipse.uml2.uml.Signal; +import org.eclipse.uml2.uml.StructuralFeature; +import org.eclipse.uml2.uml.StructuralFeatureAction; +import org.eclipse.uml2.uml.Type; +import org.eclipse.uml2.uml.TypedElement; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; +import org.eclipse.uml2.uml.ValueSpecification; +import org.eclipse.uml2.uml.Variable; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * The PinAndParameterSynchronizer is a validator (see corresponding extensions) + * which ensure Pins and their corresponding (if a correspondance can be + * established) Parameters are correctly synchronized + * + */ +public class PinAndParameterSynchronizer extends AbstractModelConstraint { + + private static final String RESULT_IN_READ_VARIABLE_ACTION = "result"; + + private static final String VALUE_IN_ADD_VARIABLE_VALUE_ACTION = "value"; + + private static final String INSERT_AT_IN_ADD_VARIABLE_VALUE_ACTION = "insertAt"; + + private static final String TARGET_IN_DESTROY_OBJECT_ACTION = "target"; + + private static final String VALUE_PIN_IN_STRUCTURAL_FEATURE_VALUE_ACTION = VALUE_IN_ADD_VARIABLE_VALUE_ACTION; + + private static final String RESULT_PIN_READ_SRTUCTURAL_ACTION = "result"; + + private static final String OBJECT_PIN_IN_READS_STRUCTURAL_ACTION = "object"; + + /** The label provider */ + private static final ILabelProvider labelProvider = new AdapterFactoryLabelProvider(UMLDiagramEditorPlugin.getInstance().getItemProvidersAdapterFactory()); + + /** The constant to initialize target pin name */ + private static final String TARGET_PIN_INITIALIZATION_NAME = "target"; + + /** The constant to initialize request pin name */ + private static final String REQUEST_PIN_INITIALIZATION_NAME = "request"; + + /** The constant to initialize result pin name */ + private static final String RESULT_PIN_INITIALIZATION_NAME = "result"; + + /** + * Validate modification and update associated elements if necessary + * + * @see org.eclipse.emf.validation.AbstractModelConstraint#validate(org.eclipse.emf.validation.IValidationContext) + * + * @param ctx + * validation context + * @return status + */ + @Override + public IStatus validate(IValidationContext ctx) { + try { + EObject eObject = ctx.getTarget(); + // handle action creation separately not to confuse with case when + // Behavior is modified + /********* + * Done + *********/ + if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof CallBehaviorAction) { + // CallBehaviorAction created + CompoundCommand cmd = getResetPinsCmd((CallAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof CallOperationAction) { + // CallOperationAction created + CompoundCommand cmd = getResetPinsCmd((CallAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof SendSignalAction) { + // SendSignalAction created + CompoundCommand cmd = getResetPinsCmd((SendSignalAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof SendObjectAction) { + // SendObjectAction created + CompoundCommand cmd = getResetPinsCmd((SendObjectAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof DestroyObjectAction) { + // SendObjectAction created + CompoundCommand cmd = getResetPinsCmd((DestroyObjectAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && (ctx.getFeatureNewValue() instanceof AddStructuralFeatureValueAction)) { + // CreateObject Action created + CompoundCommand cmd = getResetPinsCmd((AddStructuralFeatureValueAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof ReadStructuralFeatureAction) { + // SendObjectAction created + CompoundCommand cmd = getResetPinsCmd((ReadStructuralFeatureAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof AddVariableValueAction) { + // SendObjectAction created + CompoundCommand cmd = getResetPinsCmd((AddVariableValueAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof ReadVariableAction) { + // SendObjectAction created + CompoundCommand cmd = getResetPinsCmd((ReadVariableAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof BroadcastSignalAction) { + // SendObjectAction created + CompoundCommand cmd = getResetPinsCmd((InvocationAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + /********* + * Done + *********/ + } else if ((EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) && ctx.getFeatureNewValue() instanceof CreateObjectAction) { + // CreateObject Action created + CompoundCommand cmd = getResetPinsCmd((CreateObjectAction) ctx.getFeatureNewValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + } + /********* + * Done + *********/ + // handle Operation move for redefining target pin type + if ((EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) && UMLPackage.eINSTANCE.getOperation_Class().equals(ctx.getFeature()) && eObject instanceof Operation) { + // Operation moved + CompoundCommand cmd = getUpdateTargetPinsType((Operation) eObject); + if (!cmd.isEmpty() && cmd.canExecute()) { + if (askForValidation(getCallingActions((Operation) eObject))) { + cmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + } + /********* + * Done + *********/ + if (eObject instanceof ValueSpecification) { + // the value specification may be in an upperValue or lowerValue + // replace values with appropriate ones + EObject topValueSpec = eObject; + while (topValueSpec.eContainer() instanceof ValueSpecification) { + topValueSpec = topValueSpec.eContainer(); + } + eObject = topValueSpec.eContainer(); + } + /********* + * Done + *********/ + if (eObject instanceof Pin) { + // special case for CallOperationAction target pin : no + // synchronization, but type + Element owner = ((Pin) eObject).getOwner(); + Pin target = null; + if (owner instanceof CallOperationAction) { + target = ((CallOperationAction) owner).getTarget(); + } + if (target != null && target.equals(eObject)) { + return handleTargetPinModification((Pin) eObject, ctx); + } else { + // Pin is modified, report modification on + // Parameter/Property + return handlePinModification((Pin) eObject, ctx); + } + /********* + * Done + *********/ + } else if (eObject instanceof Parameter) { + // Parameter is modified, report modification on Pins + return handleParameterModification((Parameter) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof Property) { + // Property is modified, report modification on Pins + return handlePropertyModification((Property) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof CallOperationAction) { + // action is modified, ensure deleted/added Pin impact a + // Parameter + return handleCallOperationActionModification((CallOperationAction) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof Operation) { + // Operation is modified, ensure deleted/added Parameter impact + // Pins + return handleOperationModification((Operation) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof CallBehaviorAction) { + // action is modified, ensure deleted/added Pin impact a + // Parameter + return handleCallBehaviorActionModification((CallBehaviorAction) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof Behavior) { + // Behavior is modified, ensure deleted/added Parameter impact + // Pins + return handleBehaviorModification((Behavior) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof SendSignalAction) { + // action is modified, ensure deleted/added Pin impact a + // Property + return handleSendSignalActionModification((SendSignalAction) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof Signal) { + // Signal is modified, ensure deleted/added Property impact Pins + return handleSignalModification((Signal) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof SendObjectAction) { + // action is modified, ensure deleted/added Pin are authorized + return handleSendObjectActionModification((SendObjectAction) eObject, ctx); + /********* + * Done + *********/ + } else if (eObject instanceof BroadcastSignalAction) { + // action is modified, ensure deleted/added Pin impact a + // Property + return handleBroadcastSignalActionModification((BroadcastSignalAction) eObject, ctx); + } + return ctx.createSuccessStatus(); + } catch (RuntimeException rte) { + // avoid throwing uncaught exception which would disable the + // constraint + Log.warning(DiagramUIPlugin.getInstance(), DiagramUIStatusCodes.IGNORED_EXCEPTION_WARNING, "Unexpected exception during Pin and Parameter synchronization : ", rte); + // ensure that the constraint's failure does not prevent + // modification + return ctx.createSuccessStatus(); + } + } + + /** + * Test if the Pin feature impacts the parameter or if the Parameter feature + * impacts pins + * + * @param modifiedFeature + * the feature to test + * @return true if the feature impacts the associated Parameter or Pin + * objects + */ + protected boolean testPinOrParameterOrPropertyFeature(EStructuralFeature modifiedFeature) { + boolean type = UMLPackage.eINSTANCE.getTypedElement_Type().equals(modifiedFeature); + boolean ordering = UMLPackage.eINSTANCE.getMultiplicityElement_IsOrdered().equals(modifiedFeature); + boolean multiplicity = UMLPackage.eINSTANCE.getMultiplicityElement_IsUnique().equals(modifiedFeature) || UMLPackage.eINSTANCE.getMultiplicityElement_Lower().equals(modifiedFeature) + || UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue().equals(modifiedFeature) || UMLPackage.eINSTANCE.getMultiplicityElement_Upper().equals(modifiedFeature) + || UMLPackage.eINSTANCE.getMultiplicityElement_UpperValue().equals(modifiedFeature); + boolean inAValueSpecification = modifiedFeature != null && ValueSpecification.class.isAssignableFrom(modifiedFeature.getContainerClass()); + return type || ordering || multiplicity || inAValueSpecification; + } + + /** + * Test if the Action feature impacts the number of Pins and Parameters + * + * @param modifiedFeature + * the feature to test + * @return true if the feature impacts the number of Parameters or Pins + */ + protected boolean testActionFeature(EStructuralFeature modifiedFeature) { + boolean input = UMLPackage.eINSTANCE.getInvocationAction_Argument().equals(modifiedFeature) || UMLPackage.eINSTANCE.getCallOperationAction_Target().equals(modifiedFeature); + boolean output = UMLPackage.eINSTANCE.getCallAction_Result().equals(modifiedFeature); + return input || output; + } + + /** + * Ensure target Pin modification is correct + * + * @param pin + * modified pin + * @param ctx + * validation context + * @return status + */ + protected IStatus handleTargetPinModification(Pin pin, IValidationContext ctx) { + // the type of the target pin can not be modified. + if (UMLPackage.eINSTANCE.getTypedElement_Type().equals(ctx.getFeature())) { + Element owner = pin.getOwner(); + if (owner instanceof CallOperationAction && ((CallOperationAction) owner).getOperation() != null) { + proposeNavigation(((CallOperationAction) owner).getOperation()); + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Propose the user to create a parameter in the given element + * + * @param element + * element to navigate to or to create a parameter in + * @param preferredPinClass + * the direction to select as default (or null) + */ + protected boolean proposeParameterCreation(final NamedElement element, final EClass preferredPinClass) { + final String elementLabel = labelProvider.getText(element); + final String message = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UnauthorizedModification, elementLabel); + final ParameterDirectionKind preferredDirection; + if (UMLPackage.eINSTANCE.getOutputPin().isSuperTypeOf(preferredPinClass)) { + preferredDirection = ParameterDirectionKind.OUT_LITERAL; + } else { + preferredDirection = ParameterDirectionKind.IN_LITERAL; + } + SafeDialogOpenerDuringValidation<Boolean> opener = new SafeDialogOpenerDuringValidation<Boolean>() { + + @Override + protected Boolean openDialog() { + WarningAndCreateParameterDialog dialog = new WarningAndCreateParameterDialog(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UnauthorizedModificationTitle, message, element, labelProvider, preferredDirection); + boolean result = dialog.open() == Window.OK; + if (result) { + Parameter parameter = dialog.getParameter(); + handleParameterCreatedDuringValidation(parameter, preferredPinClass); + } + return result; + } + }; + return opener.execute(); + } + + /** + * Correct the model to add required pins, taking in account the parameter + * which has just been created with no validation feedback. + * + * @param parameter + * the created parameter + * @param preferredPinClass + * the EClass the user would like to create a pin of + */ + protected void handleParameterCreatedDuringValidation(Parameter parameter, EClass preferredPinClass) { + if (parameter != null) { + Map<Integer, TypedElement> empty = Collections.emptyMap(); + CompoundCommand globalCmd = new CompoundCommand(); + // explore referencing actions + List<InvocationAction> callingActions = getCallingActions(parameter.getOwner()); + switch (parameter.getDirection()) { + case IN_LITERAL: + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + int index = action.getArguments().size(); + CompoundCommand cmd = getAddPinsCmd(action, Collections.singletonMap(index, (TypedElement) parameter), empty, preferredPinClass); + globalCmd.append(cmd); + } + } + break; + case OUT_LITERAL: + case RETURN_LITERAL: + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + int index = ((CallAction) action).getResults().size(); + CompoundCommand cmd = getAddPinsCmd(action, empty, Collections.singletonMap(index, (TypedElement) parameter), preferredPinClass); + globalCmd.append(cmd); + } + } + break; + case INOUT_LITERAL: + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + int indexIn = action.getArguments().size(); + int indexOut = ((CallAction) action).getResults().size(); + CompoundCommand cmd = getAddPinsCmd(action, Collections.singletonMap(indexIn, (TypedElement) parameter), Collections.singletonMap(indexOut, (TypedElement) parameter), preferredPinClass); + globalCmd.append(cmd); + } + } + break; + } + if (!globalCmd.isEmpty() && globalCmd.canExecute()) { + globalCmd.execute(); + } + } + } + + /** + * Propose the user to create an attribute in the given element + * + * @param element + * element to navigate to or to create an attribute in + * @param preferredPinClass + * the direction to select as default (or null) + */ + protected boolean proposeAttributeCreation(final NamedElement element, final EClass preferredPinClass) { + final String elementLabel = labelProvider.getText(element); + final String message = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UnauthorizedModification, elementLabel); + SafeDialogOpenerDuringValidation<Boolean> opener = new SafeDialogOpenerDuringValidation<Boolean>() { + + @Override + protected Boolean openDialog() { + WarningAndCreateAttributeDialog dialog = new WarningAndCreateAttributeDialog(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UnauthorizedModificationTitle, message, element, labelProvider); + boolean result = dialog.open() == Window.OK; + if (result) { + Property attribute = dialog.getAttribute(); + handlePropertyCreatedDuringValidation(attribute, preferredPinClass); + } + return result; + } + }; + return opener.execute(); + } + + /** + * Correct the model to add required pins, taking in account the property + * which has just been created with no validation feedback. + * + * @param property + * the created property + * @param preferredPinClass + * the EClass the user would like to create a pin of + */ + protected void handlePropertyCreatedDuringValidation(Property property, EClass preferredPinClass) { + if (property != null) { + Map<Integer, Parameter> empty = Collections.emptyMap(); + CompoundCommand globalCmd = new CompoundCommand(); + // explore referencing actions + List<InvocationAction> callingActions = getCallingActions(property.getOwner()); + for (InvocationAction action : callingActions) { + if (action instanceof SendSignalAction || action instanceof BroadcastSignalActionEditPart) { + int index = action.getArguments().size(); + CompoundCommand cmd = getAddPinsCmd(action, Collections.singletonMap(index, property), preferredPinClass); + globalCmd.append(cmd); + } + } + if (!globalCmd.isEmpty() && globalCmd.canExecute()) { + globalCmd.execute(); + } + } + } + + /** + * Propose the user to navigate to the given element + * + * @param element + * element to navigate to + */ + protected void proposeNavigation(final NamedElement element) { + final String elementLabel = labelProvider.getText(element); + final String message = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UnauthorizedModificationRedirection, elementLabel); + SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() { + + @Override + protected Void openDialog() { + WarningAndLinkDialog dialog = new WarningAndLinkDialog(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UnauthorizedModificationTitle, message, element, elementLabel); + dialog.open(); + return null; + } + }; + opener.execute(); + } + + /** + * Ensure Pin modification is in accordance with associated Parameter + * + * @param pin + * modified pin (not a target pin) + * @param ctx + * validation context + * @return status + */ + protected IStatus handlePinModification(Pin pin, IValidationContext ctx) { + if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) { + if (testPinOrParameterOrPropertyFeature(ctx.getFeature())) { + NamedElement invoked = getInvokedObject(pin); + if (invoked != null) { + proposeNavigation(invoked); + return ctx.createFailureStatus(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure Parameter modification is reported on associated Pins + * + * @param parameter + * modified parameter + * @param ctx + * validation context + * @return status + */ + protected IStatus handleParameterModification(Parameter parameter, IValidationContext ctx) { + if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) { + if (testPinOrParameterOrPropertyFeature(ctx.getFeature())) { + // Update corresponding pins + CompoundCommand cmd = getUpdatePinsCmd(getPins(parameter), parameter.getType(), parameter.isOrdered(), parameter.isUnique(), parameter.getLower(), parameter.getLowerValue(), parameter.getUpper(), parameter.getUpperValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + if (askForValidation(getCallingActions(parameter.getOwner()))) { + cmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + } else if (UMLPackage.eINSTANCE.getParameter_Direction().equals(ctx.getFeature())) { + // Remove/Add corresponding pins with type in accordance to + // direction + for (Notification event : ctx.getAllEvents()) { + if (UMLPackage.eINSTANCE.getParameter_Direction().equals(event.getFeature()) || UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(event.getFeature())) { + return changePinsBecauseOfParameterDirection(parameter, event, ctx); + } + } + } else if (UMLPackage.eINSTANCE.getNamedElement_Name().equals(ctx.getFeature())) { + // Synchronize the pin name if not set yet + CompoundCommand cmd = getSetPinsNamesCmd(getPins(parameter), parameter.getName()); + if (!cmd.isEmpty() && cmd.canExecute()) { + if (askForValidation(getCallingActions(parameter.getOwner()))) { + cmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure Property modification is reported on associated Pins + * + * @param property + * modified property + * @param ctx + * validation context + * @return status + */ + protected IStatus handlePropertyModification(Property property, IValidationContext ctx) { + if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) { + if (testPinOrParameterOrPropertyFeature(ctx.getFeature())) { + // Update corresponding pins + CompoundCommand cmd = getUpdatePinsCmd(getPins(property), property.getType(), property.isOrdered(), property.isUnique(), property.getLower(), property.getLowerValue(), property.getUpper(), property.getUpperValue()); + if (!cmd.isEmpty() && cmd.canExecute()) { + if (askForValidation(getCallingActions(property.getOwner()))) { + cmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + } else if (UMLPackage.eINSTANCE.getNamedElement_Name().equals(ctx.getFeature())) { + // Synchronize the pin name if not set yet + CompoundCommand cmd = getSetPinsNamesCmd(getPins(property), property.getName()); + if (!cmd.isEmpty() && cmd.canExecute()) { + if (askForValidation(getCallingActions(property.getOwner()))) { + cmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Change the Pins because parameter's direction has changed + * + * @param parameter + * the modified parameter + * @param event + * the direction change event + * @param ctx + * validation context + * @return status + */ + protected IStatus changePinsBecauseOfParameterDirection(TypedElement parameter, Notification event, IValidationContext ctx) { + // constants used for type safety + List<Integer> emptyList = Collections.emptyList(); + Map<Integer, TypedElement> emptyMap = Collections.emptyMap(); + Object oldDir = event.getOldValue(); + Object newDir = event.getNewValue(); + int inIndex = getIndex(parameter, true); + int outIndex = getIndex(parameter, false); + CompoundCommand globalCmd = new CompoundCommand(); + List<InvocationAction> callingActions = getCallingActions(parameter.getOwner()); + if (ParameterDirectionKind.IN_LITERAL.equals(oldDir)) { + if (ParameterDirectionKind.OUT_LITERAL.equals(newDir) || ParameterDirectionKind.RETURN_LITERAL.equals(newDir)) { + // explore referencing actions to remove in and add out + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + CompoundCommand cmd = getRemovePinsCmd((CallAction) action, Collections.singletonList(inIndex), emptyList); + globalCmd.append(cmd); + cmd = getAddPinsCmd(action, emptyMap, Collections.singletonMap(outIndex, parameter), null); + globalCmd.append(cmd); + } + } + } else if (ParameterDirectionKind.INOUT_LITERAL.equals(newDir)) { + // explore referencing actions to add out + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + CompoundCommand cmd = getAddPinsCmd(action, emptyMap, Collections.singletonMap(outIndex, parameter), null); + globalCmd.append(cmd); + } + } + } + } else if (ParameterDirectionKind.OUT_LITERAL.equals(oldDir) || ParameterDirectionKind.RETURN_LITERAL.equals(oldDir)) { + if (ParameterDirectionKind.IN_LITERAL.equals(newDir)) { + // explore referencing actions to remove out and add in + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + CompoundCommand cmd = getRemovePinsCmd((CallAction) action, emptyList, Collections.singletonList(outIndex)); + globalCmd.append(cmd); + cmd = getAddPinsCmd(action, Collections.singletonMap(inIndex, parameter), emptyMap, null); + globalCmd.append(cmd); + } + } + } else if (ParameterDirectionKind.INOUT_LITERAL.equals(newDir)) { + // explore referencing actions to add in + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + CompoundCommand cmd = getAddPinsCmd(action, Collections.singletonMap(inIndex, parameter), emptyMap, null); + globalCmd.append(cmd); + } + } + } + } else if (ParameterDirectionKind.INOUT_LITERAL.equals(oldDir)) { + if (ParameterDirectionKind.IN_LITERAL.equals(newDir)) { + // explore referencing actions to remove out + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + CompoundCommand cmd = getRemovePinsCmd((CallAction) action, emptyList, Collections.singletonList(outIndex)); + globalCmd.append(cmd); + } + } + } else if (ParameterDirectionKind.OUT_LITERAL.equals(newDir) || ParameterDirectionKind.RETURN_LITERAL.equals(newDir)) { + // explore referencing actions to remove in + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + CompoundCommand cmd = getRemovePinsCmd((CallAction) action, Collections.singletonList(inIndex), emptyList); + globalCmd.append(cmd); + } + } + } + } + if (!globalCmd.isEmpty() && globalCmd.canExecute()) { + if (askForValidation(callingActions)) { + globalCmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Get the list of actions invoking this element + * + * @param element + * an Operation or a Behavior or a Signal + * @return list of InvocationAction + */ + protected static List<InvocationAction> getCallingActions(Element element) { + // explore referencing actions + Set<InvocationAction> callingActions = new HashSet<InvocationAction>(); + if (element instanceof Behavior || element instanceof Operation) { + Collection<Setting> references = CacheAdapter.getInstance().getNonNavigableInverseReferences(element); + for (Setting ref : references) { + EObject action = ref.getEObject(); + // parameter's owner is action's called Operation + boolean operationCase = UMLPackage.eINSTANCE.getCallOperationAction_Operation().equals(ref.getEStructuralFeature()); + // parameter's owner is action's called Behavior + boolean behaviorCase = UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior().equals(ref.getEStructuralFeature()); + if ((operationCase || behaviorCase) && action instanceof CallAction && action.eContainer() != null) { + callingActions.add((CallAction) action); + } + } + } else if (element instanceof Signal) { + Collection<Setting> references = CacheAdapter.getInstance().getNonNavigableInverseReferences(element); + for (Setting ref : references) { + EObject action = ref.getEObject(); + // parameter's owner is action's sent Signal + boolean signalCase = UMLPackage.eINSTANCE.getSendSignalAction_Signal().equals(ref.getEStructuralFeature()); + if (signalCase && action instanceof SendSignalAction && action.eContainer() != null) { + callingActions.add((SendSignalAction) action); + } + } + } + return new ArrayList<InvocationAction>(callingActions); + } + + /** + * Ensure CallOperationAction modification is reported on associated + * Operation + * + * @param action + * modified action + * @param ctx + * validation context + * @return status + */ + protected IStatus handleCallOperationActionModification(CallOperationAction action, IValidationContext ctx) { + if (testTransformPinCase(ctx)) { + return ctx.createSuccessStatus(); + } else if (testCustomModificationToValidPins(action, ctx)) { + return ctx.createSuccessStatus(); + } else if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) { + if (testActionFeature(ctx.getFeature()) && action.getOperation() != null) { + if (action.getOperation() != null) { + if (canCreateParameterFromCallAction(action)) { + Object pin = ctx.getFeatureNewValue(); + boolean parameterCreated = proposeParameterCreation(action.getOperation(), ((EObject) pin).eClass()); + if (parameterCreated) { + // remove the user-created value + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + Command cmd = RemoveCommand.create(editingdomain, ctx.getFeatureNewValue()); + cmd.execute(); + return ctx.createSuccessStatus(); + } + } else { + /* + * No modification of parameters is allowed from the + * CallOperationAction. This means we can not add Pins + */ + proposeNavigation(action.getOperation()); + } + return ctx.createFailureStatus(); + } + } + } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) { + if (testActionFeature(ctx.getFeature()) && action.getOperation() != null) { + /* + * Yet, no modification of parameters is allowed from the + * CallOperationAction. This means we can not remove Pins + */ + if (action.getOperation() != null) { + proposeNavigation(action.getOperation()); + return ctx.createFailureStatus(); + } + } + } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getCallOperationAction_Operation().equals(ctx.getFeature())) { + /* + * The operation changes, so must the pins + */ + CompoundCommand cmd = getResetPinsCmd(action); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + } + if (UMLPackage.eINSTANCE.getCallOperationAction_Target().equals(ctx.getFeature())) { + /* + * Try to remove or assign target pin. This must not be + * authorized. + */ + final String msg = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UndeleteablePinMessage, UMLPackage.eINSTANCE.getCallOperationAction_Target().getName()); + SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() { + + @Override + protected Void openDialog() { + MessageDialog.openWarning(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UndeleteablePinTitle, msg); + return null; + } + }; + opener.execute(); + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * @param node + * @param ctx + * @return + */ + protected boolean testCustomModificationToValidPins(ActivityNode node, IValidationContext ctx) { + // reflexive code to call each validation method matching the given object in : UMLValidationHelper.class + // the method call rach public and static method + IStatus status = null; + Class<? extends UMLValidationHelper> aClass = UMLValidationHelper.class; + Method[] methods = aClass.getDeclaredMethods(); + for (Method m : methods) { + if (Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers()) && m.getReturnType() == IStatus.class) { + if (m.isAnnotationPresent(PinAndParameterSynchronizeValidator.class) && m.getParameterTypes().length == 2) { + if (m.getParameterTypes()[0].isInstance(node)) { + try { + status = (IStatus) m.invoke(aClass, node, ctx); + if (status != null && !status.isOK()) { + break; + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } + } + } + } + } + return status == null || status.isOK(); + } + + /** + * Ensure CallBehaviorAction modification is reported on associated Behavior + * + * @param action + * modified action + * @param ctx + * validation context + * @return status + */ + protected IStatus handleCallBehaviorActionModification(CallBehaviorAction action, IValidationContext ctx) { + if (testTransformPinCase(ctx)) { + return ctx.createSuccessStatus(); + } else if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) { + if (testActionFeature(ctx.getFeature()) && action.getBehavior() != null) { + if (action.getBehavior() != null) { + if (canCreateParameterFromCallAction(action)) { + Object pin = ctx.getFeatureNewValue(); + boolean parameterCreated = proposeParameterCreation(action.getBehavior(), ((EObject) pin).eClass()); + if (parameterCreated) { + // remove the user-created value + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + Command cmd = RemoveCommand.create(editingdomain, ctx.getFeatureNewValue()); + cmd.execute(); + return ctx.createSuccessStatus(); + } + } else { + /* + * No modification of parameters is allowed from the + * CallBehaviorAction. This means we can not add Pins + */ + proposeNavigation(action.getBehavior()); + } + return ctx.createFailureStatus(); + } + } + } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) { + if (testActionFeature(ctx.getFeature()) && action.getBehavior() != null) { + /* + * Yet, no modification of parameters is allowed from the + * CallBehaviorAction. This means we can not remove Pins + */ + if (action.getBehavior() != null) { + proposeNavigation(action.getBehavior()); + return ctx.createFailureStatus(); + } + } + } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getCallBehaviorAction_Behavior().equals(ctx.getFeature())) { + /* + * The behavior changes, so must the pins + */ + CompoundCommand cmd = getResetPinsCmd(action); + if (action.getBehavior() != null) { + String behaviorName = action.getBehavior().getName(); + if (behaviorName != null && !"".equals(behaviorName)) { + // By the way, update the CallBehaviorAction name + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + cmd.append(SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getNamedElement_Name(), behaviorName)); + } + } + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Test if a parameter can be created from a call action, after appropriate + * warnings + * + * @param action + * the call action + * @return true if we can create a parameter + */ + protected boolean canCreateParameterFromCallAction(CallAction action) { + return true; + } + + /** + * Test if an attribute can be created from a send signal action, after + * appropriate warnings + * + * @param action + * the send signal action + * @return true if we can create an attribute + */ + protected boolean canCreateAttributesFromSendSignalAction(SendSignalAction action) { + return true; + } + + /** + * Ensure BroadcastSignalAction modification is reported on associated + * Signal + * + * @param action + * modified action + * @param ctx + * validation context + * @return status + */ + protected IStatus handleBroadcastSignalActionModification(BroadcastSignalAction action, IValidationContext ctx) { + if (testTransformPinCase(ctx)) { + return ctx.createSuccessStatus(); + } else if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) { + if (testActionFeature(ctx.getFeature()) && action.getSignal() != null) { + if (action.getSignal() != null) { + Object pin = ctx.getFeatureNewValue(); + boolean attributeCreated = proposeAttributeCreation(action.getSignal(), ((EObject) pin).eClass()); + if (attributeCreated) { + // remove the user-created value + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + Command cmd = RemoveCommand.create(editingdomain, ctx.getFeatureNewValue()); + cmd.execute(); + return ctx.createSuccessStatus(); + } + return ctx.createFailureStatus(); + } + } + } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) { + if (testActionFeature(ctx.getFeature()) && action.getSignal() != null) { + /* + * Yet, no modification of attributes is allowed from the + * BroadcastSignalAction. This means we can not remove Pins + */ + if (action.getSignal() != null) { + proposeNavigation(action.getSignal()); + return ctx.createFailureStatus(); + } + } + } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getBroadcastSignalAction_Signal().equals(ctx.getFeature())) { + /* + * The signal changes, so must the pins + */ + CompoundCommand cmd = getResetPinsCmd(action); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure SendSignalAction modification is reported on associated Signal + * + * @param action + * modified action + * @param ctx + * validation context + * @return status + */ + protected IStatus handleSendSignalActionModification(SendSignalAction action, IValidationContext ctx) { + if (testTransformPinCase(ctx)) { + return ctx.createSuccessStatus(); + } else if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) { + if (testActionFeature(ctx.getFeature()) && action.getSignal() != null) { + if (action.getSignal() != null) { + if (canCreateAttributesFromSendSignalAction(action)) { + Object pin = ctx.getFeatureNewValue(); + boolean attributeCreated = proposeAttributeCreation(action.getSignal(), ((EObject) pin).eClass()); + if (attributeCreated) { + // remove the user-created value + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + Command cmd = RemoveCommand.create(editingdomain, ctx.getFeatureNewValue()); + cmd.execute(); + return ctx.createSuccessStatus(); + } + } else { + /* + * No modification of attributes is allowed from the + * SendSignalAction. This means we can not add Pins + */ + proposeNavigation(action.getSignal()); + } + return ctx.createFailureStatus(); + } + } + } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) { + if (testActionFeature(ctx.getFeature()) && action.getSignal() != null) { + /* + * Yet, no modification of attributes is allowed from the + * SendSignalAction. This means we can not remove Pins + */ + if (action.getSignal() != null) { + proposeNavigation(action.getSignal()); + return ctx.createFailureStatus(); + } + } + } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getSendSignalAction_Signal().equals(ctx.getFeature())) { + /* + * The signal changes, so must the pins + */ + CompoundCommand cmd = getResetPinsCmd(action); + if (!cmd.isEmpty() && cmd.canExecute()) { + cmd.execute(); + } + } + if (UMLPackage.eINSTANCE.getSendSignalAction_Target().equals(ctx.getFeature())) { + /* + * Try to remove or assign target pin. This must not be + * authorized. + */ + final String msg = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UndeleteablePinMessage, UMLPackage.eINSTANCE.getSendSignalAction_Target().getName()); + SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() { + + @Override + protected Void openDialog() { + MessageDialog.openWarning(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UndeleteablePinTitle, msg); + return null; + } + }; + opener.execute(); + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure SendObjectAction modification is authorized + * + * @param action + * modified action + * @param ctx + * validation context + * @return status + */ + protected IStatus handleSendObjectActionModification(SendObjectAction action, IValidationContext ctx) { + if (testTransformPinCase(ctx)) { + return ctx.createSuccessStatus(); + } else if (EMFEventType.SET.equals(ctx.getEventType()) || EMFEventType.UNSET.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getSendObjectAction_Target().equals(ctx.getFeature())) { + /* + * Try to remove or assign target pin. This must not be + * authorized. + */ + final String msg = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UndeleteablePinMessage, UMLPackage.eINSTANCE.getSendObjectAction_Target().getName()); + SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() { + + @Override + protected Void openDialog() { + MessageDialog.openWarning(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UndeleteablePinTitle, msg); + return null; + } + }; + opener.execute(); + return ctx.createFailureStatus(); + } + if (UMLPackage.eINSTANCE.getSendObjectAction_Request().equals(ctx.getFeature())) { + /* + * Try to remove or assign target pin. This must not be + * authorized. + */ + final String msg = NLS.bind(CustomMessages.PinAndParameterSynchronizer_UndeleteablePinMessage, UMLPackage.eINSTANCE.getSendObjectAction_Request().getName()); + SafeDialogOpenerDuringValidation<Void> opener = new SafeDialogOpenerDuringValidation<Void>() { + + @Override + protected Void openDialog() { + MessageDialog.openWarning(new Shell(Display.getDefault()), CustomMessages.PinAndParameterSynchronizer_UndeleteablePinTitle, msg); + return null; + } + }; + opener.execute(); + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Test whether the executing operation is a transform into on a pin + * + * @param ctx + * the validation context + * @return true if we are executing a transform into on a pin + */ + protected boolean testTransformPinCase(IValidationContext ctx) { + List<Notification> events = ctx.getAllEvents(); + Object removed = null; + Object added = null; + if (events.size() == 1) { + Notification set = events.get(0); + if (Notification.SET == set.getEventType()) { + removed = set.getOldValue(); + added = set.getNewValue(); + } + } else if (events.size() == 2) { + Notification remove = events.get(0); + Notification add = events.get(1); + if (Notification.REMOVE == remove.getEventType() && Notification.ADD == add.getEventType()) { + if (remove.getPosition() == add.getPosition() && add.getFeature().equals(remove.getFeature())) { + removed = remove.getOldValue(); + added = add.getNewValue(); + } + } else if (Notification.REMOVE_MANY == remove.getEventType() && Notification.ADD_MANY == add.getEventType()) { + if (Notification.NO_INDEX == remove.getPosition() && add.getFeature().equals(remove.getFeature())) { + if (remove.getOldValue() instanceof List<?> && add.getNewValue() instanceof List<?>) { + ArrayList<Object> removeList = new ArrayList<Object>((List<?>) remove.getOldValue()); + removeList.removeAll((List<?>) add.getNewValue()); + ArrayList<Object> addList = new ArrayList<Object>((List<?>) add.getNewValue()); + addList.removeAll((List<?>) remove.getOldValue()); + if (removeList.size() == 1 && addList.size() == 1) { + removed = removeList.get(0); + added = addList.get(0); + } + } + } + } + } + // check that replacing pin object is similar before concluding a + // transform into + if (removed instanceof Pin && added instanceof Pin) { + Pin removedPin = (Pin) removed; + Pin addedPin = (Pin) added; + boolean similars = true; + // test name + similars &= removedPin.getName() == null || removedPin.getName().equals(addedPin.getName()); + // test type + similars &= EcoreUtil.equals(removedPin.getType(), addedPin.getType()); + // test is ordered + similars &= removedPin.isOrdered() == addedPin.isOrdered(); + // test multiplicity : is unique + similars &= removedPin.isUnique() == addedPin.isUnique(); + // test multiplicity : lower value + similars &= EcoreUtil.equals(removedPin.getLowerValue(), addedPin.getLowerValue()); + // test multiplicity : upper value + similars &= EcoreUtil.equals(removedPin.getUpperValue(), addedPin.getUpperValue()); + return similars; + } + return false; + } + + /** + * Ensure Operation modification is reported on associated actions + * + * @param operation + * modified operation + * @param ctx + * validation context + * @return status + */ + protected IStatus handleOperationModification(Operation operation, IValidationContext ctx) { + if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(ctx.getFeature())) { + return handleParametersAdded(operation, ctx); + } + } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(ctx.getFeature())) { + return handleParametersRemoved(operation, ctx); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure Behavior modification is reported on associated actions + * + * @param behavior + * modified behavior + * @param ctx + * validation context + * @return status + */ + protected IStatus handleBehaviorModification(Behavior behavior, IValidationContext ctx) { + if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getBehavior_OwnedParameter().equals(ctx.getFeature())) { + return handleParametersAdded(behavior, ctx); + } + } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getBehavior_OwnedParameter().equals(ctx.getFeature())) { + return handleParametersRemoved(behavior, ctx); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure Signal modification is reported on associated actions + * + * @param signal + * modified signal + * @param ctx + * validation context + * @return status + */ + protected IStatus handleSignalModification(Signal signal, IValidationContext ctx) { + if (EMFEventType.ADD.equals(ctx.getEventType()) || EMFEventType.ADD_MANY.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getSignal_OwnedAttribute().equals(ctx.getFeature())) { + return handleAttributesAdded(signal, ctx); + } + } else if (EMFEventType.REMOVE.equals(ctx.getEventType()) || EMFEventType.REMOVE_MANY.equals(ctx.getEventType())) { + if (UMLPackage.eINSTANCE.getSignal_OwnedAttribute().equals(ctx.getFeature())) { + return handleAttributesRemoved(signal, ctx); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure Pins corresponding to parameters are removed + * + * @param element + * modified operation or behavior + * @param ctx + * validation context + * @return status + */ + protected IStatus handleParametersRemoved(NamedElement element, IValidationContext ctx) { + // construct the list of removed indexes and their direction + Map<Integer, ParameterDirectionKind> removedParameterIndexes = new HashMap<Integer, ParameterDirectionKind>(); + for (Notification event : ctx.getAllEvents()) { + if (UMLPackage.eINSTANCE.getBehavior_OwnedParameter().equals(event.getFeature()) || UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(event.getFeature())) { + Object removedValue = event.getOldValue(); + if (removedValue instanceof Parameter) { + // handle parameter direction + ParameterDirectionKind dir = ((Parameter) removedValue).getDirection(); + removedParameterIndexes.put(event.getPosition(), dir); + } else if (removedValue instanceof List<?>) { + List<?> col = (List<?>) removedValue; + if (!col.isEmpty()) { + for (int i = 0; i < col.size(); i++) { + Object object = col.get(i); + if (object instanceof Parameter) { + removedParameterIndexes.put(i, ((Parameter) object).getDirection()); + } + } + } + } + } + } + List<Parameter> newParameters = Collections.emptyList(); + if (element instanceof Behavior) { + newParameters = ((Behavior) element).getOwnedParameters(); + } else if (element instanceof Operation) { + newParameters = ((Operation) element).getOwnedParameters(); + } + List<Integer> removedInputPinIndexes = new LinkedList<Integer>(); + List<Integer> removedOutputPinIndexes = new LinkedList<Integer>(); + Iterator<Parameter> parametersIterator = newParameters.iterator(); + // iterate on the virtual list of old parameters + // (correspondingParameterIndex) to deduce + // pins indexes + int correspondingParameterIndex = 0; + int correspondingInputPinIndex = 0; + int correspondingOutputPinIndex = 0; + while (removedParameterIndexes.containsKey(correspondingParameterIndex) || parametersIterator.hasNext()) { + if (removedParameterIndexes.containsKey(correspondingParameterIndex)) { + // parameter removed, pin(s) removed + switch (removedParameterIndexes.get(correspondingParameterIndex)) { + case IN_LITERAL: + removedInputPinIndexes.add(correspondingInputPinIndex); + correspondingInputPinIndex++; + break; + case OUT_LITERAL: + case RETURN_LITERAL: + removedOutputPinIndexes.add(correspondingOutputPinIndex); + correspondingOutputPinIndex++; + break; + case INOUT_LITERAL: + // in-out parameter has two pins + removedInputPinIndexes.add(correspondingInputPinIndex); + correspondingInputPinIndex++; + removedOutputPinIndexes.add(correspondingOutputPinIndex); + correspondingOutputPinIndex++; + break; + } + } else { + // parameter not removed, pin(s) not removed + Parameter nextParam = parametersIterator.next(); + switch (nextParam.getDirection()) { + case IN_LITERAL: + correspondingInputPinIndex++; + break; + case OUT_LITERAL: + case RETURN_LITERAL: + correspondingOutputPinIndex++; + break; + case INOUT_LITERAL: + // in-out parameter has two pins + correspondingInputPinIndex++; + correspondingOutputPinIndex++; + break; + } + } + // explore next parameter + correspondingParameterIndex++; + } + CompoundCommand globalCmd = new CompoundCommand(); + // explore referencing actions + List<InvocationAction> callingActions = getCallingActions(element); + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + CompoundCommand cmd = getRemovePinsCmd((CallAction) action, removedInputPinIndexes, removedOutputPinIndexes); + globalCmd.append(cmd); + } + } + if (!globalCmd.isEmpty() && globalCmd.canExecute()) { + if (askForValidation(callingActions)) { + globalCmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure Pins corresponding to parameters are added + * + * @param element + * modified operation or behavior + * @param ctx + * validation context + * @return status + */ + protected IStatus handleParametersAdded(NamedElement element, IValidationContext ctx) { + // construct the list of added indexes and their direction + List<Parameter> addedParameters = new LinkedList<Parameter>(); + for (Notification event : ctx.getAllEvents()) { + if (UMLPackage.eINSTANCE.getBehavior_OwnedParameter().equals(event.getFeature()) || UMLPackage.eINSTANCE.getBehavioralFeature_OwnedParameter().equals(event.getFeature())) { + Object addedValue = event.getNewValue(); + if (addedValue instanceof Parameter) { + addedParameters.add((Parameter) addedValue); + } else if (addedValue instanceof List<?>) { + List<?> col = (List<?>) addedValue; + if (!col.isEmpty()) { + for (int i = 0; i < col.size(); i++) { + Object object = col.get(i); + if (object instanceof Parameter) { + addedParameters.add((Parameter) object); + } + } + } + } + } + } + List<Parameter> newParameters = Collections.emptyList(); + if (element instanceof Behavior) { + newParameters = ((Behavior) element).getOwnedParameters(); + } else if (element instanceof Operation) { + newParameters = ((Operation) element).getOwnedParameters(); + } + Map<Integer, TypedElement> addedInputPinMap = new HashMap<Integer, TypedElement>(); + Map<Integer, TypedElement> addedOutputPinMap = new HashMap<Integer, TypedElement>(); + // iterate on the list of new parameters to deduce pins indexes + int correspondingInputPinIndex = 0; + int correspondingOutputPinIndex = 0; + for (Parameter param : newParameters) { + if (addedParameters.contains(param)) { + // parameter added, pin(s) to add + switch (param.getDirection()) { + case IN_LITERAL: + addedInputPinMap.put(correspondingInputPinIndex, param); + correspondingInputPinIndex++; + break; + case OUT_LITERAL: + case RETURN_LITERAL: + addedOutputPinMap.put(correspondingOutputPinIndex, param); + correspondingOutputPinIndex++; + break; + case INOUT_LITERAL: + // in-out parameter has two pins + addedInputPinMap.put(correspondingInputPinIndex, param); + correspondingInputPinIndex++; + addedOutputPinMap.put(correspondingOutputPinIndex, param); + correspondingOutputPinIndex++; + break; + } + } else { + // parameter not added, pin already exists + switch (param.getDirection()) { + case IN_LITERAL: + correspondingInputPinIndex++; + break; + case OUT_LITERAL: + case RETURN_LITERAL: + correspondingOutputPinIndex++; + break; + case INOUT_LITERAL: + // in-out parameter has two pins + correspondingInputPinIndex++; + correspondingOutputPinIndex++; + break; + } + } + // explore next parameter + } + CompoundCommand globalCmd = new CompoundCommand(); + // explore referencing actions + List<InvocationAction> callingActions = getCallingActions(element); + for (InvocationAction action : callingActions) { + if (action instanceof CallAction) { + CompoundCommand cmd = getAddPinsCmd(action, addedInputPinMap, addedOutputPinMap, null); + globalCmd.append(cmd); + } + } + if (!globalCmd.isEmpty() && globalCmd.canExecute()) { + if (askForValidation(callingActions)) { + globalCmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure Pins corresponding to parameters are removed + * + * @param element + * modified signal + * @param ctx + * validation context + * @return status + */ + protected IStatus handleAttributesRemoved(Signal element, IValidationContext ctx) { + // construct the list of removed indexes and their direction + Set<Integer> removedAttributeIndexes = new HashSet<Integer>(); + for (Notification event : ctx.getAllEvents()) { + if (UMLPackage.eINSTANCE.getSignal_OwnedAttribute().equals(event.getFeature())) { + Object removedValue = event.getOldValue(); + if (removedValue instanceof Property) { + removedAttributeIndexes.add(event.getPosition()); + } else if (removedValue instanceof List<?>) { + List<?> col = (List<?>) removedValue; + if (!col.isEmpty()) { + for (int i = 0; i < col.size(); i++) { + Object object = col.get(i); + if (object instanceof Property) { + removedAttributeIndexes.add(i); + } + } + } + } + } + } + // deduce pins indexes from old attributes indexes + List<Integer> removedInputPinIndexes = new LinkedList<Integer>(removedAttributeIndexes); + CompoundCommand globalCmd = new CompoundCommand(); + // explore referencing actions + List<InvocationAction> callingActions = getCallingActions(element); + for (InvocationAction action : callingActions) { + if (action instanceof SendSignalAction) { + CompoundCommand cmd = getRemovePinsCmd((SendSignalAction) action, removedInputPinIndexes); + globalCmd.append(cmd); + } + } + if (!globalCmd.isEmpty() && globalCmd.canExecute()) { + if (askForValidation(callingActions)) { + globalCmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Ensure Pins corresponding to attributes are added + * + * @param element + * modified signal + * @param ctx + * validation context + * @return status + */ + protected IStatus handleAttributesAdded(Signal element, IValidationContext ctx) { + // construct the list of added indexes and their direction + List<Property> addedAttributes = new LinkedList<Property>(); + for (Notification event : ctx.getAllEvents()) { + if (UMLPackage.eINSTANCE.getSignal_OwnedAttribute().equals(event.getFeature())) { + Object addedValue = event.getNewValue(); + if (addedValue instanceof Property) { + addedAttributes.add((Property) addedValue); + } else if (addedValue instanceof List<?>) { + List<?> col = (List<?>) addedValue; + if (!col.isEmpty()) { + for (int i = 0; i < col.size(); i++) { + Object object = col.get(i); + if (object instanceof Property) { + addedAttributes.add((Property) object); + } + } + } + } + } + } + List<Property> newAttributes = Collections.emptyList(); + if (element instanceof Signal) { + newAttributes = element.getOwnedAttributes(); + } + Map<Integer, Property> addedInputPinMap = new HashMap<Integer, Property>(); + // iterate on the list of added attributes to deduce pins indexes + for (Property param : addedAttributes) { + if (newAttributes.contains(param)) { + addedInputPinMap.put(newAttributes.indexOf(param), param); + } + } + CompoundCommand globalCmd = new CompoundCommand(); + // explore referencing actions + List<InvocationAction> callingActions = getCallingActions(element); + for (InvocationAction action : callingActions) { + if (action instanceof SendSignalAction) { + CompoundCommand cmd = getAddPinsCmd(action, addedInputPinMap, null); + globalCmd.append(cmd); + } + } + if (!globalCmd.isEmpty() && globalCmd.canExecute()) { + if (askForValidation(callingActions)) { + globalCmd.execute(); + } else { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Get the command to update type of target input pins referring the + * operation + * + * @param operation + * the operation which parent type has changed + * @return the command + */ + protected CompoundCommand getUpdateTargetPinsType(Operation operation) { + CompoundCommand globalCmd = new CompoundCommand(); + // get operation parent type + Type type = null; + Element owner = operation.getOwner(); + if (owner instanceof Type) { + type = (Type) owner; + } + if (type != null) {// Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + // explore referencing actions + for (InvocationAction action : getCallingActions(operation)) {// operation + // is + // action's + // called + // Operation + if (action instanceof CallOperationAction) { + InputPin targetPin = ((CallOperationAction) action).getTarget(); + if (targetPin != null) { + Command cmd = SetCommand.create(editingdomain, targetPin, UMLPackage.eINSTANCE.getTypedElement_Type(), type); + globalCmd.append(cmd); + } + } + } + } + return globalCmd; + } + + /** + * Get the command to remove pins linked with parameter at the given indexes + * + * @param action + * the CallOperationAction or CallBehaviorAction (no effect + * otherwise) + * @param removedInputPinsIndexes + * the indexes of input pins to remove (except target) + * @param removedOutputPinsIndexes + * the indexes of output pins to remove + * @return the command to remove corresponding Pins + */ + protected CompoundCommand getRemovePinsCmd(CallAction action, List<Integer> removedInputPinsIndexes, List<Integer> removedOutputPinsIndexes) { + CompoundCommand globalCmd = new CompoundCommand(); + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + if (action instanceof CallBehaviorAction || action instanceof CallOperationAction) { + ArrayList<InputPin> removedIn = new ArrayList<InputPin>(removedInputPinsIndexes.size()); + for (int i : removedInputPinsIndexes) { + if (i < action.getArguments().size()) { + removedIn.add(action.getArguments().get(i)); + } + } + if (!removedIn.isEmpty()) { + Command cmd = RemoveCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getInvocationAction_Argument(), removedIn); + globalCmd.append(cmd); + } + ArrayList<OutputPin> removedOut = new ArrayList<OutputPin>(removedInputPinsIndexes.size()); + for (int i : removedOutputPinsIndexes) { + if (i < action.getResults().size()) { + removedOut.add(action.getResults().get(i)); + } + } + if (!removedOut.isEmpty()) { + Command cmd = RemoveCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getCallAction_Result(), removedOut); + globalCmd.append(cmd); + } + } + return globalCmd; + } + + /** + * Get the command to remove pins linked with attribute at the given indexes + * + * @param action + * the SendSignalAction + * @param removedInputPinsIndexes + * the indexes of input pins to remove (except target) + * @return the command to remove corresponding Pins + */ + protected CompoundCommand getRemovePinsCmd(SendSignalAction action, List<Integer> removedInputPinsIndexes) { + CompoundCommand globalCmd = new CompoundCommand(); + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + if (action instanceof SendSignalAction) { + ArrayList<InputPin> removedIn = new ArrayList<InputPin>(removedInputPinsIndexes.size()); + for (int i : removedInputPinsIndexes) { + if (i < action.getArguments().size()) { + removedIn.add(action.getArguments().get(i)); + } + } + if (!removedIn.isEmpty()) { + Command cmd = RemoveCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getInvocationAction_Argument(), removedIn); + globalCmd.append(cmd); + } + } + return globalCmd; + } + + /** + * Get the command to add pins linked with parameter at the given indexes + * + * @param invocationAction + * the CallBehaviorAction or CallOperationAction (no effect + * otherwise) + * @param addedInputPinMap + * the indexes of input pins to add and parameters to copy + * @param addedOutputPinMap + * the indexes of output pins to add and parameters to copy + * @param preferredPinClass + * the EClass to use to create a new pin whenever possible (or + * null) + * @return the command to add corresponding Pins + */ + protected static CompoundCommand getAddPinsCmd(InvocationAction invocationAction, Map<Integer, TypedElement> addedInputPinMap, Map<Integer, TypedElement> addedOutputPinMap, EClass preferredPinClass) { + CompoundCommand globalCmd = new CompoundCommand(); + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + if (invocationAction instanceof CallBehaviorAction || invocationAction instanceof CallOperationAction || invocationAction instanceof SendSignalAction || invocationAction instanceof BroadcastSignalAction) { + /* + * An element can not be added at an index bigger than the size. + * Hence, add commands must be sorted according to the decreasing + * index and the index must be adapted taking in account elements + * that will be added. We use a bucket sort on indexes of both maps. + */ + int nextKey = addedInputPinMap.size() + invocationAction.getArguments().size(); + int numberOfPinsToAdd = addedInputPinMap.size(); + while (numberOfPinsToAdd > 0) { + if (addedInputPinMap.containsKey(nextKey)) { + numberOfPinsToAdd--; + InputPin pin = createInputPin(addedInputPinMap.get(nextKey), preferredPinClass); + // index at which pin is added must take in account other + // pins added after + int addIndex = nextKey - numberOfPinsToAdd; + Command cmd = AddCommand.create(editingdomain, invocationAction, UMLPackage.eINSTANCE.getInvocationAction_Argument(), pin, addIndex); + LinkPinToParameter link = new LinkPinToParameter(pin, addedInputPinMap.get(nextKey)); + CreatePinToParameterLinkEAnnotation linkCommand = new CreatePinToParameterLinkEAnnotation(EditorUtils.getTransactionalEditingDomain(), link); + globalCmd.append(cmd); + if (linkCommand != null && linkCommand.canExecute()) { + globalCmd.append(linkCommand); + } + } + nextKey--; + } + if (invocationAction instanceof CallAction) { + CallAction callAction = (CallAction) invocationAction; + nextKey = addedOutputPinMap.size() + callAction.getResults().size(); + numberOfPinsToAdd = addedOutputPinMap.size(); + while (numberOfPinsToAdd > 0) { + if (addedOutputPinMap.containsKey(nextKey)) { + numberOfPinsToAdd--; + OutputPin pin = createOutputPin(addedOutputPinMap.get(nextKey)); + // index at which pin is added must take in account other + // pins added after + int addIndex = nextKey - numberOfPinsToAdd; + Command cmd = AddCommand.create(editingdomain, callAction, UMLPackage.eINSTANCE.getCallAction_Result(), pin, addIndex); + globalCmd.append(cmd); + LinkPinToParameter link = new LinkPinToParameter(pin, addedOutputPinMap.get(nextKey)); + CreatePinToParameterLinkEAnnotation linkCommand = new CreatePinToParameterLinkEAnnotation(EditorUtils.getTransactionalEditingDomain(), link); + if (linkCommand != null) { + globalCmd.append(linkCommand); + } + } + nextKey--; + } + } + } + return globalCmd; + } + + /** + * Get the command to add pins linked with properties at the given indexes + * + * @param action + * the SendSignalAction + * @param addedInputPinMap + * the indexes of input pins to add and properties to copy + * @param preferredPinClass + * the EClass to use to create a new pin whenever possible (or + * null) + * @return the command to add corresponding Pins + */ + public static CompoundCommand getAddPinsCmd(InvocationAction action, Map<Integer, Property> addedInputPinMap, EClass preferredPinClass) { + CompoundCommand globalCmd = new CompoundCommand(); + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + /* + * An element can not be added at an index bigger than the size. Hence, + * add commands must be sorted according to the decreasing index and the + * index must be adapted taking in account elements that will be added. + * We use a bucket sort on indexes of both maps. + */ + int nextKey = addedInputPinMap.size() + action.getArguments().size(); + int numberOfPinsToAdd = addedInputPinMap.size(); + while (numberOfPinsToAdd > 0) { + if (addedInputPinMap.containsKey(nextKey)) { + numberOfPinsToAdd--; + InputPin pin = createInputPin(addedInputPinMap.get(nextKey), preferredPinClass); + // index at which pin is added must take in account other pins + // added after + int addIndex = nextKey - numberOfPinsToAdd; + Command cmd = AddCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getInvocationAction_Argument(), pin, addIndex); + globalCmd.append(cmd); + LinkPinToParameter link = new LinkPinToParameter(pin, addedInputPinMap.get(nextKey)); + CreatePinToParameterLinkEAnnotation linkCommand = new CreatePinToParameterLinkEAnnotation(WorkspaceEditingDomainFactory.INSTANCE.getEditingDomain(action.eResource().getResourceSet()), link); + if (linkCommand != null && linkCommand.canExecute()) { + globalCmd.append(linkCommand); + } + } + nextKey--; + } + return globalCmd; + } + + /** + * Create an output pin with valued copied from the parameter + * + * @param typedElement + * the reference parameter + */ + protected static OutputPin createOutputPin(TypedElement typedElement) { + OutputPin pin = UMLFactory.eINSTANCE.createOutputPin(); + assignUpperBound(pin); + // Initialize name + pin.setName(typedElement.getName()); + // Synchronize type + pin.setType(typedElement.getType()); + if (typedElement instanceof Property) { + Property property = (Property) typedElement; + // Synchronize is ordered + pin.setIsOrdered(property.isOrdered()); + // Synchronize mutliplicity : is unique + pin.setIsUnique(property.isUnique()); + // Synchronize mutliplicity : lower value + ValueSpecification lowerValue = property.getLowerValue(); + if (lowerValue != null) { + // use a copy command for new value + Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(lowerValue)); + copy.execute(); + Collection<?> result = copy.getResult(); + Object valueToAffect = null; + if (!result.isEmpty()) { + valueToAffect = result.iterator().next(); + } + if (valueToAffect instanceof ValueSpecification) { + pin.setLowerValue((ValueSpecification) valueToAffect); + } + } + // Synchronize mutliplicity : upper value + ValueSpecification upperValue = property.getUpperValue(); + if (upperValue != null) { + // use a copy command for new value + Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(upperValue)); + copy.execute(); + Collection<?> result = copy.getResult(); + Object valueToAffect = null; + if (!result.isEmpty()) { + valueToAffect = result.iterator().next(); + } + if (valueToAffect instanceof ValueSpecification) { + pin.setUpperValue((ValueSpecification) valueToAffect); + } + } + } + return pin; + } + + /** + * Create a target input pin, eventually from a given operation + * + * @param operation + * the invoked operation or null + */ + protected static InputPin createTargetPin(Operation operation) { + InputPin pin = UMLFactory.eINSTANCE.createInputPin(); + assignUpperBound(pin); + if (operation != null) { + Element owningType = operation.getOwner(); + if (owningType instanceof Type) { + pin.setType((Type) owningType); + } + } + pin.setName(TARGET_PIN_INITIALIZATION_NAME); + return pin; + } + + /** + * Create a result input pin, eventually from a given operation + * + * @param classifier + * the to set the output type + */ + protected OutputPin createResultPin(Classifier classifier) { + OutputPin pin = UMLFactory.eINSTANCE.createOutputPin(); + assignUpperBound(pin); + if (classifier != null) { + pin.setType(classifier); + } + pin.setName(RESULT_PIN_INITIALIZATION_NAME); + return pin; + } + + /** + * Create a result input pin, eventually from a given operation + * + * @param var + * the to set the output type + */ + protected OutputPin createResultPin(Variable var) { + OutputPin pin = UMLFactory.eINSTANCE.createOutputPin(); + assignUpperBound(pin); + if (var != null) { + pin.setType(var.getType()); + } + pin.setName(RESULT_IN_READ_VARIABLE_ACTION); + return pin; + } + + /** + * Create a request input pin + * + * @param operation + * the invoked operation or null + */ + public static InputPin createRequestPin() { + InputPin pin = UMLFactory.eINSTANCE.createInputPin(); + assignUpperBound(pin); + pin.setName(REQUEST_PIN_INITIALIZATION_NAME); + return pin; + } + + /** + * Create an input pin with valued copied from the property + * + * @param typedElement + * the reference property + * @param preferredPinClass + * the EClass to use to create a new pin whenever possible (or + * null) + */ + public static InputPin createInputPin(TypedElement typedElement, EClass preferredPinClass) { + InputPin pin; + if (UMLPackage.eINSTANCE.getValuePin().equals(preferredPinClass)) { + pin = UMLFactory.eINSTANCE.createValuePin(); + } else if (UMLPackage.eINSTANCE.getActionInputPin().equals(preferredPinClass)) { + pin = UMLFactory.eINSTANCE.createActionInputPin(); + } else { + pin = UMLFactory.eINSTANCE.createInputPin(); + } + assignUpperBound(pin); + // Initialize name + pin.setName(typedElement.getName()); + // Synchronize type + pin.setType(typedElement.getType()); + if (pin instanceof Property) { + Property property = (Property) pin; + // Synchronize is ordered + pin.setIsOrdered(property.isOrdered()); + // Synchronize multiplicity : is unique + pin.setIsUnique(property.isUnique()); + // Synchronize multiplicity : lower value + ValueSpecification lowerValue = property.getLowerValue(); + if (lowerValue != null) { + // use a copy command for new value + Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(lowerValue)); + copy.execute(); + Collection<?> result = copy.getResult(); + Object valueToAffect = null; + if (!result.isEmpty()) { + valueToAffect = result.iterator().next(); + } + if (valueToAffect instanceof ValueSpecification) { + pin.setLowerValue((ValueSpecification) valueToAffect); + } + } + // Synchronize multiplicity : upper value + ValueSpecification upperValue = property.getUpperValue(); + if (upperValue != null) { + // use a copy command for new value + Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(upperValue)); + copy.execute(); + Collection<?> result = copy.getResult(); + Object valueToAffect = null; + if (!result.isEmpty()) { + valueToAffect = result.iterator().next(); + } + if (valueToAffect instanceof ValueSpecification) { + pin.setUpperValue((ValueSpecification) valueToAffect); + } + } + } + return pin; + } + + /** + * Create an input pin with valued copied from the parameter + * + * @param parameter + * the reference parameter + * @param preferredPinClass + * the EClass to use to create a new pin whenever possible (or + * null) + */ + protected static InputPin createInputPin(Parameter parameter, EClass preferredPinClass) { + InputPin pin; + if (UMLPackage.eINSTANCE.getValuePin().equals(preferredPinClass)) { + pin = UMLFactory.eINSTANCE.createValuePin(); + } else if (UMLPackage.eINSTANCE.getActionInputPin().equals(preferredPinClass)) { + pin = UMLFactory.eINSTANCE.createActionInputPin(); + } else { + pin = UMLFactory.eINSTANCE.createInputPin(); + } + assignUpperBound(pin); + // Initialize name + pin.setName(parameter.getName()); + // Synchronize type + pin.setType(parameter.getType()); + // Synchronize is ordered + pin.setIsOrdered(parameter.isOrdered()); + // Synchronize multiplicity : is unique + pin.setIsUnique(parameter.isUnique()); + // Synchronize multiplicity : lower value + ValueSpecification lowerValue = parameter.getLowerValue(); + if (lowerValue != null) { + // use a copy command for new value + Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(lowerValue)); + copy.execute(); + Collection<?> result = copy.getResult(); + Object valueToAffect = null; + if (!result.isEmpty()) { + valueToAffect = result.iterator().next(); + } + if (valueToAffect instanceof ValueSpecification) { + pin.setLowerValue((ValueSpecification) valueToAffect); + } + } + // Synchronize multiplicity : upper value + ValueSpecification upperValue = parameter.getUpperValue(); + if (upperValue != null) { + // use a copy command for new value + Command copy = CopyCommand.create(EditorUtils.getTransactionalEditingDomain(), Collections.singleton(upperValue)); + copy.execute(); + Collection<?> result = copy.getResult(); + Object valueToAffect = null; + if (!result.isEmpty()) { + valueToAffect = result.iterator().next(); + } + if (valueToAffect instanceof ValueSpecification) { + pin.setUpperValue((ValueSpecification) valueToAffect); + } + } + return pin; + } + + /** + * Get the command to reset all pins of the action. + * + * @param action + * action to reinitialize pins (AddStructuralFeatureValueAction) + * @return command + */ + protected CompoundCommand getResetPinsCmd(AddStructuralFeatureValueAction action) { + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + CompoundCommand globalCmd = new CompoundCommand(); + if (action.getValue() == null) { + InputPin valuePin = createValuePinInAddStructuralFeatureAction(action); + Command cmdValuePin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getWriteStructuralFeatureAction_Value(), valuePin); + globalCmd.append(cmdValuePin); + } + if (action.getObject() == null) { + InputPin objectPin = createObjectPinInStructuralFeatureAction(action); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getStructuralFeatureAction_Object(), objectPin); + globalCmd.append(cmd); + } + if (action.getResult() == null) { + OutputPin resultPin = createResultPinInStructuralAction(action); + Command cmdResultPin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getWriteStructuralFeatureAction_Result(), resultPin); + globalCmd.append(cmdResultPin); + } + return globalCmd; + } + + /** + * Get the command to reset all pins of the action. + * + * @param action + * action to reinitialize pins (ReadVariableAction) + * @return command + */ + // Get the editing domain + protected CompoundCommand getResetPinsCmd(ReadVariableAction action) { + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + CompoundCommand globalCmd = new CompoundCommand(); + if (action.getResult() == null) { + OutputPin resultPin = createResultPin(action.getVariable()); + Command cmdResultPin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getReadVariableAction_Result(), resultPin); + globalCmd.append(cmdResultPin); + } + return globalCmd; + } + + // /** + // * Get the command to reset all pins of the action. + // * + // * @param action + // * action to reinitialize pins (BroadcastSignalAction) + // * @return command + // */ + // protected CompoundCommand getResetPinsCmd(BroadcastSignalAction action) { + // // Get the editing domain + // TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + // CompoundCommand globalCmd = new CompoundCommand(); + // if(action.getSignal() != null) { + // if(action.getArguments().isEmpty()) { + // EList<Property> properties = action.getSignal().getAllAttributes(); + // for(Property argument : properties) { + // InputPin argPin = UMLFactory.eINSTANCE.createInputPin(); + // assignUpperBound(argPin); + // argPin.setName(argument.getName()); + // argPin.setType(argument.getType()); + // Command cmdArg = AddCommand.create(editingdomain, action, UMLPackage.Literals.INVOCATION_ACTION__ARGUMENT, Arrays.asList(argPin)); + // globalCmd.append(cmdArg); + // } + // } + // } + // return globalCmd; + // } + /** + * Get the command to reset all pins of the action. + * + * @param action + * action to reinitialize pins (AddVariableValueAction) + * @return command + */ + protected CompoundCommand getResetPinsCmd(AddVariableValueAction action) { + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + CompoundCommand globalCmd = new CompoundCommand(); + if (action.getValue() == null) { + InputPin valuePin = createValuePinInAddVariableValueAction(action.getVariable()); + Command cmdValuePin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getWriteVariableAction_Value(), valuePin); + globalCmd.append(cmdValuePin); + } + if (action.getInsertAt() == null) { + InputPin insertAtPin = UMLFactory.eINSTANCE.createInputPin(); + assignUpperBound(insertAtPin); + insertAtPin.setName(INSERT_AT_IN_ADD_VARIABLE_VALUE_ACTION); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getAddVariableValueAction_InsertAt(), insertAtPin); + globalCmd.append(cmd); + } + return globalCmd; + } + + /** + * Get the command to reset all pins of the action. + * + * @param action + * action to reinitialize pins (AddStructuralFeatureValueAction) + * @return command + */ + public static CompoundCommand getResetPinsCmd(DestroyObjectAction action) { + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + CompoundCommand globalCmd = new CompoundCommand(); + if (action.getTarget() == null) { + InputPin targetPin = UMLFactory.eINSTANCE.createInputPin(); + assignUpperBound(targetPin); + targetPin.setName(TARGET_IN_DESTROY_OBJECT_ACTION); + Command cmdTargetPin = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getDestroyObjectAction_Target(), targetPin); + globalCmd.append(cmdTargetPin); + } + return globalCmd; + } + + /** + * Create a Pin value for a Structural feature action + * + * @param action + * @return + */ + public static InputPin createValuePinInAddStructuralFeatureAction(StructuralFeatureAction action) { + InputPin pin = UMLFactory.eINSTANCE.createInputPin(); + assignUpperBound(pin); + if (action != null) { + StructuralFeature feature = action.getStructuralFeature(); + if (feature != null && feature.getType() != null) { + Type owningType = feature.getType(); + if (owningType instanceof Type) { + pin.setType(owningType); + } + } + } + pin.setName(VALUE_PIN_IN_STRUCTURAL_FEATURE_VALUE_ACTION); + return pin; + } + + /** + * Create a Pin value for a Structural feature action + * + * @param action + * @return + */ + protected InputPin createValuePinInAddVariableValueAction(Variable var) { + InputPin pin = UMLFactory.eINSTANCE.createInputPin(); + assignUpperBound(pin); + if (var != null) { + Type owningType = var.getType(); + if (owningType instanceof Type) { + pin.setType(owningType); + } + } + pin.setName(VALUE_IN_ADD_VARIABLE_VALUE_ACTION); + return pin; + } + + /** + * Get the command to reset all pins of the action. + * + * @param action + * action to reinitialize pins (SendObjectAction) + * @return command + */ + public static CompoundCommand getResetPinsCmd(SendObjectAction action) { + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + CompoundCommand globalCmd = new CompoundCommand(); + // add target pin + if (action.getTarget() == null) { + InputPin targetPin = createTargetPin(null); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getSendObjectAction_Target(), targetPin); + globalCmd.append(cmd); + } + // add request pin + if (action.getRequest() == null) { + InputPin requestPin = createRequestPin(); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getSendObjectAction_Request(), requestPin); + globalCmd.append(cmd); + } + return globalCmd; + } + + /** + * Get the command to reset all pins of the action. + * + * @param action + * action to reinitialize pins (ReadStructuralFeatureAction) + * @return command + */ + protected CompoundCommand getResetPinsCmd(ReadStructuralFeatureAction action) { + // Get the editing domain + TransactionalEditingDomain editingdomain; + try { + editingdomain = ServiceUtilsForEObject.getInstance().getTransactionalEditingDomain(action); + } catch (ServiceException ex) { + Log.error(DiagramUIPlugin.getInstance(), DiagramUIStatusCodes.IGNORED_EXCEPTION_WARNING, ex.getMessage(), ex); + return null; + } + CompoundCommand globalCmd = new CompoundCommand(); + // add result pin + if (action.getResult() == null) { + OutputPin resultPin = createResultPinInStructuralAction(action); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getReadStructuralFeatureAction_Result(), resultPin); + globalCmd.append(cmd); + } + // add object pin + if (action.getObject() == null) { + InputPin objectPin = createObjectPinInStructuralFeatureAction(action); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getStructuralFeatureAction_Object(), objectPin); + globalCmd.append(cmd); + } + return globalCmd; + } + + /** + * Create the object pin of an ReadStructuralAction + * + * @param action + * @return + */ + public static InputPin createObjectPinInStructuralFeatureAction(StructuralFeatureAction action) { + InputPin pin = UMLFactory.eINSTANCE.createInputPin(); + assignUpperBound(pin); + if (action != null) { + Type type = getTypeFromStructuralFeature(action); + if (type != null) { + pin.setType(type); + } + } + pin.setName(OBJECT_PIN_IN_READS_STRUCTURAL_ACTION); + return pin; + } + + public static Type getTypeFromStructuralFeature(StructuralFeatureAction action) { + Type type = null; + StructuralFeature feature = action.getStructuralFeature(); + if (feature != null) { + Element owner = feature.getOwner(); + if (owner != null) { + if (feature.getFeaturingClassifiers().contains(owner)) { + type = ((Type) owner); + } + } + } + return type; + } + + /** + * Create a simple output pin for a ReadStructura feature FIXME set type + * + * @param action + * @return + */ + public static OutputPin createResultPinInStructuralAction(StructuralFeatureAction action) { + OutputPin pin = UMLFactory.eINSTANCE.createOutputPin(); + assignUpperBound(pin); + Type type = getTypeFromStructuralFeature(action); + if (type != null) { + pin.setType(type); + } + pin.setName(RESULT_PIN_READ_SRTUCTURAL_ACTION); + return pin; + } + + private static void assignUpperBound(ObjectNode node) { + LiteralInteger literal = UMLFactory.eINSTANCE.createLiteralInteger(); + literal.setValue(1); + node.setUpperBound(literal); + } + + /** + * Get the command to reset all pins of the action. + * + * @param action + * action to reinitialize pins (SendObjectAction) + * @return command + */ + protected CompoundCommand getResetPinsCmd(CreateObjectAction action) { + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + CompoundCommand globalCmd = new CompoundCommand(); + // add target pin + if (action.getResult() == null) { + OutputPin resultPin = createResultPin((Classifier) null); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getCreateObjectAction_Result(), resultPin); + globalCmd.append(cmd); + } + return globalCmd; + } + + // /** + // * Get the command to reset all pins of the action. + // * + // * @param action + // * action to reinitialize pins (SendSignalAction) + // * @return command + // */ + // public static CompoundCommand getResetPinsCmd(InvocationAction action) { + // if(!(action instanceof SendSignalAction || action instanceof BroadcastSignalAction)) { + // return null; + // } + // // Get the editing domain + // TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + // CompoundCommand globalCmd = new CompoundCommand(); + // // remove argument pins + // if(!action.getArguments().isEmpty()) { + // Command cmd = RemoveCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getInvocationAction_Argument(), action.getArguments()); + // globalCmd.append(cmd); + // } + // // recover attributes + // List<Property> attributes = Collections.emptyList(); + // Signal signal = action instanceof SendSignalAction ? ((SendSignalAction)action).getSignal() : ((BroadcastSignalAction)action).getSignal(); + // if(signal != null) { + // attributes = signal.getOwnedAttributes(); + // } + // // add pins corresponding to attributes + // Map<Integer, Property> inParameters = new HashMap<Integer, Property>(); + // int inIndex = 0; + // for(Property att : attributes) { + // inParameters.put(inIndex, att); + // inIndex++; + // } + // if(!inParameters.isEmpty()) { + // Command cmd = getAddPinsCmd(action, inParameters, null); + // globalCmd.append(cmd); + // } + // if(action instanceof SendSignalAction) { + // SendSignalAction sendSignalAction = (SendSignalAction)action; + // // add target pin + // if(sendSignalAction.getTarget() == null) { + // InputPin targetPin = createTargetPin(null); + // Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getSendSignalAction_Target(), targetPin); + // globalCmd.append(cmd); + // } + // } + // return globalCmd; + // } + /** + * Retrieve the parameter linked + * + * @param p + * Pin where the EAnnotaion is stored + * @param xmiResource + * @return + */ + public static TypedElement getLinkedParemeter(Pin p, XMIResource xmiResource) { + if (p != null && xmiResource != null) { + EAnnotation eAnnotation = p.getEAnnotation(IPinToParameterLinkCommand.PIN_TO_PARAMETER_LINK); + if (eAnnotation != null && !eAnnotation.getDetails().isEmpty()) { + String id = eAnnotation.getDetails().get(0).getValue(); + EObject pa = xmiResource.getEObject(id); + if (pa instanceof TypedElement) { + return (TypedElement) pa; + } + } + } + return null; + } + + /** + * Get the command to reset all pins of the action. + * + * @param action + * action to reinitialize pins (CallOperationAction or + * CallBehaviorAction) + * @return command + */ + public static CompoundCommand getResetPinsCmd(InvocationAction action) { + // Getting the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + CompoundCommand globalCmd = new CompoundCommand(); + Element behaviorStructural = null; + List<? extends TypedElement> parameters = Collections.emptyList(); + if (action instanceof CallBehaviorAction) { + behaviorStructural = ((CallBehaviorAction) action).getBehavior(); + if (behaviorStructural != null) { + parameters = ((Behavior) behaviorStructural).getOwnedParameters(); + } else { + return globalCmd; + } + } else if (action instanceof CallOperationAction) { + behaviorStructural = ((CallOperationAction) action).getOperation(); + if (behaviorStructural != null) { + parameters = ((Operation) behaviorStructural).getOwnedParameters(); + } else { + return globalCmd; + } + } else if (action instanceof SendSignalAction) { + behaviorStructural = ((SendSignalAction) action).getSignal(); + if (behaviorStructural != null) { + parameters = ((Signal) behaviorStructural).getOwnedAttributes(); + } else { + return globalCmd; + } + } else if (action instanceof BroadcastSignalAction) { + Signal signal = ((BroadcastSignalAction) action).getSignal(); + if (signal != null) { + behaviorStructural = signal; + parameters = ((Signal) behaviorStructural).getOwnedAttributes(); + } else { + parameters = Collections.emptyList(); + } + } + XMIResource xmiResource = getXMIResource(behaviorStructural); + // Removing input pins that are not up to date. + Collection<TypedElement> parameterWhichPinNotDeleted = new ArrayList<TypedElement>(); + Iterable<? extends Pin> allPins = Lists.newArrayList(action.getArguments()); + if (action instanceof CallAction) { + allPins = Iterables.concat(allPins, ((CallAction) action).getResults()); + } + List<Command> removesCommand = Lists.newArrayList(); + for (Pin pin : allPins) { + if (SynchronizePinsParametersHandler.isUpToDate(pin, xmiResource)) { + TypedElement pa = getLinkedParemeter(pin, xmiResource); + parameterWhichPinNotDeleted.add(pa); + } else { + EReference feature = null; + if (pin instanceof InputPin) { + feature = UMLPackage.eINSTANCE.getInvocationAction_Argument(); + } else if (pin instanceof OutputPin) { + feature = UMLPackage.eINSTANCE.getCallAction_Result(); + } + // Removing the pin. + Command cmd = RemoveCommand.create(editingdomain, action, feature, pin); + if (cmd.canExecute()) { + removesCommand.add(cmd); + } + } + } + // Splitting parameters + Map<Integer, TypedElement> inParams = new HashMap<Integer, TypedElement>(); + Map<Integer, TypedElement> outParams = new HashMap<Integer, TypedElement>(); + splitParameters(parameters, parameterWhichPinNotDeleted, inParams, outParams, action); + // Creating new pins. + if (!inParams.isEmpty() || !outParams.isEmpty()) { + Command cmd = getAddPinsCmd(action, inParams, outParams, null); + globalCmd.append(cmd); + } + /* + * Append remove command after create command since create command calculate index of new pins before removing those pins + */ + for (Command rmComand : removesCommand) { + globalCmd.append(rmComand); + } + /* + * No need to reset this pin + */ + if (action instanceof CallOperationAction) { + // add target pin + Operation operation = ((CallOperationAction) action).getOperation(); + if (operation != null) { + InputPin targetPin = createTargetPin(operation); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getCallOperationAction_Target(), targetPin); + globalCmd.append(cmd); + } + } else if (action instanceof SendSignalAction) { + SendSignalAction sendSignalAction = (SendSignalAction) action; + // add target pin + if (sendSignalAction.getTarget() == null) { + InputPin targetPin = createTargetPin(null); + Command cmd = SetCommand.create(editingdomain, action, UMLPackage.eINSTANCE.getSendSignalAction_Target(), targetPin); + globalCmd.append(cmd); + } + } + return globalCmd; + } + + /** + * Split a list of parameters in two lists : in and out parameters. If a parameter is to be ignored, then "null" is added to the + * corresponding list instead. + */ + public static void splitParameters(List<? extends TypedElement> allParams, Collection<? extends TypedElement> paramsToIgnore, Map<Integer, TypedElement> inParams, Map<Integer, TypedElement> outParams, Action action) { + if (action instanceof CallAction) { + Integer inIndex = 0; + Integer outIndex = 0; + for (TypedElement typeElem : allParams) { + if (typeElem instanceof Parameter) { + Parameter param = (Parameter) typeElem; + ParameterDirectionKind direction = param.getDirection(); + // In + if (direction == ParameterDirectionKind.IN_LITERAL || direction == ParameterDirectionKind.INOUT_LITERAL) { + if (!paramsToIgnore.contains(param)) { + inParams.put(inIndex, param); + } + inIndex++; + } + // Out + if (direction == ParameterDirectionKind.OUT_LITERAL || direction == ParameterDirectionKind.INOUT_LITERAL || direction == ParameterDirectionKind.RETURN_LITERAL) { + if (!paramsToIgnore.contains(param)) { + outParams.put(outIndex, param); + } + outIndex++; + } + } + } + } else if (action instanceof InvocationAction) { + Integer inIndex = 0; + for (TypedElement typeElem : allParams) { + if (!paramsToIgnore.contains(typeElem)) { + inParams.put(inIndex, typeElem); + } + inIndex++; + } + } + } + + /** + * Retrieves the XMIResource + * + * @param behaviorStructural + * @return + */ + public static XMIResource getXMIResource(Element behaviorStructural) { + XMIResource xmiResource = null; + if (behaviorStructural != null) { + Resource resource = behaviorStructural.eResource(); + if (resource instanceof XMIResource) { + xmiResource = (XMIResource) resource; + } + } + return xmiResource; + } + + /** + * Get the command to update a pins list with the name if not set yet + * + * @param pins + * the list of pins to update + * @param name + * the new name set on parameter + * @return the command to execute + */ + protected CompoundCommand getSetPinsNamesCmd(List<Pin> pins, String name) { + CompoundCommand globalCmd = new CompoundCommand(); + if (pins == null || name == null || "".equals(name)) { + return globalCmd; + } + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + for (Pin pin : pins) { + // erase the name only if null (not set, the user may have set an + // empty string name) + if (pin.getName() == null) { + // add the command + Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getNamedElement_Name(), name); + globalCmd.append(cmd); + } + } + return globalCmd; + } + + /** + * Get the command to update a pins list with given values + * + * @param pins + * the list of pins to update + * @param type + * the new type value + * @param ordered + * the new isOrdered value + * @param unique + * the new isUnique value + * @param lower + * the new lower value + * @param lowerValue + * the new lowerValue value + * @param upper + * the new upper value + * @param upperValue + * the new upperValue value + * @return the command to execute + */ + protected CompoundCommand getUpdatePinsCmd(List<Pin> pins, Type type, boolean ordered, boolean unique, int lower, ValueSpecification lowerValue, int upper, ValueSpecification upperValue) { + CompoundCommand globalCmd = new CompoundCommand(); + if (pins == null) { + return globalCmd; + } + // Get the editing domain + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + for (Pin pin : pins) { + if (!EcoreUtil.equals(pin.getType(), type)) { + // add the command + Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getTypedElement_Type(), type); + globalCmd.append(cmd); + } + if (pin.isOrdered() != ordered) { + // add the command + Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getMultiplicityElement_IsOrdered(), ordered); + globalCmd.append(cmd); + } + if (pin.isUnique() != unique) { + // add the command + Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getMultiplicityElement_IsUnique(), unique); + globalCmd.append(cmd); + } + // UMLPackage.eINSTANCE.getMultiplicityElement_Lower() is derived + // from + // UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue() + if (!EcoreUtil.equals(pin.getLowerValue(), lowerValue)) { + Object affectedvalue = null; + // Execute a copy command then add the set command + if (lowerValue != null) { + Command copy = CopyCommand.create(editingdomain, Collections.singleton(lowerValue)); + copy.execute(); + Collection<?> result = copy.getResult(); + if (!result.isEmpty()) { + affectedvalue = result.iterator().next(); + } + } + Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getMultiplicityElement_LowerValue(), affectedvalue); + globalCmd.append(cmd); + } + // UMLPackage.eINSTANCE.getMultiplicityElement_Upper() is derived + // from + // UMLPackage.eINSTANCE.getMultiplicityElement_UpperValue() + if (!EcoreUtil.equals(pin.getUpperValue(), upperValue)) { + Object affectedvalue = null; + // Execute a copy command then add the set command + if (upperValue != null) { + Command copy = CopyCommand.create(editingdomain, Collections.singleton(upperValue)); + copy.execute(); + Collection<?> result = copy.getResult(); + if (!result.isEmpty()) { + affectedvalue = result.iterator().next(); + } + } + Command cmd = SetCommand.create(editingdomain, pin, UMLPackage.eINSTANCE.getMultiplicityElement_UpperValue(), affectedvalue); + globalCmd.append(cmd); + } + } + return globalCmd; + } + + /** + * Get the object invoked by the pin's parent action + * + * @return invoked operation, invoked behavior or null + */ + static protected NamedElement getInvokedObject(Pin pin) { + Element action = pin.getOwner(); + if (action instanceof CallOperationAction) { + Operation operation = ((CallOperationAction) action).getOperation(); + return operation; + } else if (action instanceof CallBehaviorAction) { + Behavior behavior = ((CallBehaviorAction) action).getBehavior(); + return behavior; + } else if (action instanceof SendSignalAction) { + Signal signal = ((SendSignalAction) action).getSignal(); + return signal; + } + return null; + } + + /** + * Get all Pins associated to the property (provided no pin or property has + * been added without synchronization) + * + * @param property + * the property + * @return the list of associated pins + */ + static protected List<Pin> getPins(Property property) { + Element owner = property.getOwner(); + if (owner instanceof Signal) { + // initialize listOfPins + List<Pin> listOfPins = new LinkedList<Pin>(); + // get index of pins + int inIndex = ((Signal) owner).getAttributes().indexOf(property); + List<InvocationAction> callingActions = getCallingActions(owner); + // inspect each referencing action + for (InvocationAction action : callingActions) { + // owner is action's sent Signal + Pin pin = ((SendSignalAction) action).getArguments().get(inIndex); + if (pin != null) { + listOfPins.add(pin); + } + } + return listOfPins; + } + return Collections.emptyList(); + } + + /** + * Get all Pins associated to the parameter (provided no pin or parameter + * has been added without synchronization) + * + * @param parameter + * the parameter + * @return the list of associated pins + */ + static protected List<Pin> getPins(Parameter parameter) { + Element owner = parameter.getOwner(); + List<InvocationAction> callingActions = getCallingActions(owner); + // initialize listOfPins + List<Pin> listOfPins = new LinkedList<Pin>(); + // get index of pins + int inIndex = -1; + int outIndex = -1; + switch (parameter.getDirection()) { + case IN_LITERAL: + inIndex = getIndex(parameter, true); + break; + case OUT_LITERAL: + case RETURN_LITERAL: + outIndex = getIndex(parameter, false); + break; + case INOUT_LITERAL: + inIndex = getIndex(parameter, true); + outIndex = getIndex(parameter, false); + break; + } + if (owner instanceof Operation) { + // inspect each referencing action + for (InvocationAction action : callingActions) { + // owner is action's called Operation + switch (parameter.getDirection()) { + case IN_LITERAL: + Pin pin = ((CallOperationAction) action).getArguments().get(inIndex); + if (pin != null) { + listOfPins.add(pin); + } + break; + case OUT_LITERAL: + case RETURN_LITERAL: + pin = ((CallOperationAction) action).getResults().get(outIndex); + if (pin != null) { + listOfPins.add(pin); + } + break; + case INOUT_LITERAL: + pin = ((CallOperationAction) action).getArguments().get(inIndex); + if (pin != null) { + listOfPins.add(pin); + } + pin = ((CallOperationAction) action).getResults().get(outIndex); + if (pin != null) { + listOfPins.add(pin); + } + break; + } + } + return listOfPins; + } else if (owner instanceof Behavior) { + // inspect each referencing action + for (InvocationAction action : callingActions) { + // owner is action's called Behavior + switch (parameter.getDirection()) { + case IN_LITERAL: + Pin pin = ((CallBehaviorAction) action).getArguments().get(inIndex); + if (pin != null) { + listOfPins.add(pin); + } + break; + case OUT_LITERAL: + case RETURN_LITERAL: + pin = ((CallBehaviorAction) action).getResults().get(outIndex); + if (pin != null) { + listOfPins.add(pin); + } + break; + case INOUT_LITERAL: + pin = ((CallBehaviorAction) action).getArguments().get(inIndex); + if (pin != null) { + listOfPins.add(pin); + } + pin = ((CallBehaviorAction) action).getResults().get(outIndex); + if (pin != null) { + listOfPins.add(pin); + } + break; + } + } + return listOfPins; + } + return Collections.emptyList(); + } + + /** + * Get the index (considering Parameters in or out parameters only) at which + * the parameter appears in its container. For convenience with Pin mapping, + * in-out parameters counted are in both solution. Note that this count does + * not take in account the searched for parameter direction. This means that + * this method works even if the searched parameter has a different + * direction than the one specified in in (usefull when direction changes). + * + * @param typedElement + * the searched parameter + * @param in + * if true, compute position in Parameters of direction in, if + * false, of direction out + * @return the position in which the parameter appears (0 based) or -1 if + * failed + */ + static protected int getIndex(TypedElement typedElement, boolean in) { + if (typedElement == null) { + return -1; + } + Element owner = typedElement.getOwner(); + List<Parameter> parametersList = Collections.emptyList(); + if (owner instanceof Operation) { + parametersList = ((Operation) owner).getOwnedParameters(); + } else if (owner instanceof Behavior) { + parametersList = ((Behavior) owner).getOwnedParameters(); + } + int index = 0; + for (Parameter param : parametersList) { + if (param.equals(typedElement)) { + return index; + } + if (in && (ParameterDirectionKind.IN_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.INOUT_LITERAL.equals(param.getDirection()))) { + index++; + } else if (!in && (ParameterDirectionKind.OUT_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.RETURN_LITERAL.equals(param.getDirection()) || ParameterDirectionKind.INOUT_LITERAL.equals(param.getDirection()))) { + index++; + } + } + return -1; + } + + /** + * Ask the user to validate all the implied modifications (parameters and + * all associated pins) + * + * @param listOfActions + * the list of impacted calling actions + * @return whether the user validates the modifications + */ + protected boolean askForValidation(final List<? extends NamedElement> listOfActions) { + SafeDialogOpenerDuringValidation<Boolean> opener = new SafeDialogOpenerDuringValidation<Boolean>() { + + @Override + protected Boolean openDialog() { + return ConfirmPinAndParameterSyncDialog.openConfirmFromParameter(Display.getDefault().getActiveShell(), listOfActions, labelProvider); + } + }; + return opener.execute(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/SafeDialogOpenerDuringValidation.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/SafeDialogOpenerDuringValidation.java index 23fefc53709..77f10f30841 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/SafeDialogOpenerDuringValidation.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/SafeDialogOpenerDuringValidation.java @@ -1,77 +1,77 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import org.eclipse.core.commands.operations.IOperationApprover2;
-import org.eclipse.core.commands.operations.IOperationHistory;
-import org.eclipse.core.commands.operations.IUndoableOperation;
-import org.eclipse.core.commands.operations.OperationHistoryFactory;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-/**
- * This class must be used to open a dialog during a validation. Its usage
- * avoids side effects with the Properties view, which would throw an {@link IllegalStateException}. The parameterizing class can be used to return
- * a result from the dialog (use {@link Void} if no result is expected).
- */
-public abstract class SafeDialogOpenerDuringValidation<ReturnType> {
-
- /**
- * This approver is used to disable any operation during opening of a popup
- * to avoid side effects
- */
- private static IOperationApprover2 operationDisapprover = new IOperationApprover2() {
-
- @Override
- public IStatus proceedUndoing(IUndoableOperation operation, IOperationHistory history, IAdaptable info) {
- return Status.CANCEL_STATUS;
- }
-
- @Override
- public IStatus proceedRedoing(IUndoableOperation operation, IOperationHistory history, IAdaptable info) {
- return Status.CANCEL_STATUS;
- }
-
- @Override
- public IStatus proceedExecuting(IUndoableOperation operation, IOperationHistory history, IAdaptable info) {
- return Status.CANCEL_STATUS;
- }
- };
-
- /**
- * Subclasses must implement this method with the dialog opening. If no
- * result is expected, return null.
- */
- protected abstract ReturnType openDialog();
-
- /**
- * Run the dialog opening with necessary precautions.
- */
- public final ReturnType execute() {
- /*
- * We are currently validating an ongoing operation. Opening a popup
- * here may have side-effects such as re-launching the same operation.
- * (the editor may have not been deactivated yet, and its loss of focus
- * will open a new operation) For this reason, we temporarily disable
- * all operations on the history, just enough time for opening the
- * popup.
- */
- IOperationHistory history = OperationHistoryFactory.getOperationHistory();
- history.addOperationApprover(operationDisapprover);
- ReturnType result = openDialog();
- history.removeOperationApprover(operationDisapprover);
- return result;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import org.eclipse.core.commands.operations.IOperationApprover2; +import org.eclipse.core.commands.operations.IOperationHistory; +import org.eclipse.core.commands.operations.IUndoableOperation; +import org.eclipse.core.commands.operations.OperationHistoryFactory; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; + +/** + * This class must be used to open a dialog during a validation. Its usage + * avoids side effects with the Properties view, which would throw an {@link IllegalStateException}. The parameterizing class can be used to return + * a result from the dialog (use {@link Void} if no result is expected). + */ +public abstract class SafeDialogOpenerDuringValidation<ReturnType> { + + /** + * This approver is used to disable any operation during opening of a popup + * to avoid side effects + */ + private static IOperationApprover2 operationDisapprover = new IOperationApprover2() { + + @Override + public IStatus proceedUndoing(IUndoableOperation operation, IOperationHistory history, IAdaptable info) { + return Status.CANCEL_STATUS; + } + + @Override + public IStatus proceedRedoing(IUndoableOperation operation, IOperationHistory history, IAdaptable info) { + return Status.CANCEL_STATUS; + } + + @Override + public IStatus proceedExecuting(IUndoableOperation operation, IOperationHistory history, IAdaptable info) { + return Status.CANCEL_STATUS; + } + }; + + /** + * Subclasses must implement this method with the dialog opening. If no + * result is expected, return null. + */ + protected abstract ReturnType openDialog(); + + /** + * Run the dialog opening with necessary precautions. + */ + public final ReturnType execute() { + /* + * We are currently validating an ongoing operation. Opening a popup + * here may have side-effects such as re-launching the same operation. + * (the editor may have not been deactivated yet, and its loss of focus + * will open a new operation) For this reason, we temporarily disable + * all operations on the history, just enough time for opening the + * popup. + */ + IOperationHistory history = OperationHistoryFactory.getOperationHistory(); + history.addOperationApprover(operationDisapprover); + ReturnType result = openDialog(); + history.removeOperationApprover(operationDisapprover); + return result; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/UMLValidationHelper.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/UMLValidationHelper.java index 82cc0368a67..4afc4f135f0 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/UMLValidationHelper.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/UMLValidationHelper.java @@ -1,1104 +1,1104 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.emf.common.util.EList;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.emf.ecore.util.EcoreUtil;
-import org.eclipse.emf.validation.IValidationContext;
-import org.eclipse.uml2.uml.Action;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.ActivityEdge;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.Behavior;
-import org.eclipse.uml2.uml.CallOperationAction;
-import org.eclipse.uml2.uml.ControlNode;
-import org.eclipse.uml2.uml.DecisionNode;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.ExceptionHandler;
-import org.eclipse.uml2.uml.ExecutableNode;
-import org.eclipse.uml2.uml.InputPin;
-import org.eclipse.uml2.uml.InterruptibleActivityRegion;
-import org.eclipse.uml2.uml.ObjectFlow;
-import org.eclipse.uml2.uml.ObjectNode;
-import org.eclipse.uml2.uml.Operation;
-import org.eclipse.uml2.uml.OutputPin;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.ParameterDirectionKind;
-import org.eclipse.uml2.uml.Pin;
-import org.eclipse.uml2.uml.StructuredActivityNode;
-import org.eclipse.uml2.uml.Type;
-import org.eclipse.uml2.uml.UMLPackage;
-import org.eclipse.uml2.uml.ValuePin;
-import org.eclipse.uml2.uml.ValueSpecification;
-
-public class UMLValidationHelper {
-
- /**
- * Exception Handler constraint define in From UML Superstructure Version 2.4.1 with change bars
- */
- private static final String EXCEPTION_HANDLER_CONSTRAINT_2 = "An edge that has a source in an exception handler structured node must also have its target in the handler, and vice versa.";
-
- /**
- * Exception Handler constraint define in From UML Superstructure Version 2.4.1 with change bars
- */
- private static final String EXCEPTION_HANDLER_CONSTRAINT_3 = "If the protected node is a StructuredActivityNode with output pins, then the exception handler body must also be a StructuredActivityNode with output pins that correspond in number and types to those of the protected node.";
-
- /**
- * Exception Handler constraint define in From UML Superstructure Version 2.4.1 with change bars
- */
- private static final String EXCEPTION_HANDLER_CONSTRAINT_4 = "The handler body has one input, and that input is the same as the exception input";
-
- /**
- * Exception Handler constraint define in From UML Superstructure Version 2.4.1 with change bars
- */
- private static final String EXCEPTION_HANDLER_CONSTRAINT_1 = "The exception handler and its input object node are not the source or target of any edge.";
-
- /**
- * The source and target of an edge must be in the same activity as the
- * edge.
- *
- * @param context
- * The receiving '<em><b>Activity Edge</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateSourceAndTarget(ActivityEdge context, IValidationContext ctx) {
- Activity edgeActivity = context.getActivity();
- if (edgeActivity == null) {
- // edge is contained by activity or group. Its activity is by
- // consequence a parent of it
- Element edgeOwner = context.getOwner();
- while (edgeOwner != null && !(edgeOwner instanceof Activity)) {
- edgeOwner = edgeOwner.getOwner();
- }
- if (edgeOwner instanceof Activity) {
- edgeActivity = (Activity) edgeOwner;
- } else {
- // this case should not occur. But in such a case, model is
- // invalid for another
- // reason
- return ctx.createSuccessStatus();
- }
- }
- ActivityNode source = context.getSource();
- ActivityNode target = context.getTarget();
- if (source != null && target != null) {
- Activity sourceActivity = source.getActivity();
- if (sourceActivity == null) {
- // activity node is contained by activity or group. Its activity
- // is by consequence a
- // parent of it
- Element sourceOwner = source.getOwner();
- while (sourceOwner != null && !(sourceOwner instanceof Activity)) {
- sourceOwner = sourceOwner.getOwner();
- }
- if (sourceOwner instanceof Activity) {
- sourceActivity = (Activity) sourceOwner;
- } else {
- // this case should not occur. But in such a case, model is
- // invalid for another
- // reason
- return ctx.createSuccessStatus();
- }
- }
- Activity targetActivity = target.getActivity();
- if (targetActivity == null) {
- // activity node is contained by activity or group. Its activity
- // is by consequence a
- // parent of it
- Element targetOwner = target.getOwner();
- while (targetOwner != null && !(targetOwner instanceof Activity)) {
- targetOwner = targetOwner.getOwner();
- }
- if (targetOwner instanceof Activity) {
- targetActivity = (Activity) targetOwner;
- } else {
- // this case should not occur. But in such a case, model is
- // invalid for another
- // reason
- return ctx.createSuccessStatus();
- }
- }
- if (!edgeActivity.equals(sourceActivity) || !edgeActivity.equals(targetActivity)) {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Implementation of the constraint
- * [1] Interrupting edges of a region must have their source node in the region and their target node outside the region in the
- * same activity containing the region.
- * From UML Superstructure Version 2.4.1 with change bars
- * USE for validation framework
- *
- * @param context
- * @param ctx
- * @param interrupts
- * @return
- */
- public static IStatus validateInterruptibleEdge(ActivityEdge context, IValidationContext ctx) {
- return validateInterruptibleEdge(context, context.getInterrupts()) ? ctx.createSuccessStatus() : ctx
- .createFailureStatus("Interrupting edges of a region must have their source node in the region and their target node outside the region in the same activity containing the region.");//
- }
-
- /**
- * Implementation of the constraint on Exception Handler:
- * [2] An edge that has a source in an exception handler structured node must also have its target in the handler, and vice versa.
- *
- * @param context
- * @param ctx
- * @return
- */
- public static IStatus validateException_StructuredActivityNode_Constraint2(ActivityEdge context, IValidationContext ctx) {
- /*
- * Test the constraint un Exception handler section from Version 2.4.1 with change bars
- * [2] An edge that has a source in an exception handler structured node must also have its target in the handler, and vice versa.
- */
- ActivityNode source = context.getSource();
- ActivityNode target = context.getTarget();
- if (source != null && target != null) {
- StructuredActivityNode inStrucActNode = source.getInStructuredNode();
- if (inStrucActNode != null) {
- if (!inStrucActNode.equals(target.getInStructuredNode())) {
- return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_2);
- }
- } else {
- if (target.getInStructuredNode() != null) {
- return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_2);
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Implementation of the constraint on Exception Handler:
- * [4] The handler body has one input, and that input is the same as the exception input
- *
- * @param context
- * @param ctx
- * @return
- */
- public static IStatus validateException_HandlerBody_Constraint4(ExceptionHandler context, IValidationContext ctx) {
- ExecutableNode handlerBody = context.getHandlerBody();
- /*
- * [4] The handler body has one input, and that input is the same as the exception input
- */
- if (handlerBody != null) {
- if (handlerBody instanceof Action) {
- Action handlerBodyAction = (Action) handlerBody;
- if (handlerBodyAction.getInputs() == null || handlerBodyAction.getInputs().size() != 1) {
- return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_4);//
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Implementation of the constraint:
- * [3] If the protected node is a StructuredActivityNode with output pins, then the exception handler body must also be a
- * StructuredActivityNode with output pins that correspond in number and types to those of the protected node.
- *
- * @param context
- * @param ctx
- * @return
- */
- public static IStatus validateException_SourceAndTargetEdge_Constraint1(ExceptionHandler context, IValidationContext ctx) {
- /*
- * [1] The exception handler and its input object node are not the source or target of any edge.
- */
- ObjectNode exceptionInput = context.getExceptionInput();
- if (exceptionInput != null) {
- EList<ActivityEdge> incominEdges = exceptionInput.getIncomings();
- EList<ActivityEdge> outgoingEdges = exceptionInput.getOutgoings();
- if ((incominEdges != null && incominEdges.size() != 0) || (outgoingEdges != null && outgoingEdges.size() != 0)) {
- return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_1);
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Implementation of the constraint:
- * [3] If the protected node is a StructuredActivityNode with output pins, then the exception handler body must also be a
- * StructuredActivityNode with output pins that correspond in number and types to those of the protected node.
- *
- * @param context
- * @param ctx
- * @return
- */
- public static IStatus validateException_StructuredActivityNode_Constraint3(ExceptionHandler context, IValidationContext ctx) {
- /*
- * [3] If the protected node is a StructuredActivityNode with output pins, then the exception handler body must also be a
- * StructuredActivityNode with output pins that correspond in number and types to those of the protected node.
- */
- ExecutableNode protectedNode = context.getProtectedNode();
- ExecutableNode handlerBody = context.getHandlerBody();
- if (protectedNode != null && handlerBody != null) {
- if (protectedNode instanceof StructuredActivityNode) {
- StructuredActivityNode structuredActNode = (StructuredActivityNode) protectedNode;
- if (handlerBody instanceof StructuredActivityNode) {
- EList<OutputPin> protectedNodeOutputPin = structuredActNode.getOutputs();
- EList<OutputPin> handlerBodyOutputPin = ((StructuredActivityNode) handlerBody).getOutputs();
- if (protectedNodeOutputPin.size() != handlerBodyOutputPin.size()) {
- return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_3);
- }
- for (int i = 0; i < protectedNodeOutputPin.size(); i++) {
- OutputPin outputPin = protectedNodeOutputPin.get(i);
- if (outputPin != null && outputPin.equals(handlerBodyOutputPin.get(i))) {
- return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_3);
- }
- }
- } else if (handlerBody != null) {
- return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_3);
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Implementation of the constraint
- * [1] Interrupting edges of a region must have their source node in the region and their target node outside the region in the
- * same activity containing the region.
- * From UML Superstructure Version 2.4.1 with change bars
- *
- * @param context
- * @param ctx
- * @param interrupts
- * @return
- */
- public static boolean validateInterruptibleEdge(ActivityEdge context, InterruptibleActivityRegion interrupts) {
- if (interrupts != null) {
- // validate source
- Element source = context.getSource();
- boolean validSource = false;
- while (source instanceof ActivityNode && !validSource) {
- if (((ActivityNode) source).getInInterruptibleRegions().contains(interrupts)) {
- validSource = true;
- }
- source = source.getOwner();
- }
- if (!validSource) {
- return false;
- }
- // validate target
- Element target = context.getTarget();
- while (target instanceof ActivityNode) {
- if (((ActivityNode) target).getInInterruptibleRegions().contains(interrupts)) {
- return false;
- }
- target = target.getOwner();
- }
- }
- return true;
- }
-
- /**
- * Object nodes connected by an object flow, with optionally intervening
- * control nodes, must have compatible types. In particular, the downstream
- * object node type must be the same or a supertype of the upstream object
- * node type.
- *
- * @param context
- * The receiving '<em><b>Object Flow</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateCompatibleTypes(ObjectFlow context, IValidationContext ctx) {
- /*
- * In case object flow have transformation behavior, the basic
- * constraint (which describes general case only) does not need to be
- * respected. In such a case Type consistency is checked by
- * validateTransformationBehaviour. The UML specification is not very
- * precise on this point. The constraint must be relaxed when a
- * transformation interferes.
- */
- if (context.getTransformation() == null) {
- List<Type> srcTypes = getUpstreamExpectedTypes(context, new LinkedList<ObjectFlow>());
- for (Type srcType : srcTypes) {
- for (Type targetType : getDownstreamExpectedTypes(context, new LinkedList<ObjectFlow>())) {
- if (!isSuperType(targetType, srcType)) {
- return ctx.createFailureStatus();
- }
- }
- }
- }
- // if there is a transformation, validateTransformationBehaviour
- // applies.
- return ctx.createSuccessStatus();
- }
-
- /**
- * Object nodes connected by an object flow, with optionally intervening
- * control nodes, must have the same upper bounds.
- *
- * @param context
- * The receiving '<em><b>Object Flow</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateSameUpperBounds(ObjectFlow context, IValidationContext ctx) {
- ActivityNode source = context.getSource();
- if (source instanceof ObjectNode) {
- ValueSpecification srcUpper = ((ObjectNode) source).getUpperBound();
- for (ObjectNode targetNode : getDownStreamObjectNodes(context)) {
- ValueSpecification targetUpper = targetNode.getUpperBound();
- if (!EcoreUtil.equals(srcUpper, targetUpper)) {
- return ctx.createFailureStatus();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * An edge with constant weight may not target an object node, or lead to an
- * object node downstream with no intervening actions, that has an upper
- * bound less than the weight.
- *
- * @param context
- * The receiving '<em><b>Object Flow</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateTarget(ObjectFlow context, IValidationContext ctx) {
- int weight = 0;
- try {
- if (context.getWeight() != null) {
- weight = context.getWeight().integerValue();
- } else {
- // no weight specified
- return ctx.createSuccessStatus();
- }
- } catch (UnsupportedOperationException noValueExc) {
- return ctx.createSuccessStatus();
- }
- for (ObjectNode targetNode : getDownStreamObjectNodes(context)) {
- int targetUpper = 0;
- try {
- if (targetNode.getUpperBound() != null) {
- targetUpper = targetNode.getUpperBound().integerValue();
- } else {
- // no upper bound specified
- continue;
- }
- } catch (UnsupportedOperationException noValueExc) {
- continue;
- }
- if (targetUpper < weight) {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * A transformation behavior has one input parameter and one output
- * parameter. The input parameter must be the same as or a supertype of the
- * type of object token coming from the source end. The output parameter
- * must be the same or a subtype of the type of object token expected
- * downstream. The behavior cannot have side effects.
- *
- * @param context
- * The receiving '<em><b>Object Flow</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateTransformationBehaviour(ObjectFlow context, IValidationContext ctx) {
- Behavior transformation = context.getTransformation();
- if (transformation != null) {
- int numberIn = 0;
- int numberOut = 0;
- Parameter paramIn = null;
- Parameter paramOut = null;
- for (Parameter param : transformation.getOwnedParameters()) {
- switch (param.getDirection()) {
- case IN_LITERAL:
- numberIn++;
- paramIn = param;
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- numberOut++;
- paramOut = param;
- break;
- case INOUT_LITERAL:
- numberIn++;
- paramIn = param;
- numberOut++;
- paramOut = param;
- break;
- }
- }
- if (numberIn != 1 || numberOut != 1) {
- return ctx.createFailureStatus();
- }
- // check types coming in the flow
- List<Type> srcTypes = getUpstreamExpectedTypes(context, new LinkedList<ObjectFlow>());
- for (Type typeToCheck : srcTypes) {
- if (!isSuperType(paramIn.getType(), typeToCheck)) {
- ctx.createFailureStatus();
- }
- }
- // check types going out the flow
- List<Type> targetTypes = getDownstreamExpectedTypes(context, new LinkedList<ObjectFlow>());
- for (Type typeToCheck : targetTypes) {
- if (!isSuperType(typeToCheck, paramOut.getType())) {
- ctx.createFailureStatus();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * A selection behavior has one input parameter and one output parameter.
- * The input parameter must be a bag of elements of the same as or a
- * supertype of the type of source object node. The output parameter must be
- * the same or a subtype of the type of source object node. The behavior
- * cannot have side effects.
- *
- * @param context
- * The receiving '<em><b>Object Flow</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateInputAndOutputParameter(ObjectFlow context, IValidationContext ctx) {
- Behavior selection = context.getSelection();
- if (selection != null) {
- int numberIn = 0;
- int numberOut = 0;
- Parameter paramIn = null;
- Parameter paramOut = null;
- for (Parameter param : selection.getOwnedParameters()) {
- switch (param.getDirection()) {
- case IN_LITERAL:
- numberIn++;
- paramIn = param;
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- numberOut++;
- paramOut = param;
- break;
- case INOUT_LITERAL:
- numberIn++;
- paramIn = param;
- numberOut++;
- paramOut = param;
- break;
- }
- }
- if (numberIn != 1 || numberOut != 1) {
- return ctx.createFailureStatus();
- }
- // check types coming in the flow
- List<Type> srcTypes = getUpstreamExpectedTypes(context, new LinkedList<ObjectFlow>());
- for (Type typeToCheck : srcTypes) {
- if (!isSuperType(paramIn.getType(), typeToCheck)) {
- ctx.createFailureStatus();
- }
- }
- // check types going out the flow
- List<Type> targetTypes = getDownstreamExpectedTypes(context, new LinkedList<ObjectFlow>());
- for (Type typeToCheck : targetTypes) {
- if (!isSuperType(typeToCheck, paramOut.getType())) {
- ctx.createFailureStatus();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * The type of value specification must be compatible with the type of the
- * value pin.
- *
- * @param context
- * The receiving '<em><b>Value Pin</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateCompatibleType(ValuePin context, IValidationContext ctx) {
- ValueSpecification value = context.getValue();
- if (value != null) {
- if (!isSuperType(context.getType(), value.getType())) {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * If the decision node has no decision input flow and an incoming object
- * flow, then a decision input behavior has one input parameter whose type
- * is the same as or a supertype of the type of object tokens offered on the
- * incoming edge.
- *
- * @param context
- * The receiving '<em><b>Decision Node</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateIncomingObjectOneInputParameter(DecisionNode context, IValidationContext ctx) {
- Behavior behavior = context.getDecisionInput();
- if (behavior != null) {
- ObjectFlow decisionInputFlow = context.getDecisionInputFlow();
- ActivityEdge incomingObjectFlow = context.getIncoming(null, true, UMLPackage.eINSTANCE.getObjectFlow());
- if (decisionInputFlow == null && incomingObjectFlow != null) {
- ObjectFlow inFlow = (ObjectFlow) incomingObjectFlow;
- /*
- * No decision input flow and an incoming object flow. There
- * must be 1 in parameter with type compatibility with
- * incomingObjectFlow
- */
- boolean parameterFound = false;
- for (Parameter param : behavior.getOwnedParameters()) {
- if (ParameterDirectionKind.IN_LITERAL.equals(param.getDirection())) {
- if (!parameterFound) {
- // recover type coming from the flow
- List<Type> types = getTypeComingFromFlow(inFlow, new LinkedList<ObjectFlow>());
- for (Type comingType : types) {
- if (!isSuperType(param.getType(), comingType)) {
- // type of the parameter is not compatible
- // with incoming edge
- return ctx.createFailureStatus();
- }
- }
- } else {
- // unexpected second input parameter
- return ctx.createFailureStatus();
- }
- }
- }
- if (!parameterFound) {
- // expected input parameter not found
- return ctx.createFailureStatus();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * If the decision node has a decision input flow and an incoming control
- * flow, then a decision input behavior has one input parameter whose type
- * is the same as or a supertype of the type of object tokens offered on the
- * decision input flow.
- *
- * @param context
- * The receiving '<em><b>Decision Node</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateIncomingControlOneInputParameter(DecisionNode context, IValidationContext ctx) {
- Behavior behavior = context.getDecisionInput();
- if (behavior != null) {
- ObjectFlow decisionInputFlow = context.getDecisionInputFlow();
- ActivityEdge incomingControlFlow = context.getIncoming(null, true, UMLPackage.eINSTANCE.getControlFlow());
- if (decisionInputFlow != null && incomingControlFlow != null) {
- /*
- * Decision input flow and an incoming control flow. There must
- * be 1 in parameter with type compatibility with
- * decisionInputFlow
- */
- boolean parameterFound = false;
- for (Parameter param : behavior.getOwnedParameters()) {
- if (ParameterDirectionKind.IN_LITERAL.equals(param.getDirection())) {
- if (!parameterFound) {
- // recover type coming from the flow
- List<Type> types = getTypeComingFromFlow(decisionInputFlow, new LinkedList<ObjectFlow>());
- for (Type comingType : types) {
- if (!isSuperType(param.getType(), comingType)) {
- // type of the parameter is not compatible
- // with incoming edge
- return ctx.createFailureStatus();
- }
- }
- parameterFound = true;
- } else {
- // unexpected second input parameter
- return ctx.createFailureStatus();
- }
- }
- }
- if (!parameterFound) {
- // expected input parameter not found
- return ctx.createFailureStatus();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * If the decision node has a decision input flow and an second incoming
- * object flow, then a decision input behavior has two input parameters, the
- * first of which has a type that is the same as or a supertype of the type
- * of the type of object tokens offered on the nondecision input flow and
- * the second of which has a type that is the same as or a supertype of the
- * type of object tokens offered on the decision input flow.
- *
- * @param context
- * The receiving '<em><b>Decision Node</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateTwoInputParameters(DecisionNode context, IValidationContext ctx) {
- Behavior behavior = context.getDecisionInput();
- if (behavior != null) {
- ObjectFlow decisionInputFlow = context.getDecisionInputFlow();
- ActivityEdge incomingObjectFlow = null;
- for (ActivityEdge incomingEdge : context.getIncomings()) {
- // filter the decision flow
- if (incomingEdge instanceof ObjectFlow && incomingEdge != decisionInputFlow) {
- incomingObjectFlow = incomingEdge;
- }
- }
- if (decisionInputFlow != null && incomingObjectFlow != null) {
- ObjectFlow inFlow = (ObjectFlow) incomingObjectFlow;
- /*
- * Decision input flow and an other incoming object flow. There
- * must be 2 in parameters with type compatibility with each
- * flow
- */
- int numberOfParameterFound = 0;
- for (Parameter param : behavior.getOwnedParameters()) {
- if (ParameterDirectionKind.IN_LITERAL.equals(param.getDirection())) {
- if (numberOfParameterFound == 0) {
- // recover type coming from the non decision flow
- List<Type> types = getTypeComingFromFlow(inFlow, new LinkedList<ObjectFlow>());
- for (Type comingType : types) {
- if (!isSuperType(param.getType(), comingType)) {
- // type of the parameter is not compatible
- // with incoming edge
- return ctx.createFailureStatus();
- }
- }
- numberOfParameterFound++;
- } else if (numberOfParameterFound == 1) {
- // recover type coming from the decision flow
- List<Type> types = getTypeComingFromFlow(decisionInputFlow, new LinkedList<ObjectFlow>());
- for (Type comingType : types) {
- if (!isSuperType(param.getType(), comingType)) {
- // type of the parameter is not compatible
- // with incoming edge
- return ctx.createFailureStatus();
- }
- }
- numberOfParameterFound++;
- } else {
- // unexpected third input parameter
- return ctx.createFailureStatus();
- }
- }
- }
- if (numberOfParameterFound < 2) {
- // expected input parameters not found
- return ctx.createFailureStatus();
- }
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * A selection behavior has one input parameter and one output parameter.
- * The input parameter must be a bag of elements of the same type as the
- * object node or a supertype of the type of object node. The output
- * parameter must be the same or a subtype of the type of object node. The
- * behavior cannot have side effects.
- *
- * @param context
- * The receiving '<em><b>Object Node</b></em>' model object.
- * @param ctx
- * The cache of context-specific information.
- */
- public static IStatus validateInputOutputParameter(ObjectNode context, IValidationContext ctx) {
- Behavior selection = context.getSelection();
- if (selection != null) {
- Parameter inParam = null;
- Parameter outParam = null;
- for (Parameter param : selection.getOwnedParameters()) {
- switch (param.getDirection()) {
- case IN_LITERAL:
- if (inParam != null) {
- // second input found
- return ctx.createFailureStatus();
- }
- inParam = param;
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- if (outParam != null) {
- // second output found
- return ctx.createFailureStatus();
- }
- outParam = param;
- break;
- case INOUT_LITERAL:
- if (inParam != null) {
- // second input found
- return ctx.createFailureStatus();
- }
- inParam = param;
- if (outParam != null) {
- // second output found
- return ctx.createFailureStatus();
- }
- outParam = param;
- break;
- }
- }
- if (inParam == null || outParam == null) {
- // missing a parameter
- return ctx.createFailureStatus();
- }
- // check type compatibility
- if (!isSuperType(inParam.getType(), context.getType())) {
- return ctx.createFailureStatus();
- }
- if (!isSuperType(context.getType(), outParam.getType())) {
- return ctx.createFailureStatus();
- }
- }
- return ctx.createSuccessStatus();
- }
-
- /**
- * Check that type is compatible with the first one as parent
- *
- * @param superType
- * the type which should be supertype
- * @param childType
- * the type which should be at lower level
- * @return true if superType is a supertype of childType or if one of them
- * is null
- */
- private static boolean isSuperType(Type superType, Type childType) {
- if (superType == null || childType == null) {
- return true;
- }
- return childType.conformsTo(superType);
- }
-
- /**
- * Get all object nodes which are downstream this object flow. These are the
- * target of the object flow, eventually by the intermediate of control
- * nodes.
- *
- * @param objectFlow
- * the object flow to explore
- * @return list of object nodes downstream
- */
- private static List<ObjectNode> getDownStreamObjectNodes(ObjectFlow objectFlow) {
- ActivityNode target = objectFlow.getTarget();
- if (target instanceof ObjectNode) {
- return Collections.singletonList((ObjectNode) target);
- } else if (target instanceof ControlNode) {
- List<ObjectNode> result = new LinkedList<ObjectNode>();
- for (ActivityEdge outgoingEdge : target.getOutgoings()) {
- if (outgoingEdge instanceof ObjectFlow && !outgoingEdge.equals(objectFlow)) {
- result.addAll(getDownStreamObjectNodes((ObjectFlow) outgoingEdge));
- }
- }
- return result;
- }
- return Collections.emptyList();
- }
-
- /**
- * Get the type which should be expected upstream an object flow
- * (considering the source)
- *
- * @param objectFlow
- * the object flow
- * @param alreadyMetObjectFlows
- * the list of object flows which have already been visited to
- * avoid loops. Callers shall pass new LinkedList<ObjectFlow>()
- * @return the list of types according to different incoming flows
- * (unspecified types omitted).
- */
- private static List<Type> getUpstreamExpectedTypes(ObjectFlow objectFlow, List<ObjectFlow> alreadyMetObjectFlows) {
- ActivityNode src = objectFlow.getSource();
- // handle loops
- if (alreadyMetObjectFlows.contains(objectFlow)) {
- // We are engaged on a loop of object flows. Break it now.
- return Collections.emptyList();
- } else {
- alreadyMetObjectFlows.add(objectFlow);
- }
- // recover incoming types
- if (src instanceof ObjectNode) {
- // type of source object node
- Type type = ((ObjectNode) src).getType();
- if (type != null) {
- return Collections.singletonList(type);
- } else {
- return Collections.emptyList();
- }
- } else if (src instanceof ControlNode) {
- // type coming to the control node from object flows
- List<Type> result = new LinkedList<Type>();
- for (ActivityEdge incomingEdge : src.getIncomings()) {
- if (incomingEdge instanceof ObjectFlow) {
- ObjectFlow incomingFlow = (ObjectFlow) incomingEdge;
- // get the types the incoming flow sends
- result.addAll(getTypeComingFromFlow(incomingFlow, alreadyMetObjectFlows));
- }
- }
- return result;
- }
- return Collections.emptyList();
- }
-
- /**
- * Get the type which should be expected downstream an object flow
- * (considering the target)
- *
- * @param objectFlow
- * the object flow
- * @param alreadyMetObjectFlows
- * the list of object flows which have already been visited to
- * avoid loops. Callers shall pass new LinkedList<ObjectFlow>()
- * @return the list of types according to different outgoing flows
- * (unspecified types omitted).
- */
- private static List<Type> getDownstreamExpectedTypes(ObjectFlow objectFlow, List<ObjectFlow> alreadyMetObjectFlows) {
- ActivityNode target = objectFlow.getTarget();
- // handle loops
- if (alreadyMetObjectFlows.contains(objectFlow)) {
- // We are engaged on a loop of object flows. Break it now.
- return Collections.emptyList();
- } else {
- alreadyMetObjectFlows.add(objectFlow);
- }
- // recover outgoing types
- if (target instanceof ObjectNode) {
- // type of target object node
- Type type = ((ObjectNode) target).getType();
- if (type != null) {
- return Collections.singletonList(type);
- } else {
- return Collections.emptyList();
- }
- } else if (target instanceof ControlNode) {
- // type coming to the control node from object flows
- List<Type> result = new LinkedList<Type>();
- for (ActivityEdge outgoingEdge : target.getOutgoings()) {
- if (outgoingEdge instanceof ObjectFlow) {
- ObjectFlow outgoingFlow = (ObjectFlow) outgoingEdge;
- // get the types the outgoing flow expects
- result.addAll(getTypeExpectedByFlow(outgoingFlow, alreadyMetObjectFlows));
- }
- }
- return result;
- }
- return Collections.emptyList();
- }
-
- /**
- * Get the types which an object flow sends (considering itself and its
- * source)
- *
- * @param inputFlow
- * the object flow
- * @param alreadyMetObjectFlows
- * the list of object flows which have already been visited to
- * avoid loops. Callers shall pass new LinkedList<ObjectFlow>()
- * @return the list of types according to different incoming flows
- * (unspecified types omitted).
- */
- private static List<Type> getTypeComingFromFlow(ObjectFlow inputFlow, List<ObjectFlow> alreadyMetObjectFlows) {
- List<Type> result = new LinkedList<Type>();
- if (inputFlow.getTransformation() == null && inputFlow.getSelection() == null) {
- // type coming from other object flows' sources
- result.addAll(getUpstreamExpectedTypes(inputFlow, alreadyMetObjectFlows));
- } else if (inputFlow.getTransformation() != null) {
- // type coming from other object flows' transformation behavior
- for (Parameter transfParam : inputFlow.getTransformation().getOwnedParameters()) {
- switch (transfParam.getDirection()) {
- case IN_LITERAL:
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- case INOUT_LITERAL:
- if (transfParam.getType() != null) {
- result.add(transfParam.getType());
- }
- break;
- }
- }
- } else if (inputFlow.getSelection() != null) {
- // type coming from other object flows' selection behavior
- for (Parameter selParam : inputFlow.getSelection().getOwnedParameters()) {
- switch (selParam.getDirection()) {
- case IN_LITERAL:
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- case INOUT_LITERAL:
- if (selParam.getType() != null) {
- result.add(selParam.getType());
- }
- break;
- }
- }
- }
- return result;
- }
-
- /**
- * Get the types which an object flow handles (considering itself and its
- * target)
- *
- * @param outputFlow
- * the object flow
- * @param alreadyMetObjectFlows
- * the list of object flows which have already been visited to
- * avoid loops. Callers shall pass new LinkedList<ObjectFlow>()
- * @return the list of types according to different outgoing flows
- * (unspecified types omitted).
- */
- private static List<Type> getTypeExpectedByFlow(ObjectFlow outputFlow, List<ObjectFlow> alreadyMetObjectFlows) {
- List<Type> result = new LinkedList<Type>();
- if (outputFlow.getTransformation() == null) {
- // type coming from other object flows' targets
- result.addAll(getDownstreamExpectedTypes(outputFlow, alreadyMetObjectFlows));
- } else {
- // type coming from other object flows' transformation behavior
- for (Parameter transfParam : outputFlow.getTransformation().getOwnedParameters()) {
- switch (transfParam.getDirection()) {
- case IN_LITERAL:
- case INOUT_LITERAL:
- if (transfParam.getType() != null) {
- result.add(transfParam.getType());
- }
- break;
- case OUT_LITERAL:
- case RETURN_LITERAL:
- break;
- }
- }
- }
- return result;
- }
-
- enum Direction {
- IN, OUT
- };
-
- /**
- * Validate Call Operation Action,
- * the validity of the parameters with pins
- *
- * @param action
- * @param ctx
- * @return OK_STATUS if paramters and pins are synchronised
- */
- @PinAndParameterSynchronizeValidator
- public static IStatus validateCallOperation(CallOperationAction action, IValidationContext ctx) {
- if (action.getOperation() == null) {
- return ctx.createFailureStatus(String.format("%s does not have operation", action.getName()));
- }
- // in check
- List<Parameter> ins = getParameters(action.getOperation(), Direction.IN);
- EList<InputPin> inputs = action.getArguments();
- if (ins.size() != inputs.size()) {
- return ctx.createFailureStatus(String.format("pins of %s does not have the same number of input pins as input parameters of the operation %s", action.getName(), action.getOperation().getName()));
- }
- int index = 0;
- for (Parameter p : ins) {
- IStatus status = validatePin(index, p, inputs, ctx);
- if (!status.isOK()) {
- return status;
- }
- index++;
- }
- // out check
- List<Parameter> outs = getParameters(action.getOperation(), Direction.OUT);
- int indexOuts = 0;
- EList<OutputPin> outputs = action.getOutputs();
- if (outs.size() != outputs.size()) {
- return ctx.createFailureStatus(String.format("pins of %s does not have the same number of output pins as output parameters of the operation %s", action.getName(), action.getOperation().getName()));
- }
- for (Parameter p : outs) {
- IStatus status = validatePin(indexOuts, p, outputs, ctx);
- if (!status.isOK()) {
- return status;
- }
- indexOuts++;
- }
- // chic type check
- return Status.OK_STATUS;
- }
-
- private static IStatus validatePin(int index, Parameter p, EList<? extends Pin> inputs, IValidationContext ctx) {
- Pin pin = inputs.get(index);
- for (EStructuralFeature a : pin.eClass().getEAllStructuralFeatures()) {
- EStructuralFeature feature = getFeature(a.getName(), p.eClass());
- if (!a.isDerived() && a.isChangeable() && feature != null) {
- if (!pin.eGet(a).equals(p.eGet(feature))) {
- return ctx.createFailureStatus(String.format("attribute %s and attribute %s are different for pin %s", a.getName(), feature.getName(), pin.getName()));
- }
- }
- }
- // check type
- if ((pin.getType() == null || p.getType() == null) && p.getType() != pin.getType()) {
- return ctx.createFailureStatus(String.format("type of pin %s is different the parameter %s", pin.getName(), p.getName()));
- }
- if (pin.getType() != null && !pin.getType().conformsTo(p.getType())) {
- return ctx.createFailureStatus(String.format("type of pin %s is not compatible with the parameter %s", pin.getName(), p.getName()));
- }
- return Status.OK_STATUS;
- }
-
- private static EStructuralFeature getFeature(String name, EClass eclass) {
- for (EStructuralFeature a : eclass.getEAllAttributes()) {
- if (a.getName() != null && a.getName().equals(name)) {
- return a;
- }
- }
- return null;
- }
-
- private static List<Parameter> getParameters(Operation operation, Direction theDirection) {
- List<Parameter> parameters = new ArrayList<Parameter>(operation.getOwnedParameters().size());
- for (Parameter p : operation.getOwnedParameters()) {
- if (theDirection == Direction.IN) {
- if (p.getDirection() == ParameterDirectionKind.IN_LITERAL || p.getDirection() == ParameterDirectionKind.INOUT_LITERAL) {
- parameters.add(p);
- }
- } else if (theDirection == Direction.OUT) {
- if (p.getDirection() == ParameterDirectionKind.OUT_LITERAL || p.getDirection() == ParameterDirectionKind.INOUT_LITERAL || p.getDirection() == ParameterDirectionKind.RETURN_LITERAL) {
- parameters.add(p);
- }
- }
- }
- return parameters;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.emf.validation.IValidationContext; +import org.eclipse.uml2.uml.Action; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.ActivityEdge; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.Behavior; +import org.eclipse.uml2.uml.CallOperationAction; +import org.eclipse.uml2.uml.ControlNode; +import org.eclipse.uml2.uml.DecisionNode; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.ExceptionHandler; +import org.eclipse.uml2.uml.ExecutableNode; +import org.eclipse.uml2.uml.InputPin; +import org.eclipse.uml2.uml.InterruptibleActivityRegion; +import org.eclipse.uml2.uml.ObjectFlow; +import org.eclipse.uml2.uml.ObjectNode; +import org.eclipse.uml2.uml.Operation; +import org.eclipse.uml2.uml.OutputPin; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.ParameterDirectionKind; +import org.eclipse.uml2.uml.Pin; +import org.eclipse.uml2.uml.StructuredActivityNode; +import org.eclipse.uml2.uml.Type; +import org.eclipse.uml2.uml.UMLPackage; +import org.eclipse.uml2.uml.ValuePin; +import org.eclipse.uml2.uml.ValueSpecification; + +public class UMLValidationHelper { + + /** + * Exception Handler constraint define in From UML Superstructure Version 2.4.1 with change bars + */ + private static final String EXCEPTION_HANDLER_CONSTRAINT_2 = "An edge that has a source in an exception handler structured node must also have its target in the handler, and vice versa."; + + /** + * Exception Handler constraint define in From UML Superstructure Version 2.4.1 with change bars + */ + private static final String EXCEPTION_HANDLER_CONSTRAINT_3 = "If the protected node is a StructuredActivityNode with output pins, then the exception handler body must also be a StructuredActivityNode with output pins that correspond in number and types to those of the protected node."; + + /** + * Exception Handler constraint define in From UML Superstructure Version 2.4.1 with change bars + */ + private static final String EXCEPTION_HANDLER_CONSTRAINT_4 = "The handler body has one input, and that input is the same as the exception input"; + + /** + * Exception Handler constraint define in From UML Superstructure Version 2.4.1 with change bars + */ + private static final String EXCEPTION_HANDLER_CONSTRAINT_1 = "The exception handler and its input object node are not the source or target of any edge."; + + /** + * The source and target of an edge must be in the same activity as the + * edge. + * + * @param context + * The receiving '<em><b>Activity Edge</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateSourceAndTarget(ActivityEdge context, IValidationContext ctx) { + Activity edgeActivity = context.getActivity(); + if (edgeActivity == null) { + // edge is contained by activity or group. Its activity is by + // consequence a parent of it + Element edgeOwner = context.getOwner(); + while (edgeOwner != null && !(edgeOwner instanceof Activity)) { + edgeOwner = edgeOwner.getOwner(); + } + if (edgeOwner instanceof Activity) { + edgeActivity = (Activity) edgeOwner; + } else { + // this case should not occur. But in such a case, model is + // invalid for another + // reason + return ctx.createSuccessStatus(); + } + } + ActivityNode source = context.getSource(); + ActivityNode target = context.getTarget(); + if (source != null && target != null) { + Activity sourceActivity = source.getActivity(); + if (sourceActivity == null) { + // activity node is contained by activity or group. Its activity + // is by consequence a + // parent of it + Element sourceOwner = source.getOwner(); + while (sourceOwner != null && !(sourceOwner instanceof Activity)) { + sourceOwner = sourceOwner.getOwner(); + } + if (sourceOwner instanceof Activity) { + sourceActivity = (Activity) sourceOwner; + } else { + // this case should not occur. But in such a case, model is + // invalid for another + // reason + return ctx.createSuccessStatus(); + } + } + Activity targetActivity = target.getActivity(); + if (targetActivity == null) { + // activity node is contained by activity or group. Its activity + // is by consequence a + // parent of it + Element targetOwner = target.getOwner(); + while (targetOwner != null && !(targetOwner instanceof Activity)) { + targetOwner = targetOwner.getOwner(); + } + if (targetOwner instanceof Activity) { + targetActivity = (Activity) targetOwner; + } else { + // this case should not occur. But in such a case, model is + // invalid for another + // reason + return ctx.createSuccessStatus(); + } + } + if (!edgeActivity.equals(sourceActivity) || !edgeActivity.equals(targetActivity)) { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Implementation of the constraint + * [1] Interrupting edges of a region must have their source node in the region and their target node outside the region in the + * same activity containing the region. + * From UML Superstructure Version 2.4.1 with change bars + * USE for validation framework + * + * @param context + * @param ctx + * @param interrupts + * @return + */ + public static IStatus validateInterruptibleEdge(ActivityEdge context, IValidationContext ctx) { + return validateInterruptibleEdge(context, context.getInterrupts()) ? ctx.createSuccessStatus() : ctx + .createFailureStatus("Interrupting edges of a region must have their source node in the region and their target node outside the region in the same activity containing the region.");// + } + + /** + * Implementation of the constraint on Exception Handler: + * [2] An edge that has a source in an exception handler structured node must also have its target in the handler, and vice versa. + * + * @param context + * @param ctx + * @return + */ + public static IStatus validateException_StructuredActivityNode_Constraint2(ActivityEdge context, IValidationContext ctx) { + /* + * Test the constraint un Exception handler section from Version 2.4.1 with change bars + * [2] An edge that has a source in an exception handler structured node must also have its target in the handler, and vice versa. + */ + ActivityNode source = context.getSource(); + ActivityNode target = context.getTarget(); + if (source != null && target != null) { + StructuredActivityNode inStrucActNode = source.getInStructuredNode(); + if (inStrucActNode != null) { + if (!inStrucActNode.equals(target.getInStructuredNode())) { + return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_2); + } + } else { + if (target.getInStructuredNode() != null) { + return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_2); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Implementation of the constraint on Exception Handler: + * [4] The handler body has one input, and that input is the same as the exception input + * + * @param context + * @param ctx + * @return + */ + public static IStatus validateException_HandlerBody_Constraint4(ExceptionHandler context, IValidationContext ctx) { + ExecutableNode handlerBody = context.getHandlerBody(); + /* + * [4] The handler body has one input, and that input is the same as the exception input + */ + if (handlerBody != null) { + if (handlerBody instanceof Action) { + Action handlerBodyAction = (Action) handlerBody; + if (handlerBodyAction.getInputs() == null || handlerBodyAction.getInputs().size() != 1) { + return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_4);// + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Implementation of the constraint: + * [3] If the protected node is a StructuredActivityNode with output pins, then the exception handler body must also be a + * StructuredActivityNode with output pins that correspond in number and types to those of the protected node. + * + * @param context + * @param ctx + * @return + */ + public static IStatus validateException_SourceAndTargetEdge_Constraint1(ExceptionHandler context, IValidationContext ctx) { + /* + * [1] The exception handler and its input object node are not the source or target of any edge. + */ + ObjectNode exceptionInput = context.getExceptionInput(); + if (exceptionInput != null) { + EList<ActivityEdge> incominEdges = exceptionInput.getIncomings(); + EList<ActivityEdge> outgoingEdges = exceptionInput.getOutgoings(); + if ((incominEdges != null && incominEdges.size() != 0) || (outgoingEdges != null && outgoingEdges.size() != 0)) { + return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_1); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Implementation of the constraint: + * [3] If the protected node is a StructuredActivityNode with output pins, then the exception handler body must also be a + * StructuredActivityNode with output pins that correspond in number and types to those of the protected node. + * + * @param context + * @param ctx + * @return + */ + public static IStatus validateException_StructuredActivityNode_Constraint3(ExceptionHandler context, IValidationContext ctx) { + /* + * [3] If the protected node is a StructuredActivityNode with output pins, then the exception handler body must also be a + * StructuredActivityNode with output pins that correspond in number and types to those of the protected node. + */ + ExecutableNode protectedNode = context.getProtectedNode(); + ExecutableNode handlerBody = context.getHandlerBody(); + if (protectedNode != null && handlerBody != null) { + if (protectedNode instanceof StructuredActivityNode) { + StructuredActivityNode structuredActNode = (StructuredActivityNode) protectedNode; + if (handlerBody instanceof StructuredActivityNode) { + EList<OutputPin> protectedNodeOutputPin = structuredActNode.getOutputs(); + EList<OutputPin> handlerBodyOutputPin = ((StructuredActivityNode) handlerBody).getOutputs(); + if (protectedNodeOutputPin.size() != handlerBodyOutputPin.size()) { + return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_3); + } + for (int i = 0; i < protectedNodeOutputPin.size(); i++) { + OutputPin outputPin = protectedNodeOutputPin.get(i); + if (outputPin != null && outputPin.equals(handlerBodyOutputPin.get(i))) { + return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_3); + } + } + } else if (handlerBody != null) { + return ctx.createFailureStatus(EXCEPTION_HANDLER_CONSTRAINT_3); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * Implementation of the constraint + * [1] Interrupting edges of a region must have their source node in the region and their target node outside the region in the + * same activity containing the region. + * From UML Superstructure Version 2.4.1 with change bars + * + * @param context + * @param ctx + * @param interrupts + * @return + */ + public static boolean validateInterruptibleEdge(ActivityEdge context, InterruptibleActivityRegion interrupts) { + if (interrupts != null) { + // validate source + Element source = context.getSource(); + boolean validSource = false; + while (source instanceof ActivityNode && !validSource) { + if (((ActivityNode) source).getInInterruptibleRegions().contains(interrupts)) { + validSource = true; + } + source = source.getOwner(); + } + if (!validSource) { + return false; + } + // validate target + Element target = context.getTarget(); + while (target instanceof ActivityNode) { + if (((ActivityNode) target).getInInterruptibleRegions().contains(interrupts)) { + return false; + } + target = target.getOwner(); + } + } + return true; + } + + /** + * Object nodes connected by an object flow, with optionally intervening + * control nodes, must have compatible types. In particular, the downstream + * object node type must be the same or a supertype of the upstream object + * node type. + * + * @param context + * The receiving '<em><b>Object Flow</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateCompatibleTypes(ObjectFlow context, IValidationContext ctx) { + /* + * In case object flow have transformation behavior, the basic + * constraint (which describes general case only) does not need to be + * respected. In such a case Type consistency is checked by + * validateTransformationBehaviour. The UML specification is not very + * precise on this point. The constraint must be relaxed when a + * transformation interferes. + */ + if (context.getTransformation() == null) { + List<Type> srcTypes = getUpstreamExpectedTypes(context, new LinkedList<ObjectFlow>()); + for (Type srcType : srcTypes) { + for (Type targetType : getDownstreamExpectedTypes(context, new LinkedList<ObjectFlow>())) { + if (!isSuperType(targetType, srcType)) { + return ctx.createFailureStatus(); + } + } + } + } + // if there is a transformation, validateTransformationBehaviour + // applies. + return ctx.createSuccessStatus(); + } + + /** + * Object nodes connected by an object flow, with optionally intervening + * control nodes, must have the same upper bounds. + * + * @param context + * The receiving '<em><b>Object Flow</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateSameUpperBounds(ObjectFlow context, IValidationContext ctx) { + ActivityNode source = context.getSource(); + if (source instanceof ObjectNode) { + ValueSpecification srcUpper = ((ObjectNode) source).getUpperBound(); + for (ObjectNode targetNode : getDownStreamObjectNodes(context)) { + ValueSpecification targetUpper = targetNode.getUpperBound(); + if (!EcoreUtil.equals(srcUpper, targetUpper)) { + return ctx.createFailureStatus(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * An edge with constant weight may not target an object node, or lead to an + * object node downstream with no intervening actions, that has an upper + * bound less than the weight. + * + * @param context + * The receiving '<em><b>Object Flow</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateTarget(ObjectFlow context, IValidationContext ctx) { + int weight = 0; + try { + if (context.getWeight() != null) { + weight = context.getWeight().integerValue(); + } else { + // no weight specified + return ctx.createSuccessStatus(); + } + } catch (UnsupportedOperationException noValueExc) { + return ctx.createSuccessStatus(); + } + for (ObjectNode targetNode : getDownStreamObjectNodes(context)) { + int targetUpper = 0; + try { + if (targetNode.getUpperBound() != null) { + targetUpper = targetNode.getUpperBound().integerValue(); + } else { + // no upper bound specified + continue; + } + } catch (UnsupportedOperationException noValueExc) { + continue; + } + if (targetUpper < weight) { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * A transformation behavior has one input parameter and one output + * parameter. The input parameter must be the same as or a supertype of the + * type of object token coming from the source end. The output parameter + * must be the same or a subtype of the type of object token expected + * downstream. The behavior cannot have side effects. + * + * @param context + * The receiving '<em><b>Object Flow</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateTransformationBehaviour(ObjectFlow context, IValidationContext ctx) { + Behavior transformation = context.getTransformation(); + if (transformation != null) { + int numberIn = 0; + int numberOut = 0; + Parameter paramIn = null; + Parameter paramOut = null; + for (Parameter param : transformation.getOwnedParameters()) { + switch (param.getDirection()) { + case IN_LITERAL: + numberIn++; + paramIn = param; + break; + case OUT_LITERAL: + case RETURN_LITERAL: + numberOut++; + paramOut = param; + break; + case INOUT_LITERAL: + numberIn++; + paramIn = param; + numberOut++; + paramOut = param; + break; + } + } + if (numberIn != 1 || numberOut != 1) { + return ctx.createFailureStatus(); + } + // check types coming in the flow + List<Type> srcTypes = getUpstreamExpectedTypes(context, new LinkedList<ObjectFlow>()); + for (Type typeToCheck : srcTypes) { + if (!isSuperType(paramIn.getType(), typeToCheck)) { + ctx.createFailureStatus(); + } + } + // check types going out the flow + List<Type> targetTypes = getDownstreamExpectedTypes(context, new LinkedList<ObjectFlow>()); + for (Type typeToCheck : targetTypes) { + if (!isSuperType(typeToCheck, paramOut.getType())) { + ctx.createFailureStatus(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * A selection behavior has one input parameter and one output parameter. + * The input parameter must be a bag of elements of the same as or a + * supertype of the type of source object node. The output parameter must be + * the same or a subtype of the type of source object node. The behavior + * cannot have side effects. + * + * @param context + * The receiving '<em><b>Object Flow</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateInputAndOutputParameter(ObjectFlow context, IValidationContext ctx) { + Behavior selection = context.getSelection(); + if (selection != null) { + int numberIn = 0; + int numberOut = 0; + Parameter paramIn = null; + Parameter paramOut = null; + for (Parameter param : selection.getOwnedParameters()) { + switch (param.getDirection()) { + case IN_LITERAL: + numberIn++; + paramIn = param; + break; + case OUT_LITERAL: + case RETURN_LITERAL: + numberOut++; + paramOut = param; + break; + case INOUT_LITERAL: + numberIn++; + paramIn = param; + numberOut++; + paramOut = param; + break; + } + } + if (numberIn != 1 || numberOut != 1) { + return ctx.createFailureStatus(); + } + // check types coming in the flow + List<Type> srcTypes = getUpstreamExpectedTypes(context, new LinkedList<ObjectFlow>()); + for (Type typeToCheck : srcTypes) { + if (!isSuperType(paramIn.getType(), typeToCheck)) { + ctx.createFailureStatus(); + } + } + // check types going out the flow + List<Type> targetTypes = getDownstreamExpectedTypes(context, new LinkedList<ObjectFlow>()); + for (Type typeToCheck : targetTypes) { + if (!isSuperType(typeToCheck, paramOut.getType())) { + ctx.createFailureStatus(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * The type of value specification must be compatible with the type of the + * value pin. + * + * @param context + * The receiving '<em><b>Value Pin</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateCompatibleType(ValuePin context, IValidationContext ctx) { + ValueSpecification value = context.getValue(); + if (value != null) { + if (!isSuperType(context.getType(), value.getType())) { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * If the decision node has no decision input flow and an incoming object + * flow, then a decision input behavior has one input parameter whose type + * is the same as or a supertype of the type of object tokens offered on the + * incoming edge. + * + * @param context + * The receiving '<em><b>Decision Node</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateIncomingObjectOneInputParameter(DecisionNode context, IValidationContext ctx) { + Behavior behavior = context.getDecisionInput(); + if (behavior != null) { + ObjectFlow decisionInputFlow = context.getDecisionInputFlow(); + ActivityEdge incomingObjectFlow = context.getIncoming(null, true, UMLPackage.eINSTANCE.getObjectFlow()); + if (decisionInputFlow == null && incomingObjectFlow != null) { + ObjectFlow inFlow = (ObjectFlow) incomingObjectFlow; + /* + * No decision input flow and an incoming object flow. There + * must be 1 in parameter with type compatibility with + * incomingObjectFlow + */ + boolean parameterFound = false; + for (Parameter param : behavior.getOwnedParameters()) { + if (ParameterDirectionKind.IN_LITERAL.equals(param.getDirection())) { + if (!parameterFound) { + // recover type coming from the flow + List<Type> types = getTypeComingFromFlow(inFlow, new LinkedList<ObjectFlow>()); + for (Type comingType : types) { + if (!isSuperType(param.getType(), comingType)) { + // type of the parameter is not compatible + // with incoming edge + return ctx.createFailureStatus(); + } + } + } else { + // unexpected second input parameter + return ctx.createFailureStatus(); + } + } + } + if (!parameterFound) { + // expected input parameter not found + return ctx.createFailureStatus(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * If the decision node has a decision input flow and an incoming control + * flow, then a decision input behavior has one input parameter whose type + * is the same as or a supertype of the type of object tokens offered on the + * decision input flow. + * + * @param context + * The receiving '<em><b>Decision Node</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateIncomingControlOneInputParameter(DecisionNode context, IValidationContext ctx) { + Behavior behavior = context.getDecisionInput(); + if (behavior != null) { + ObjectFlow decisionInputFlow = context.getDecisionInputFlow(); + ActivityEdge incomingControlFlow = context.getIncoming(null, true, UMLPackage.eINSTANCE.getControlFlow()); + if (decisionInputFlow != null && incomingControlFlow != null) { + /* + * Decision input flow and an incoming control flow. There must + * be 1 in parameter with type compatibility with + * decisionInputFlow + */ + boolean parameterFound = false; + for (Parameter param : behavior.getOwnedParameters()) { + if (ParameterDirectionKind.IN_LITERAL.equals(param.getDirection())) { + if (!parameterFound) { + // recover type coming from the flow + List<Type> types = getTypeComingFromFlow(decisionInputFlow, new LinkedList<ObjectFlow>()); + for (Type comingType : types) { + if (!isSuperType(param.getType(), comingType)) { + // type of the parameter is not compatible + // with incoming edge + return ctx.createFailureStatus(); + } + } + parameterFound = true; + } else { + // unexpected second input parameter + return ctx.createFailureStatus(); + } + } + } + if (!parameterFound) { + // expected input parameter not found + return ctx.createFailureStatus(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * If the decision node has a decision input flow and an second incoming + * object flow, then a decision input behavior has two input parameters, the + * first of which has a type that is the same as or a supertype of the type + * of the type of object tokens offered on the nondecision input flow and + * the second of which has a type that is the same as or a supertype of the + * type of object tokens offered on the decision input flow. + * + * @param context + * The receiving '<em><b>Decision Node</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateTwoInputParameters(DecisionNode context, IValidationContext ctx) { + Behavior behavior = context.getDecisionInput(); + if (behavior != null) { + ObjectFlow decisionInputFlow = context.getDecisionInputFlow(); + ActivityEdge incomingObjectFlow = null; + for (ActivityEdge incomingEdge : context.getIncomings()) { + // filter the decision flow + if (incomingEdge instanceof ObjectFlow && incomingEdge != decisionInputFlow) { + incomingObjectFlow = incomingEdge; + } + } + if (decisionInputFlow != null && incomingObjectFlow != null) { + ObjectFlow inFlow = (ObjectFlow) incomingObjectFlow; + /* + * Decision input flow and an other incoming object flow. There + * must be 2 in parameters with type compatibility with each + * flow + */ + int numberOfParameterFound = 0; + for (Parameter param : behavior.getOwnedParameters()) { + if (ParameterDirectionKind.IN_LITERAL.equals(param.getDirection())) { + if (numberOfParameterFound == 0) { + // recover type coming from the non decision flow + List<Type> types = getTypeComingFromFlow(inFlow, new LinkedList<ObjectFlow>()); + for (Type comingType : types) { + if (!isSuperType(param.getType(), comingType)) { + // type of the parameter is not compatible + // with incoming edge + return ctx.createFailureStatus(); + } + } + numberOfParameterFound++; + } else if (numberOfParameterFound == 1) { + // recover type coming from the decision flow + List<Type> types = getTypeComingFromFlow(decisionInputFlow, new LinkedList<ObjectFlow>()); + for (Type comingType : types) { + if (!isSuperType(param.getType(), comingType)) { + // type of the parameter is not compatible + // with incoming edge + return ctx.createFailureStatus(); + } + } + numberOfParameterFound++; + } else { + // unexpected third input parameter + return ctx.createFailureStatus(); + } + } + } + if (numberOfParameterFound < 2) { + // expected input parameters not found + return ctx.createFailureStatus(); + } + } + } + return ctx.createSuccessStatus(); + } + + /** + * A selection behavior has one input parameter and one output parameter. + * The input parameter must be a bag of elements of the same type as the + * object node or a supertype of the type of object node. The output + * parameter must be the same or a subtype of the type of object node. The + * behavior cannot have side effects. + * + * @param context + * The receiving '<em><b>Object Node</b></em>' model object. + * @param ctx + * The cache of context-specific information. + */ + public static IStatus validateInputOutputParameter(ObjectNode context, IValidationContext ctx) { + Behavior selection = context.getSelection(); + if (selection != null) { + Parameter inParam = null; + Parameter outParam = null; + for (Parameter param : selection.getOwnedParameters()) { + switch (param.getDirection()) { + case IN_LITERAL: + if (inParam != null) { + // second input found + return ctx.createFailureStatus(); + } + inParam = param; + break; + case OUT_LITERAL: + case RETURN_LITERAL: + if (outParam != null) { + // second output found + return ctx.createFailureStatus(); + } + outParam = param; + break; + case INOUT_LITERAL: + if (inParam != null) { + // second input found + return ctx.createFailureStatus(); + } + inParam = param; + if (outParam != null) { + // second output found + return ctx.createFailureStatus(); + } + outParam = param; + break; + } + } + if (inParam == null || outParam == null) { + // missing a parameter + return ctx.createFailureStatus(); + } + // check type compatibility + if (!isSuperType(inParam.getType(), context.getType())) { + return ctx.createFailureStatus(); + } + if (!isSuperType(context.getType(), outParam.getType())) { + return ctx.createFailureStatus(); + } + } + return ctx.createSuccessStatus(); + } + + /** + * Check that type is compatible with the first one as parent + * + * @param superType + * the type which should be supertype + * @param childType + * the type which should be at lower level + * @return true if superType is a supertype of childType or if one of them + * is null + */ + private static boolean isSuperType(Type superType, Type childType) { + if (superType == null || childType == null) { + return true; + } + return childType.conformsTo(superType); + } + + /** + * Get all object nodes which are downstream this object flow. These are the + * target of the object flow, eventually by the intermediate of control + * nodes. + * + * @param objectFlow + * the object flow to explore + * @return list of object nodes downstream + */ + private static List<ObjectNode> getDownStreamObjectNodes(ObjectFlow objectFlow) { + ActivityNode target = objectFlow.getTarget(); + if (target instanceof ObjectNode) { + return Collections.singletonList((ObjectNode) target); + } else if (target instanceof ControlNode) { + List<ObjectNode> result = new LinkedList<ObjectNode>(); + for (ActivityEdge outgoingEdge : target.getOutgoings()) { + if (outgoingEdge instanceof ObjectFlow && !outgoingEdge.equals(objectFlow)) { + result.addAll(getDownStreamObjectNodes((ObjectFlow) outgoingEdge)); + } + } + return result; + } + return Collections.emptyList(); + } + + /** + * Get the type which should be expected upstream an object flow + * (considering the source) + * + * @param objectFlow + * the object flow + * @param alreadyMetObjectFlows + * the list of object flows which have already been visited to + * avoid loops. Callers shall pass new LinkedList<ObjectFlow>() + * @return the list of types according to different incoming flows + * (unspecified types omitted). + */ + private static List<Type> getUpstreamExpectedTypes(ObjectFlow objectFlow, List<ObjectFlow> alreadyMetObjectFlows) { + ActivityNode src = objectFlow.getSource(); + // handle loops + if (alreadyMetObjectFlows.contains(objectFlow)) { + // We are engaged on a loop of object flows. Break it now. + return Collections.emptyList(); + } else { + alreadyMetObjectFlows.add(objectFlow); + } + // recover incoming types + if (src instanceof ObjectNode) { + // type of source object node + Type type = ((ObjectNode) src).getType(); + if (type != null) { + return Collections.singletonList(type); + } else { + return Collections.emptyList(); + } + } else if (src instanceof ControlNode) { + // type coming to the control node from object flows + List<Type> result = new LinkedList<Type>(); + for (ActivityEdge incomingEdge : src.getIncomings()) { + if (incomingEdge instanceof ObjectFlow) { + ObjectFlow incomingFlow = (ObjectFlow) incomingEdge; + // get the types the incoming flow sends + result.addAll(getTypeComingFromFlow(incomingFlow, alreadyMetObjectFlows)); + } + } + return result; + } + return Collections.emptyList(); + } + + /** + * Get the type which should be expected downstream an object flow + * (considering the target) + * + * @param objectFlow + * the object flow + * @param alreadyMetObjectFlows + * the list of object flows which have already been visited to + * avoid loops. Callers shall pass new LinkedList<ObjectFlow>() + * @return the list of types according to different outgoing flows + * (unspecified types omitted). + */ + private static List<Type> getDownstreamExpectedTypes(ObjectFlow objectFlow, List<ObjectFlow> alreadyMetObjectFlows) { + ActivityNode target = objectFlow.getTarget(); + // handle loops + if (alreadyMetObjectFlows.contains(objectFlow)) { + // We are engaged on a loop of object flows. Break it now. + return Collections.emptyList(); + } else { + alreadyMetObjectFlows.add(objectFlow); + } + // recover outgoing types + if (target instanceof ObjectNode) { + // type of target object node + Type type = ((ObjectNode) target).getType(); + if (type != null) { + return Collections.singletonList(type); + } else { + return Collections.emptyList(); + } + } else if (target instanceof ControlNode) { + // type coming to the control node from object flows + List<Type> result = new LinkedList<Type>(); + for (ActivityEdge outgoingEdge : target.getOutgoings()) { + if (outgoingEdge instanceof ObjectFlow) { + ObjectFlow outgoingFlow = (ObjectFlow) outgoingEdge; + // get the types the outgoing flow expects + result.addAll(getTypeExpectedByFlow(outgoingFlow, alreadyMetObjectFlows)); + } + } + return result; + } + return Collections.emptyList(); + } + + /** + * Get the types which an object flow sends (considering itself and its + * source) + * + * @param inputFlow + * the object flow + * @param alreadyMetObjectFlows + * the list of object flows which have already been visited to + * avoid loops. Callers shall pass new LinkedList<ObjectFlow>() + * @return the list of types according to different incoming flows + * (unspecified types omitted). + */ + private static List<Type> getTypeComingFromFlow(ObjectFlow inputFlow, List<ObjectFlow> alreadyMetObjectFlows) { + List<Type> result = new LinkedList<Type>(); + if (inputFlow.getTransformation() == null && inputFlow.getSelection() == null) { + // type coming from other object flows' sources + result.addAll(getUpstreamExpectedTypes(inputFlow, alreadyMetObjectFlows)); + } else if (inputFlow.getTransformation() != null) { + // type coming from other object flows' transformation behavior + for (Parameter transfParam : inputFlow.getTransformation().getOwnedParameters()) { + switch (transfParam.getDirection()) { + case IN_LITERAL: + break; + case OUT_LITERAL: + case RETURN_LITERAL: + case INOUT_LITERAL: + if (transfParam.getType() != null) { + result.add(transfParam.getType()); + } + break; + } + } + } else if (inputFlow.getSelection() != null) { + // type coming from other object flows' selection behavior + for (Parameter selParam : inputFlow.getSelection().getOwnedParameters()) { + switch (selParam.getDirection()) { + case IN_LITERAL: + break; + case OUT_LITERAL: + case RETURN_LITERAL: + case INOUT_LITERAL: + if (selParam.getType() != null) { + result.add(selParam.getType()); + } + break; + } + } + } + return result; + } + + /** + * Get the types which an object flow handles (considering itself and its + * target) + * + * @param outputFlow + * the object flow + * @param alreadyMetObjectFlows + * the list of object flows which have already been visited to + * avoid loops. Callers shall pass new LinkedList<ObjectFlow>() + * @return the list of types according to different outgoing flows + * (unspecified types omitted). + */ + private static List<Type> getTypeExpectedByFlow(ObjectFlow outputFlow, List<ObjectFlow> alreadyMetObjectFlows) { + List<Type> result = new LinkedList<Type>(); + if (outputFlow.getTransformation() == null) { + // type coming from other object flows' targets + result.addAll(getDownstreamExpectedTypes(outputFlow, alreadyMetObjectFlows)); + } else { + // type coming from other object flows' transformation behavior + for (Parameter transfParam : outputFlow.getTransformation().getOwnedParameters()) { + switch (transfParam.getDirection()) { + case IN_LITERAL: + case INOUT_LITERAL: + if (transfParam.getType() != null) { + result.add(transfParam.getType()); + } + break; + case OUT_LITERAL: + case RETURN_LITERAL: + break; + } + } + } + return result; + } + + enum Direction { + IN, OUT + }; + + /** + * Validate Call Operation Action, + * the validity of the parameters with pins + * + * @param action + * @param ctx + * @return OK_STATUS if paramters and pins are synchronised + */ + @PinAndParameterSynchronizeValidator + public static IStatus validateCallOperation(CallOperationAction action, IValidationContext ctx) { + if (action.getOperation() == null) { + return ctx.createFailureStatus(String.format("%s does not have operation", action.getName())); + } + // in check + List<Parameter> ins = getParameters(action.getOperation(), Direction.IN); + EList<InputPin> inputs = action.getArguments(); + if (ins.size() != inputs.size()) { + return ctx.createFailureStatus(String.format("pins of %s does not have the same number of input pins as input parameters of the operation %s", action.getName(), action.getOperation().getName())); + } + int index = 0; + for (Parameter p : ins) { + IStatus status = validatePin(index, p, inputs, ctx); + if (!status.isOK()) { + return status; + } + index++; + } + // out check + List<Parameter> outs = getParameters(action.getOperation(), Direction.OUT); + int indexOuts = 0; + EList<OutputPin> outputs = action.getOutputs(); + if (outs.size() != outputs.size()) { + return ctx.createFailureStatus(String.format("pins of %s does not have the same number of output pins as output parameters of the operation %s", action.getName(), action.getOperation().getName())); + } + for (Parameter p : outs) { + IStatus status = validatePin(indexOuts, p, outputs, ctx); + if (!status.isOK()) { + return status; + } + indexOuts++; + } + // chic type check + return Status.OK_STATUS; + } + + private static IStatus validatePin(int index, Parameter p, EList<? extends Pin> inputs, IValidationContext ctx) { + Pin pin = inputs.get(index); + for (EStructuralFeature a : pin.eClass().getEAllStructuralFeatures()) { + EStructuralFeature feature = getFeature(a.getName(), p.eClass()); + if (!a.isDerived() && a.isChangeable() && feature != null) { + if (!pin.eGet(a).equals(p.eGet(feature))) { + return ctx.createFailureStatus(String.format("attribute %s and attribute %s are different for pin %s", a.getName(), feature.getName(), pin.getName())); + } + } + } + // check type + if ((pin.getType() == null || p.getType() == null) && p.getType() != pin.getType()) { + return ctx.createFailureStatus(String.format("type of pin %s is different the parameter %s", pin.getName(), p.getName())); + } + if (pin.getType() != null && !pin.getType().conformsTo(p.getType())) { + return ctx.createFailureStatus(String.format("type of pin %s is not compatible with the parameter %s", pin.getName(), p.getName())); + } + return Status.OK_STATUS; + } + + private static EStructuralFeature getFeature(String name, EClass eclass) { + for (EStructuralFeature a : eclass.getEAllAttributes()) { + if (a.getName() != null && a.getName().equals(name)) { + return a; + } + } + return null; + } + + private static List<Parameter> getParameters(Operation operation, Direction theDirection) { + List<Parameter> parameters = new ArrayList<Parameter>(operation.getOwnedParameters().size()); + for (Parameter p : operation.getOwnedParameters()) { + if (theDirection == Direction.IN) { + if (p.getDirection() == ParameterDirectionKind.IN_LITERAL || p.getDirection() == ParameterDirectionKind.INOUT_LITERAL) { + parameters.add(p); + } + } else if (theDirection == Direction.OUT) { + if (p.getDirection() == ParameterDirectionKind.OUT_LITERAL || p.getDirection() == ParameterDirectionKind.INOUT_LITERAL || p.getDirection() == ParameterDirectionKind.RETURN_LITERAL) { + parameters.add(p); + } + } + } + return parameters; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/ILinkPinToTarget.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/ILinkPinToTarget.java index 2d38a5f41da..72d824fc797 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/ILinkPinToTarget.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/ILinkPinToTarget.java @@ -1,40 +1,40 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Arthur Daussy (Atos) - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper.datastructure;
-
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Pin;
-
-/**
- * Representation of a link between a pin and a element which it represent (parameter)
- *
- * @author adaussy
- *
- */
-public interface ILinkPinToTarget {
-
- /**
- * Return the {@link Pin} object
- *
- * @return
- */
- public Pin getPin();
-
- /**
- * Return the element pointed by the link
- *
- * @return
- */
- public Element getTarget();
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Arthur Daussy (Atos) - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper.datastructure; + +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Pin; + +/** + * Representation of a link between a pin and a element which it represent (parameter) + * + * @author adaussy + * + */ +public interface ILinkPinToTarget { + + /** + * Return the {@link Pin} object + * + * @return + */ + public Pin getPin(); + + /** + * Return the element pointed by the link + * + * @return + */ + public Element getTarget(); +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/LinkPinToParameter.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/LinkPinToParameter.java index 826902d3c96..c493aff3358 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/LinkPinToParameter.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/LinkPinToParameter.java @@ -1,85 +1,85 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper.datastructure;
-
-import org.eclipse.uml2.uml.CallAction;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Parameter;
-import org.eclipse.uml2.uml.Pin;
-import org.eclipse.uml2.uml.TypedElement;
-
-/**
- * Data structure to store link between a Pin and a Parameter in an {@link CallAction}.
- * UML do not provide this link. This link is define by constraints. In MDT Papyrus we have decided to save this link in order to be able to
- * synchronized call Action and their Structural Behaviors.
- *
- * @author arthur daussy
- *
- */
-public class LinkPinToParameter implements ILinkPinToTarget {
-
- /**
- * When error occur
- */
- public static LinkPinToParameter NO_LINK_AVAILABLE = new LinkPinToParameter(null, null);
-
- /**
- * {@link Pin}
- */
- private Pin pin;
-
- /**
- * {@link Parameter} which is referenced by the pin of the {@link CallAction}
- */
- private TypedElement parameter;
-
- public LinkPinToParameter() {
- }
-
- /**
- * Constructor
- *
- * @param pin
- * {@link Pin}
- * @param parameter
- * {@link Parameter} which is referenced by the pin of the {@link CallAction} element
- */
- public LinkPinToParameter(Pin pin, TypedElement parameter) {
- super();
- this.pin = pin;
- this.parameter = parameter;
- }
-
- @Override
- public Pin getPin() {
- return pin;
- }
-
- public void setPin(Pin pin) {
- this.pin = pin;
- }
-
- public TypedElement getParameter() {
- return parameter;
- }
-
- public void setParameter(TypedElement parameter) {
- this.parameter = parameter;
- }
-
- @Override
- public Element getTarget() {
- return parameter;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper.datastructure; + +import org.eclipse.uml2.uml.CallAction; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Parameter; +import org.eclipse.uml2.uml.Pin; +import org.eclipse.uml2.uml.TypedElement; + +/** + * Data structure to store link between a Pin and a Parameter in an {@link CallAction}. + * UML do not provide this link. This link is define by constraints. In MDT Papyrus we have decided to save this link in order to be able to + * synchronized call Action and their Structural Behaviors. + * + * @author arthur daussy + * + */ +public class LinkPinToParameter implements ILinkPinToTarget { + + /** + * When error occur + */ + public static LinkPinToParameter NO_LINK_AVAILABLE = new LinkPinToParameter(null, null); + + /** + * {@link Pin} + */ + private Pin pin; + + /** + * {@link Parameter} which is referenced by the pin of the {@link CallAction} + */ + private TypedElement parameter; + + public LinkPinToParameter() { + } + + /** + * Constructor + * + * @param pin + * {@link Pin} + * @param parameter + * {@link Parameter} which is referenced by the pin of the {@link CallAction} element + */ + public LinkPinToParameter(Pin pin, TypedElement parameter) { + super(); + this.pin = pin; + this.parameter = parameter; + } + + @Override + public Pin getPin() { + return pin; + } + + public void setPin(Pin pin) { + this.pin = pin; + } + + public TypedElement getParameter() { + return parameter; + } + + public void setParameter(TypedElement parameter) { + this.parameter = parameter; + } + + @Override + public Element getTarget() { + return parameter; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/LinkPinToProperty.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/LinkPinToProperty.java index 07cec8b2f6b..370843648bd 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/LinkPinToProperty.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/helper/datastructure/LinkPinToProperty.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.helper.datastructure;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.Pin;
-import org.eclipse.uml2.uml.Property;
-
-/**
- * Link a pin a to a property
- *
- * @author arthur daussy
- */
-public class LinkPinToProperty implements ILinkPinToTarget {
-
- private Pin pin;
-
- private Property property;
-
- public LinkPinToProperty(Pin pin, Property property) {
- super();
- Assert.isNotNull(pin);
- this.pin = pin;
- Assert.isNotNull(property);
- this.property = property;
- }
-
- @Override
- public Pin getPin() {
- return pin;
- }
-
- @Override
- public Element getTarget() {
- return property;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.helper.datastructure; + +import org.eclipse.core.runtime.Assert; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.Pin; +import org.eclipse.uml2.uml.Property; + +/** + * Link a pin a to a property + * + * @author arthur daussy + */ +public class LinkPinToProperty implements ILinkPinToTarget { + + private Pin pin; + + private Property property; + + public LinkPinToProperty(Pin pin, Property property) { + super(); + Assert.isNotNull(pin); + this.pin = pin; + Assert.isNotNull(property); + this.property = property; + } + + @Override + public Pin getPin() { + return pin; + } + + @Override + public Element getTarget() { + return property; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ExceptionHandlerListener.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ExceptionHandlerListener.java index 0b410c7c61a..22b880a0f9d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ExceptionHandlerListener.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ExceptionHandlerListener.java @@ -1,74 +1,74 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.listeners;
-
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.edit.command.SetCommand;
-import org.eclipse.emf.transaction.NotificationFilter;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.papyrus.infra.emf.gmf.command.EMFtoGMFCommandWrapper;
-import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.ExceptionHandler;
-import org.eclipse.uml2.uml.ExecutableNode;
-import org.eclipse.uml2.uml.Pin;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * When an Exception Input is set (for {@link ExceptionHandler}) then the Handler Body should be set automatically
- *
- * @author arthur daussy
- *
- */
-public class ExceptionHandlerListener extends AbstractPapyrusModifcationTriggerListener {
-
- private static NotificationFilter FEATURE_FILTER = null;
-
- public static NotificationFilter getFEATURE_FILTER() {
- if (FEATURE_FILTER == null) {
- FEATURE_FILTER = NotificationFilter.createFeatureFilter(UMLPackage.Literals.EXCEPTION_HANDLER__EXCEPTION_INPUT);
- }
- return FEATURE_FILTER;
- }
-
- protected ExceptionHandler getElement(Notification notif) {
- Object elem = notif.getNotifier();
- if (elem instanceof ExceptionHandler) {
- return (ExceptionHandler) elem;
- }
- return null;
- }
-
- @Override
- public NotificationFilter getFilter() {
- return getFEATURE_FILTER();
- }
-
- @Override
- protected ICommand getModificationCommand(Notification notif) {
- if (Notification.SET == notif.getEventType()) {
- ExceptionHandler ex = getElement(notif);
- Object exceptionInput = notif.getNewValue();
- if (exceptionInput instanceof Pin) {
- Element owner = ((Pin) exceptionInput).getOwner();
- if (owner instanceof ExecutableNode) {
- SetCommand cmd = new SetCommand(getEditingDomain(notif.getNotifier()), ex, UMLPackage.Literals.EXCEPTION_HANDLER__HANDLER_BODY, owner);
- return new EMFtoGMFCommandWrapper(cmd);
- }
- }
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.listeners; + +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.edit.command.SetCommand; +import org.eclipse.emf.transaction.NotificationFilter; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.papyrus.infra.emf.gmf.command.EMFtoGMFCommandWrapper; +import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.ExceptionHandler; +import org.eclipse.uml2.uml.ExecutableNode; +import org.eclipse.uml2.uml.Pin; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * When an Exception Input is set (for {@link ExceptionHandler}) then the Handler Body should be set automatically + * + * @author arthur daussy + * + */ +public class ExceptionHandlerListener extends AbstractPapyrusModifcationTriggerListener { + + private static NotificationFilter FEATURE_FILTER = null; + + public static NotificationFilter getFEATURE_FILTER() { + if (FEATURE_FILTER == null) { + FEATURE_FILTER = NotificationFilter.createFeatureFilter(UMLPackage.Literals.EXCEPTION_HANDLER__EXCEPTION_INPUT); + } + return FEATURE_FILTER; + } + + protected ExceptionHandler getElement(Notification notif) { + Object elem = notif.getNotifier(); + if (elem instanceof ExceptionHandler) { + return (ExceptionHandler) elem; + } + return null; + } + + @Override + public NotificationFilter getFilter() { + return getFEATURE_FILTER(); + } + + @Override + protected ICommand getModificationCommand(Notification notif) { + if (Notification.SET == notif.getEventType()) { + ExceptionHandler ex = getElement(notif); + Object exceptionInput = notif.getNewValue(); + if (exceptionInput instanceof Pin) { + Element owner = ((Pin) exceptionInput).getOwner(); + if (owner instanceof ExecutableNode) { + SetCommand cmd = new SetCommand(getEditingDomain(notif.getNotifier()), ex, UMLPackage.Literals.EXCEPTION_HANDLER__HANDLER_BODY, owner); + return new EMFtoGMFCommandWrapper(cmd); + } + } + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/InInterruptibleActivityRegionListener.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/InInterruptibleActivityRegionListener.java index 8bd533caff7..882fca3effa 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/InInterruptibleActivityRegionListener.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/InInterruptibleActivityRegionListener.java @@ -1,157 +1,157 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.listeners;
-
-import java.util.Collections;
-import java.util.Iterator;
-
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.edit.command.SetCommand;
-import org.eclipse.emf.transaction.NotificationFilter;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
-import org.eclipse.papyrus.infra.emf.gmf.command.EMFtoGMFCommandWrapper;
-import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.Type;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder;
-import org.eclipse.papyrus.uml.diagram.activity.helper.UMLValidationHelper;
-import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.uml2.uml.ActivityEdge;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.UMLPackage;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Iterators;
-
-/**
- * Listen the {@link UMLPackage.Literals#ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION} feature in orfer to prevetn it to violate the constaint
- * "Interrupting edges of a region must have their source node in the region and their target node outside the region in the same activity containing the region."
- *
- * @author adaussy
- *
- */
-public class InInterruptibleActivityRegionListener extends AbstractPapyrusModifcationTriggerListener {
-
- private static NotificationFilter FEATURE_FILTER = null;
-
- public static NotificationFilter getFEATURE_FILTER() {
- if (FEATURE_FILTER == null) {
- FEATURE_FILTER = NotificationFilter.createFeatureFilter(UMLPackage.Literals.ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION);
- }
- return FEATURE_FILTER;
- }
-
- protected ActivityNode getElement(Notification notif) {
- try {
- return (ActivityNode) notif.getNotifier();
- } catch (ClassCastException e) {
- throw new RuntimeException("InInterruptibleActivityRegionListener should only be notified by ActivityNode");
- }
- }
-
- /**
- * Get the list of all starting or ending Interruptible Edge wich are related to this {@link ActivityNode} and its descendant.
- * Those Iterable can be filled with null elements so test each element for null
- *
- * @param node
- * @return
- */
- public Iterator<Iterable<ActivityEdge>> getActivityEdgeImpactedWithThisChange(ActivityNode node) {
- Iterator<Iterable<ActivityEdge>> activityEdges = Iterators.transform(Iterators.concat(Collections.singleton(node).iterator(), node.eAllContents()), new Function<EObject, Iterable<ActivityEdge>>() {
-
- @Override
- public Iterable<ActivityEdge> apply(EObject from) {
- if (from instanceof ActivityNode) {
- ActivityNode activityNode = (ActivityNode) from;
- Iterable<ActivityEdge> incomingInterruptibleEdge = Iterables.filter(activityNode.getIncomings(), new Predicate<EObject>() {
-
- @Override
- public boolean apply(EObject input) {
- if (input instanceof ActivityEdge) {
- return ((ActivityEdge) input).getInterrupts() != null;
- }
- return false;
- }
- });
- Iterable<ActivityEdge> outcomingEdgeInterruptibleEdge = Iterables.filter(activityNode.getOutgoings(), new Predicate<EObject>() {
-
- @Override
- public boolean apply(EObject input) {
- if (input instanceof ActivityEdge) {
- return ((ActivityEdge) input).getInterrupts() != null;
- }
- return false;
- }
- });
- Iterable<ActivityEdge> allInterruptibleEdge = Iterables.concat(outcomingEdgeInterruptibleEdge, incomingInterruptibleEdge);
- if (!Iterables.isEmpty(allInterruptibleEdge)) {
- return allInterruptibleEdge;
- }
- }
- return null;
- }
- });
- return activityEdges;
- }
-
- @Override
- public NotificationFilter getFilter() {
- return getFEATURE_FILTER();
- }
-
- @Override
- protected ICommand getModificationCommand(Notification notif) {
- ActivityNode node = getElement(notif);
- // Get the the interruptible Edge Starting or Going from this node or its descendant
- Iterator<Iterable<ActivityEdge>> activityEdges = getActivityEdgeImpactedWithThisChange(node);
- while (activityEdges.hasNext()) {
- Iterable<ActivityEdge> interruptibleEdge = activityEdges.next();
- if (interruptibleEdge != null) {
- for (ActivityEdge interrpEdge : interruptibleEdge) {
- if (!UMLValidationHelper.validateInterruptibleEdge(interrpEdge, interrpEdge.getInterrupts())) {
- NotificationBuilder popup = new NotificationBuilder().setAsynchronous(true).setTemporary(true).setMessage("The Activity Edge " + interrpEdge.getName() + " can not interrupt its referencing region because it violates a constraint")
- .setType(Type.INFO);
- popup.run();
- return new EMFtoGMFCommandWrapper(new SetCommand(getDiagramEditPart().getEditingDomain(), interrpEdge, UMLPackage.Literals.ACTIVITY_EDGE__INTERRUPTS, null));
- }
- }
- }
- }
- return null;
- }
-
- /**
- * get the edit part registry
- *
- * @return
- */
- protected DiagramEditPart getDiagramEditPart() {
- IWorkbench wb = PlatformUI.getWorkbench();
- IWorkbenchPage page = wb.getActiveWorkbenchWindow().getActivePage();
- IEditorPart editor = page.getActiveEditor();
- if (editor instanceof IMultiDiagramEditor) {
- IMultiDiagramEditor papyrusEditor = (IMultiDiagramEditor) editor;
- return (DiagramEditPart) papyrusEditor.getAdapter(DiagramEditPart.class);
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.listeners; + +import java.util.Collections; +import java.util.Iterator; + +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.edit.command.SetCommand; +import org.eclipse.emf.transaction.NotificationFilter; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart; +import org.eclipse.papyrus.infra.emf.gmf.command.EMFtoGMFCommandWrapper; +import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.Type; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder; +import org.eclipse.papyrus.uml.diagram.activity.helper.UMLValidationHelper; +import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.uml2.uml.ActivityEdge; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.UMLPackage; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Iterators; + +/** + * Listen the {@link UMLPackage.Literals#ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION} feature in orfer to prevetn it to violate the constaint + * "Interrupting edges of a region must have their source node in the region and their target node outside the region in the same activity containing the region." + * + * @author adaussy + * + */ +public class InInterruptibleActivityRegionListener extends AbstractPapyrusModifcationTriggerListener { + + private static NotificationFilter FEATURE_FILTER = null; + + public static NotificationFilter getFEATURE_FILTER() { + if (FEATURE_FILTER == null) { + FEATURE_FILTER = NotificationFilter.createFeatureFilter(UMLPackage.Literals.ACTIVITY_NODE__IN_INTERRUPTIBLE_REGION); + } + return FEATURE_FILTER; + } + + protected ActivityNode getElement(Notification notif) { + try { + return (ActivityNode) notif.getNotifier(); + } catch (ClassCastException e) { + throw new RuntimeException("InInterruptibleActivityRegionListener should only be notified by ActivityNode"); + } + } + + /** + * Get the list of all starting or ending Interruptible Edge wich are related to this {@link ActivityNode} and its descendant. + * Those Iterable can be filled with null elements so test each element for null + * + * @param node + * @return + */ + public Iterator<Iterable<ActivityEdge>> getActivityEdgeImpactedWithThisChange(ActivityNode node) { + Iterator<Iterable<ActivityEdge>> activityEdges = Iterators.transform(Iterators.concat(Collections.singleton(node).iterator(), node.eAllContents()), new Function<EObject, Iterable<ActivityEdge>>() { + + @Override + public Iterable<ActivityEdge> apply(EObject from) { + if (from instanceof ActivityNode) { + ActivityNode activityNode = (ActivityNode) from; + Iterable<ActivityEdge> incomingInterruptibleEdge = Iterables.filter(activityNode.getIncomings(), new Predicate<EObject>() { + + @Override + public boolean apply(EObject input) { + if (input instanceof ActivityEdge) { + return ((ActivityEdge) input).getInterrupts() != null; + } + return false; + } + }); + Iterable<ActivityEdge> outcomingEdgeInterruptibleEdge = Iterables.filter(activityNode.getOutgoings(), new Predicate<EObject>() { + + @Override + public boolean apply(EObject input) { + if (input instanceof ActivityEdge) { + return ((ActivityEdge) input).getInterrupts() != null; + } + return false; + } + }); + Iterable<ActivityEdge> allInterruptibleEdge = Iterables.concat(outcomingEdgeInterruptibleEdge, incomingInterruptibleEdge); + if (!Iterables.isEmpty(allInterruptibleEdge)) { + return allInterruptibleEdge; + } + } + return null; + } + }); + return activityEdges; + } + + @Override + public NotificationFilter getFilter() { + return getFEATURE_FILTER(); + } + + @Override + protected ICommand getModificationCommand(Notification notif) { + ActivityNode node = getElement(notif); + // Get the the interruptible Edge Starting or Going from this node or its descendant + Iterator<Iterable<ActivityEdge>> activityEdges = getActivityEdgeImpactedWithThisChange(node); + while (activityEdges.hasNext()) { + Iterable<ActivityEdge> interruptibleEdge = activityEdges.next(); + if (interruptibleEdge != null) { + for (ActivityEdge interrpEdge : interruptibleEdge) { + if (!UMLValidationHelper.validateInterruptibleEdge(interrpEdge, interrpEdge.getInterrupts())) { + NotificationBuilder popup = new NotificationBuilder().setAsynchronous(true).setTemporary(true).setMessage("The Activity Edge " + interrpEdge.getName() + " can not interrupt its referencing region because it violates a constraint") + .setType(Type.INFO); + popup.run(); + return new EMFtoGMFCommandWrapper(new SetCommand(getDiagramEditPart().getEditingDomain(), interrpEdge, UMLPackage.Literals.ACTIVITY_EDGE__INTERRUPTS, null)); + } + } + } + } + return null; + } + + /** + * get the edit part registry + * + * @return + */ + protected DiagramEditPart getDiagramEditPart() { + IWorkbench wb = PlatformUI.getWorkbench(); + IWorkbenchPage page = wb.getActiveWorkbenchWindow().getActivePage(); + IEditorPart editor = page.getActiveEditor(); + if (editor instanceof IMultiDiagramEditor) { + IMultiDiagramEditor papyrusEditor = (IMultiDiagramEditor) editor; + return (DiagramEditPart) papyrusEditor.getAdapter(DiagramEditPart.class); + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/InterruptibleEdgeListener.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/InterruptibleEdgeListener.java index 1bad01311e9..539140e1b2d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/InterruptibleEdgeListener.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/InterruptibleEdgeListener.java @@ -1,295 +1,295 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.listeners;
-
-import java.util.Collection;
-import java.util.Collections;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EClass;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.emf.ecore.EStructuralFeature.Setting;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.util.ECrossReferenceAdapter;
-import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
-import org.eclipse.emf.edit.domain.EditingDomain;
-import org.eclipse.emf.transaction.NotificationFilter;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gef.commands.Command;
-import org.eclipse.gef.commands.UnexecutableCommand;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.diagram.core.services.ViewService;
-import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
-import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.gmf.runtime.notation.Node;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
-import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowInterruptibleIconEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowInterruptibleIconEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.request.InterruptibleEdgeRequest;
-import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener;
-import org.eclipse.papyrus.infra.gmfdiag.common.utils.DiagramEditPartsUtil;
-import org.eclipse.papyrus.uml.diagram.common.util.functions.EObjectToViewFunction;
-import org.eclipse.papyrus.uml.diagram.common.util.functions.SettingToEObjectFunction;
-import org.eclipse.papyrus.uml.diagram.common.util.predicates.ReferencingViewPredicate;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.uml2.uml.ActivityEdge;
-import org.eclipse.uml2.uml.UMLPackage;
-
-import com.google.common.collect.ImmutableBiMap;
-import com.google.common.collect.Iterables;
-
-/**
- * This listener handle Interruptible Edge
- *
- * @author arthur daussy
- *
- */
-public class InterruptibleEdgeListener extends AbstractPapyrusModifcationTriggerListener {
-
- /**
- * Id of all Visual ID of the interruptible Icon
- */
- private static ImmutableBiMap<EClass, String> INTERRUPTIBLE_EDGE_ICON_VISUAL_ID_COLLECTION = ImmutableBiMap.of(UMLPackage.Literals.OBJECT_FLOW, String.valueOf(ObjectFlowInterruptibleIconEditPart.VISUAL_ID), UMLPackage.Literals.CONTROL_FLOW,
- String.valueOf(ControlFlowInterruptibleIconEditPart.VISUAL_ID));
-
- private static NotificationFilter FEATURE_FILTER = null;
-
- public static NotificationFilter getFEATURE_FILTER() {
- if (FEATURE_FILTER == null) {
- FEATURE_FILTER = NotificationFilter.createFeatureFilter(UMLPackage.Literals.ACTIVITY_EDGE__INTERRUPTS);
- }
- return FEATURE_FILTER;
- }
-
- /**
- * get the edit part registry
- *
- * @return
- */
- protected DiagramEditPart getDiagramEditPart() {
- IWorkbench wb = PlatformUI.getWorkbench();
- IWorkbenchPage page = wb.getActiveWorkbenchWindow().getActivePage();
- IEditorPart editor = page.getActiveEditor();
- if (editor instanceof IMultiDiagramEditor) {
- IMultiDiagramEditor papyrusEditor = (IMultiDiagramEditor) editor;
- return (DiagramEditPart) papyrusEditor.getAdapter(DiagramEditPart.class);
- }
- return null;
- }
-
- /**
- * This command will react on a SET event of the structural feature describe in {@link InterruptibleEdgeListener#isCorrectStructuralfeature(EStructuralFeature)} This will create a new view if the newValue != null or delete
- * it if null
- */
- @Override
- protected ICommand getModificationCommand(Notification notif) {
- if (Notification.SET == notif.getEventType()) {
- CompositeCommand cc = new CompositeCommand("Interruptible Edge Command");
- // Handling views
- final Iterable<IGraphicalEditPart> edgesEditPart = DiagramEditPartsUtil.getChildrenByEObject((EObject) notif.getNotifier(), getDiagramEditPart(), true);
- InterruptibleEdgeRequest request = new InterruptibleEdgeRequest();
- Iterable<View> views = getReferencingView(notif);
- if (notif.getNewValue() != null) {
- // handle create view
- request.setType(InterruptibleEdgeRequest.SET_INTERRUPTIBLE_EDGE);
- for (View view : views) {
- try {
- String visualID = INTERRUPTIBLE_EDGE_ICON_VISUAL_ID_COLLECTION.get(view.getElement().eClass());
- ICommand createViewCommand = createInterruptibleEdgeIcon(view, visualID);
- if (createViewCommand != null && createViewCommand.canExecute()) {
- cc.compose(createViewCommand);
- }
- } catch (NullPointerException e) {
- throw new RuntimeException("Unable to find the Visual ID of the Icon of the interruptible Edge for element" + view.getElement()); //$NON-NLS-1$
- }
- }
- } else {
- // handle delete view
- request.setType(InterruptibleEdgeRequest.UNSET_INTERRUPTIBLE_EDGE);
- for (View view : views) {
- try {
- String visualID = INTERRUPTIBLE_EDGE_ICON_VISUAL_ID_COLLECTION.get(view.getElement().eClass());
- ICommand destroyCommand = destroyInterruptibleIcon(view, visualID);
- if (destroyCommand != null && destroyCommand.canExecute()) {
- cc.compose(destroyCommand);
- }
- } catch (NullPointerException e) {
- throw new RuntimeException("Unable to find the Visual ID of the Icon of the interruptible Edge for element" + view.getElement());
- }
- }
- }
- for (IGraphicalEditPart edgeEditPart : edgesEditPart) {
- if (edgeEditPart != null && edgeEditPart instanceof InterruptibleEdge && edgeEditPart.getModel() instanceof View) {
- // Ask for the edit if something more else has to be done
- Command command = edgeEditPart.getCommand(request);
- if (command != null && command.canExecute()) {
- cc.compose(new CommandProxy(command));
- }
- }
- }
- return cc;
- }
- return null;
- }
-
- /**
- * Get all the view from Notation Model which represent the notifier.
- * Will only return the view of the same type than the notifier view
- *
- * @param notif
- * @param edgeEditPart
- * @return
- */
- public Iterable<View> getReferencingView(Notification notif) {
- final ActivityEdge element = getElement(notif);
- Resource eResource = element.eResource();
- if (eResource != null) {
- ECrossReferenceAdapter adapter = ECrossReferenceAdapter.getCrossReferenceAdapter(eResource.getResourceSet());
- if (adapter == null) {
- adapter = new ECrossReferenceAdapter();
- }
- Collection<Setting> inverseReferences = adapter.getInverseReferences(element);
- Iterable<EObject> settings = Iterables.transform(inverseReferences, new SettingToEObjectFunction());
- Iterable<EObject> eObjects = Iterables.filter(settings, new ReferencingViewPredicate(element));
- Iterable<View> views = Iterables.transform(eObjects, new EObjectToViewFunction());
- return views;
- }
- return Collections.emptyList();
- }
-
- private TransactionalEditingDomain getEditingDomain(View model) {
- DiagramEditPart diagramEditPart = getDiagramEditPart();
- if (diagramEditPart != null) {
- return diagramEditPart.getEditingDomain();
- }
- EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(model);
- if (editingDomain instanceof TransactionalEditingDomain) {
- return (TransactionalEditingDomain) editingDomain;
- }
- return null;
- }
-
- /**
- * Create the command to withdraw interruptible edge icon from the activity edge
- *
- * @return
- */
- private ICommand destroyInterruptibleIcon(final View model, final String visualID) {
- TransactionalEditingDomain editingDomain = getEditingDomain(model);
- if (editingDomain != null) {
- AbstractTransactionalCommand cmd = new AbstractTransactionalCommand(editingDomain, "Destroy Interruptible Edge Icon", null) {
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- if (model != null) {
- View interruptibleEdgeIconView = ViewUtil.getChildBySemanticHint(model, visualID);
- ViewUtil.destroy(interruptibleEdgeIconView);
- return CommandResult.newOKCommandResult();
- }
- return null;
- }
- };
- return cmd;
- }
- return null;
- }
-
- /**
- * Create the Interruptible Edge Icon View
- *
- * @return Command to be executed or {@link UnexecutableCommand#INSTANCE} if unable to create
- */
- private ICommand createInterruptibleEdgeIcon(final View model, final String visualID) {
- TransactionalEditingDomain editingDomain = getEditingDomain(model);
- if (editingDomain != null) {
- AbstractTransactionalCommand cmd = new AbstractTransactionalCommand(editingDomain, "Create Interruptible Edge Icon", null) {
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- if (model != null) {
- Node node = ViewService.createNode(model, visualID, UMLDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);
- if (node != null) {
- return CommandResult.newOKCommandResult(node);
- } else {
- return CommandResult.newErrorCommandResult("Unable to create the view for Interruptible Edge label");
- }
- }
- return null;
- }
-
- /*
- * TODO test if needed
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doUndo(org.eclipse.core.runtime.IProgressMonitor,
- * org.eclipse.core.runtime.IAdaptable)
- */
- @Override
- protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- IStatus status = super.doUndo(monitor, info);
- getDiagramEditPart().refresh();
- return status;
- }
-
- /*
- * TODO test if needed
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doUndo(org.eclipse.core.runtime.IProgressMonitor,
- * org.eclipse.core.runtime.IAdaptable)
- */
- @Override
- protected IStatus doRedo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- IStatus status = super.doRedo(monitor, info);
- getDiagramEditPart().refresh();
- return status;
- }
- };
- return cmd;
- }
- return null;
- }
-
- protected ActivityEdge getElement(Notification notif) {
- Object element = notif.getNotifier();
- if (element instanceof ActivityEdge) {
- return (ActivityEdge) element;
- }
- return null;
- }
-
- @Override
- public NotificationFilter getFilter() {
- return getFEATURE_FILTER();
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.listeners; + +import java.util.Collection; +import java.util.Collections; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.EStructuralFeature.Setting; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.util.ECrossReferenceAdapter; +import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; +import org.eclipse.emf.edit.domain.EditingDomain; +import org.eclipse.emf.transaction.NotificationFilter; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gef.commands.Command; +import org.eclipse.gef.commands.UnexecutableCommand; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.diagram.core.services.ViewService; +import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil; +import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.gmf.runtime.notation.Node; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor; +import org.eclipse.papyrus.uml.diagram.activity.edit.part.interfaces.InterruptibleEdge; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ControlFlowInterruptibleIconEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ObjectFlowInterruptibleIconEditPart; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.request.InterruptibleEdgeRequest; +import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener; +import org.eclipse.papyrus.infra.gmfdiag.common.utils.DiagramEditPartsUtil; +import org.eclipse.papyrus.uml.diagram.common.util.functions.EObjectToViewFunction; +import org.eclipse.papyrus.uml.diagram.common.util.functions.SettingToEObjectFunction; +import org.eclipse.papyrus.uml.diagram.common.util.predicates.ReferencingViewPredicate; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.PlatformUI; +import org.eclipse.uml2.uml.ActivityEdge; +import org.eclipse.uml2.uml.UMLPackage; + +import com.google.common.collect.ImmutableBiMap; +import com.google.common.collect.Iterables; + +/** + * This listener handle Interruptible Edge + * + * @author arthur daussy + * + */ +public class InterruptibleEdgeListener extends AbstractPapyrusModifcationTriggerListener { + + /** + * Id of all Visual ID of the interruptible Icon + */ + private static ImmutableBiMap<EClass, String> INTERRUPTIBLE_EDGE_ICON_VISUAL_ID_COLLECTION = ImmutableBiMap.of(UMLPackage.Literals.OBJECT_FLOW, String.valueOf(ObjectFlowInterruptibleIconEditPart.VISUAL_ID), UMLPackage.Literals.CONTROL_FLOW, + String.valueOf(ControlFlowInterruptibleIconEditPart.VISUAL_ID)); + + private static NotificationFilter FEATURE_FILTER = null; + + public static NotificationFilter getFEATURE_FILTER() { + if (FEATURE_FILTER == null) { + FEATURE_FILTER = NotificationFilter.createFeatureFilter(UMLPackage.Literals.ACTIVITY_EDGE__INTERRUPTS); + } + return FEATURE_FILTER; + } + + /** + * get the edit part registry + * + * @return + */ + protected DiagramEditPart getDiagramEditPart() { + IWorkbench wb = PlatformUI.getWorkbench(); + IWorkbenchPage page = wb.getActiveWorkbenchWindow().getActivePage(); + IEditorPart editor = page.getActiveEditor(); + if (editor instanceof IMultiDiagramEditor) { + IMultiDiagramEditor papyrusEditor = (IMultiDiagramEditor) editor; + return (DiagramEditPart) papyrusEditor.getAdapter(DiagramEditPart.class); + } + return null; + } + + /** + * This command will react on a SET event of the structural feature describe in {@link InterruptibleEdgeListener#isCorrectStructuralfeature(EStructuralFeature)} This will create a new view if the newValue != null or delete + * it if null + */ + @Override + protected ICommand getModificationCommand(Notification notif) { + if (Notification.SET == notif.getEventType()) { + CompositeCommand cc = new CompositeCommand("Interruptible Edge Command"); + // Handling views + final Iterable<IGraphicalEditPart> edgesEditPart = DiagramEditPartsUtil.getChildrenByEObject((EObject) notif.getNotifier(), getDiagramEditPart(), true); + InterruptibleEdgeRequest request = new InterruptibleEdgeRequest(); + Iterable<View> views = getReferencingView(notif); + if (notif.getNewValue() != null) { + // handle create view + request.setType(InterruptibleEdgeRequest.SET_INTERRUPTIBLE_EDGE); + for (View view : views) { + try { + String visualID = INTERRUPTIBLE_EDGE_ICON_VISUAL_ID_COLLECTION.get(view.getElement().eClass()); + ICommand createViewCommand = createInterruptibleEdgeIcon(view, visualID); + if (createViewCommand != null && createViewCommand.canExecute()) { + cc.compose(createViewCommand); + } + } catch (NullPointerException e) { + throw new RuntimeException("Unable to find the Visual ID of the Icon of the interruptible Edge for element" + view.getElement()); //$NON-NLS-1$ + } + } + } else { + // handle delete view + request.setType(InterruptibleEdgeRequest.UNSET_INTERRUPTIBLE_EDGE); + for (View view : views) { + try { + String visualID = INTERRUPTIBLE_EDGE_ICON_VISUAL_ID_COLLECTION.get(view.getElement().eClass()); + ICommand destroyCommand = destroyInterruptibleIcon(view, visualID); + if (destroyCommand != null && destroyCommand.canExecute()) { + cc.compose(destroyCommand); + } + } catch (NullPointerException e) { + throw new RuntimeException("Unable to find the Visual ID of the Icon of the interruptible Edge for element" + view.getElement()); + } + } + } + for (IGraphicalEditPart edgeEditPart : edgesEditPart) { + if (edgeEditPart != null && edgeEditPart instanceof InterruptibleEdge && edgeEditPart.getModel() instanceof View) { + // Ask for the edit if something more else has to be done + Command command = edgeEditPart.getCommand(request); + if (command != null && command.canExecute()) { + cc.compose(new CommandProxy(command)); + } + } + } + return cc; + } + return null; + } + + /** + * Get all the view from Notation Model which represent the notifier. + * Will only return the view of the same type than the notifier view + * + * @param notif + * @param edgeEditPart + * @return + */ + public Iterable<View> getReferencingView(Notification notif) { + final ActivityEdge element = getElement(notif); + Resource eResource = element.eResource(); + if (eResource != null) { + ECrossReferenceAdapter adapter = ECrossReferenceAdapter.getCrossReferenceAdapter(eResource.getResourceSet()); + if (adapter == null) { + adapter = new ECrossReferenceAdapter(); + } + Collection<Setting> inverseReferences = adapter.getInverseReferences(element); + Iterable<EObject> settings = Iterables.transform(inverseReferences, new SettingToEObjectFunction()); + Iterable<EObject> eObjects = Iterables.filter(settings, new ReferencingViewPredicate(element)); + Iterable<View> views = Iterables.transform(eObjects, new EObjectToViewFunction()); + return views; + } + return Collections.emptyList(); + } + + private TransactionalEditingDomain getEditingDomain(View model) { + DiagramEditPart diagramEditPart = getDiagramEditPart(); + if (diagramEditPart != null) { + return diagramEditPart.getEditingDomain(); + } + EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(model); + if (editingDomain instanceof TransactionalEditingDomain) { + return (TransactionalEditingDomain) editingDomain; + } + return null; + } + + /** + * Create the command to withdraw interruptible edge icon from the activity edge + * + * @return + */ + private ICommand destroyInterruptibleIcon(final View model, final String visualID) { + TransactionalEditingDomain editingDomain = getEditingDomain(model); + if (editingDomain != null) { + AbstractTransactionalCommand cmd = new AbstractTransactionalCommand(editingDomain, "Destroy Interruptible Edge Icon", null) { + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + if (model != null) { + View interruptibleEdgeIconView = ViewUtil.getChildBySemanticHint(model, visualID); + ViewUtil.destroy(interruptibleEdgeIconView); + return CommandResult.newOKCommandResult(); + } + return null; + } + }; + return cmd; + } + return null; + } + + /** + * Create the Interruptible Edge Icon View + * + * @return Command to be executed or {@link UnexecutableCommand#INSTANCE} if unable to create + */ + private ICommand createInterruptibleEdgeIcon(final View model, final String visualID) { + TransactionalEditingDomain editingDomain = getEditingDomain(model); + if (editingDomain != null) { + AbstractTransactionalCommand cmd = new AbstractTransactionalCommand(editingDomain, "Create Interruptible Edge Icon", null) { + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + if (model != null) { + Node node = ViewService.createNode(model, visualID, UMLDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT); + if (node != null) { + return CommandResult.newOKCommandResult(node); + } else { + return CommandResult.newErrorCommandResult("Unable to create the view for Interruptible Edge label"); + } + } + return null; + } + + /* + * TODO test if needed + * (non-Javadoc) + * + * @see + * org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doUndo(org.eclipse.core.runtime.IProgressMonitor, + * org.eclipse.core.runtime.IAdaptable) + */ + @Override + protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + IStatus status = super.doUndo(monitor, info); + getDiagramEditPart().refresh(); + return status; + } + + /* + * TODO test if needed + * (non-Javadoc) + * + * @see + * org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doUndo(org.eclipse.core.runtime.IProgressMonitor, + * org.eclipse.core.runtime.IAdaptable) + */ + @Override + protected IStatus doRedo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + IStatus status = super.doRedo(monitor, info); + getDiagramEditPart().refresh(); + return status; + } + }; + return cmd; + } + return null; + } + + protected ActivityEdge getElement(Notification notif) { + Object element = notif.getNotifier(); + if (element instanceof ActivityEdge) { + return (ActivityEdge) element; + } + return null; + } + + @Override + public NotificationFilter getFilter() { + return getFEATURE_FILTER(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ObjectFlowListener.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ObjectFlowListener.java index 661c76396e1..a54d8e8266c 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ObjectFlowListener.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ObjectFlowListener.java @@ -1,64 +1,64 @@ -/*****************************************************************************
- * Copyright (c) 2012 Atos.
- *
- *
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.listeners;
-
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.edit.command.SetCommand;
-import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
-import org.eclipse.emf.transaction.NotificationFilter;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.papyrus.infra.emf.gmf.command.EMFtoGMFCommandWrapper;
-import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener;
-import org.eclipse.uml2.uml.LiteralBoolean;
-import org.eclipse.uml2.uml.LiteralInteger;
-import org.eclipse.uml2.uml.ObjectFlow;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * @author tfaure
- *
- */
-public class ObjectFlowListener extends AbstractPapyrusModifcationTriggerListener {
-
- @Override
- public NotificationFilter getFilter() {
- // AN EDGE is contained only in activities and structured
- NotificationFilter filter1 = NotificationFilter.createEventTypeFilter(Notification.ADD).and(NotificationFilter.createNotifierTypeFilter(UMLPackage.Literals.STRUCTURED_ACTIVITY_NODE));
- return filter1.or(NotificationFilter.createEventTypeFilter(Notification.ADD).and(NotificationFilter.createNotifierTypeFilter(UMLPackage.Literals.ACTIVITY)));
- }
-
- @Override
- protected CompositeCommand getModificationCommand(Notification notif) {
- CompositeCommand cc = null;
- if (notif.getNewValue() instanceof ObjectFlow && notif.getFeature() instanceof EReference && ((EReference) notif.getFeature()).isContainment()) {
- cc = new CompositeCommand("Modify Flow");
- final ObjectFlow object = (ObjectFlow) notif.getNewValue();
- TransactionalEditingDomain domain = (TransactionalEditingDomain) AdapterFactoryEditingDomain.getEditingDomainFor(object);
- if (object.getGuard() == null) {
- LiteralBoolean bool = UMLFactory.eINSTANCE.createLiteralBoolean();
- bool.setValue(true);
- cc.compose(new EMFtoGMFCommandWrapper(SetCommand.create(domain, object, UMLPackage.Literals.ACTIVITY_EDGE__GUARD, bool)));
- }
- if (object.getWeight() == null) {
- LiteralInteger literalInteger = UMLFactory.eINSTANCE.createLiteralInteger();
- literalInteger.setValue(1);
- cc.compose(new EMFtoGMFCommandWrapper(SetCommand.create(domain, object, UMLPackage.Literals.ACTIVITY_EDGE__WEIGHT, literalInteger)));
- }
- }
- return cc;
- }
-}
+/***************************************************************************** + * Copyright (c) 2012 Atos. + * + * + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.listeners; + +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.edit.command.SetCommand; +import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; +import org.eclipse.emf.transaction.NotificationFilter; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.papyrus.infra.emf.gmf.command.EMFtoGMFCommandWrapper; +import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener; +import org.eclipse.uml2.uml.LiteralBoolean; +import org.eclipse.uml2.uml.LiteralInteger; +import org.eclipse.uml2.uml.ObjectFlow; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * @author tfaure + * + */ +public class ObjectFlowListener extends AbstractPapyrusModifcationTriggerListener { + + @Override + public NotificationFilter getFilter() { + // AN EDGE is contained only in activities and structured + NotificationFilter filter1 = NotificationFilter.createEventTypeFilter(Notification.ADD).and(NotificationFilter.createNotifierTypeFilter(UMLPackage.Literals.STRUCTURED_ACTIVITY_NODE)); + return filter1.or(NotificationFilter.createEventTypeFilter(Notification.ADD).and(NotificationFilter.createNotifierTypeFilter(UMLPackage.Literals.ACTIVITY))); + } + + @Override + protected CompositeCommand getModificationCommand(Notification notif) { + CompositeCommand cc = null; + if (notif.getNewValue() instanceof ObjectFlow && notif.getFeature() instanceof EReference && ((EReference) notif.getFeature()).isContainment()) { + cc = new CompositeCommand("Modify Flow"); + final ObjectFlow object = (ObjectFlow) notif.getNewValue(); + TransactionalEditingDomain domain = (TransactionalEditingDomain) AdapterFactoryEditingDomain.getEditingDomainFor(object); + if (object.getGuard() == null) { + LiteralBoolean bool = UMLFactory.eINSTANCE.createLiteralBoolean(); + bool.setValue(true); + cc.compose(new EMFtoGMFCommandWrapper(SetCommand.create(domain, object, UMLPackage.Literals.ACTIVITY_EDGE__GUARD, bool))); + } + if (object.getWeight() == null) { + LiteralInteger literalInteger = UMLFactory.eINSTANCE.createLiteralInteger(); + literalInteger.setValue(1); + cc.compose(new EMFtoGMFCommandWrapper(SetCommand.create(domain, object, UMLPackage.Literals.ACTIVITY_EDGE__WEIGHT, literalInteger))); + } + } + return cc; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ObjectNodeListener.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ObjectNodeListener.java index c5002befb06..a2badab80be 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ObjectNodeListener.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/listeners/ObjectNodeListener.java @@ -1,56 +1,56 @@ -/*****************************************************************************
- * Copyright (c) 2012 Atos.
- *
- *
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.listeners;
-
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EReference;
-import org.eclipse.emf.edit.command.SetCommand;
-import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
-import org.eclipse.emf.transaction.NotificationFilter;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.papyrus.infra.emf.gmf.command.EMFtoGMFCommandWrapper;
-import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener;
-import org.eclipse.uml2.uml.LiteralInteger;
-import org.eclipse.uml2.uml.ObjectNode;
-import org.eclipse.uml2.uml.UMLFactory;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * @author tfaure
- *
- */
-public class ObjectNodeListener extends AbstractPapyrusModifcationTriggerListener {
-
- @Override
- public NotificationFilter getFilter() {
- // an object node is contained only in actions and activities
- NotificationFilter filter1 = NotificationFilter.createEventTypeFilter(Notification.ADD).and(NotificationFilter.createNotifierTypeFilter(UMLPackage.Literals.ACTION));
- return filter1.or(NotificationFilter.createEventTypeFilter(Notification.ADD).and(NotificationFilter.createNotifierTypeFilter(UMLPackage.Literals.ACTIVITY)));
- }
-
- @Override
- protected CompositeCommand getModificationCommand(Notification notif) {
- CompositeCommand cc = null;
- if (notif.getNewValue() instanceof ObjectNode && notif.getFeature() instanceof EReference && ((EReference) notif.getFeature()).isContainment()) {
- cc = new CompositeCommand("Modify Pin");
- final ObjectNode object = (ObjectNode) notif.getNewValue();
- if (object.getUpperBound() == null && AdapterFactoryEditingDomain.getEditingDomainFor(object) != null) {
- LiteralInteger literalInteger = UMLFactory.eINSTANCE.createLiteralInteger();
- literalInteger.setValue(1);
- cc.compose(new EMFtoGMFCommandWrapper(SetCommand.create(AdapterFactoryEditingDomain.getEditingDomainFor(object), object, UMLPackage.Literals.OBJECT_NODE__UPPER_BOUND, literalInteger)));
- }
- }
- return cc;
- }
-}
+/***************************************************************************** + * Copyright (c) 2012 Atos. + * + * + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.listeners; + +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.edit.command.SetCommand; +import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; +import org.eclipse.emf.transaction.NotificationFilter; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.papyrus.infra.emf.gmf.command.EMFtoGMFCommandWrapper; +import org.eclipse.papyrus.uml.diagram.common.listeners.AbstractPapyrusModifcationTriggerListener; +import org.eclipse.uml2.uml.LiteralInteger; +import org.eclipse.uml2.uml.ObjectNode; +import org.eclipse.uml2.uml.UMLFactory; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * @author tfaure + * + */ +public class ObjectNodeListener extends AbstractPapyrusModifcationTriggerListener { + + @Override + public NotificationFilter getFilter() { + // an object node is contained only in actions and activities + NotificationFilter filter1 = NotificationFilter.createEventTypeFilter(Notification.ADD).and(NotificationFilter.createNotifierTypeFilter(UMLPackage.Literals.ACTION)); + return filter1.or(NotificationFilter.createEventTypeFilter(Notification.ADD).and(NotificationFilter.createNotifierTypeFilter(UMLPackage.Literals.ACTIVITY))); + } + + @Override + protected CompositeCommand getModificationCommand(Notification notif) { + CompositeCommand cc = null; + if (notif.getNewValue() instanceof ObjectNode && notif.getFeature() instanceof EReference && ((EReference) notif.getFeature()).isContainment()) { + cc = new CompositeCommand("Modify Pin"); + final ObjectNode object = (ObjectNode) notif.getNewValue(); + if (object.getUpperBound() == null && AdapterFactoryEditingDomain.getEditingDomainFor(object) != null) { + LiteralInteger literalInteger = UMLFactory.eINSTANCE.createLiteralInteger(); + literalInteger.setValue(1); + cc.compose(new EMFtoGMFCommandWrapper(SetCommand.create(AdapterFactoryEditingDomain.getEditingDomainFor(object), object, UMLPackage.Literals.OBJECT_NODE__UPPER_BOUND, literalInteger))); + } + } + return cc; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/ActivityParameterNodePositionLocator.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/ActivityParameterNodePositionLocator.java index 6b060b57f71..14591618734 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/ActivityParameterNodePositionLocator.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/ActivityParameterNodePositionLocator.java @@ -1,245 +1,245 @@ -/*****************************************************************************
- * 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:
- * Emilien Perico (Atos Origin) emilien.perico@atosorigin.com - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.locator;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.PositionConstants;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator;
-import org.eclipse.papyrus.uml.diagram.common.locator.AdvancedBorderItemLocator;
-import org.eclipse.papyrus.uml.diagram.common.locator.ISideAffixedNodeBorderItemLocator;
-
-public class ActivityParameterNodePositionLocator extends AdvancedBorderItemLocator implements ISideAffixedNodeBorderItemLocator {
-
- /**
- * The offset to add to default position. (to avoid corner of rounded
- * rectangles)
- */
- public static final int EXTRA_BORDER_DEFAULT_OFFSET = 8;
-
- /** The default size of a pin */
- public static final int DEFAULT_PIN_SIZE = 16;
-
- protected int borderItemOffset = 10;
-
- /** Constructor **/
- public ActivityParameterNodePositionLocator(IFigure parentFigure) {
- super(parentFigure);
- }
-
- /** Constructor **/
- public ActivityParameterNodePositionLocator(IFigure borderItem, IFigure parentFigure, Rectangle constraint) {
- super(borderItem, parentFigure, constraint);
- }
-
- /** Constructor **/
- public ActivityParameterNodePositionLocator(IFigure parentFigure, int preferredSide) {
- super(parentFigure, preferredSide);
- }
-
- @Override
- public Rectangle getValidLocation(Rectangle proposedLocation, IFigure borderItem) {
-
- Rectangle realLocation = new Rectangle(proposedLocation);
-
- if (realLocation.width < DEFAULT_PIN_SIZE) {
- realLocation.setWidth(DEFAULT_PIN_SIZE);
- }
- if (realLocation.height < DEFAULT_PIN_SIZE) {
- realLocation.setHeight(DEFAULT_PIN_SIZE);
- }
-
- int side = findClosestSideOfParent(proposedLocation, getParentBorder());
- Point newTopLeft = locateOnBorder(realLocation.getTopLeft(), side, 0, borderItem);
- realLocation.setLocation(newTopLeft);
- return realLocation;
- }
-
- /**
- * Find the closest side when x,y is inside parent.
- *
- * @param proposedLocation
- * @param parentBorder
- * @return draw constant
- */
- public static int findClosestSideOfParent(Rectangle proposedLocation, Rectangle parentBorder) {
-
- int side = BorderItemLocator.findClosestSideOfParent(proposedLocation, parentBorder);
-
- // relocate side for North
- if (side == PositionConstants.NORTH) {
- Point parentCenter = parentBorder.getCenter();
- Point childCenter = proposedLocation.getCenter();
- if (childCenter.x < parentCenter.x) {
- return PositionConstants.WEST;
- } else {
- return PositionConstants.EAST;
- }
- }
- return side;
- }
-
- /**
- * Ensure the suggested location actually lies on the parent boundary. The
- * side takes precedence.
- *
- * @param suggestedLocation
- * @param suggestedSide
- * @return point
- */
- @Override
- protected Point locateOnParent(Point suggestedLocation, int suggestedSide, IFigure borderItem) {
-
- Rectangle parent = getParentBorder();
- Dimension borderItemSize = borderItem.getSize();
- int newX = suggestedLocation.x;
- int newY = suggestedLocation.y;
-
- // default position is WEST
- // set fixed coordinate
- switch (suggestedSide) {
-
- case PositionConstants.NORTH:
- int northY = parent.y() - borderItemSize.height / 2;
- if (suggestedLocation.y != northY) {
- newY = northY;
- }
- break;
- case PositionConstants.SOUTH:
- int southY = parent.bottom() - borderItemSize.height / 2;
- if (suggestedLocation.y != southY) {
- newY = southY;
- }
- break;
- case PositionConstants.EAST:
- int eastX = parent.right() - borderItemSize.width / 2;
- if (suggestedLocation.x != eastX) {
- newX = eastX;
- }
- break;
- case PositionConstants.WEST:
- default:
- int westX = parent.x() - borderItemSize.width / 2;
- if (suggestedLocation.x != westX) {
- newX = westX;
- }
- break;
- }
-
- /* set moving coordinate */
- switch (suggestedSide) {
- case PositionConstants.NORTH:
- case PositionConstants.SOUTH:
- if (suggestedLocation.x < parent.x() + EXTRA_BORDER_DEFAULT_OFFSET) {
- newX = parent.x() + EXTRA_BORDER_DEFAULT_OFFSET;
- } else if (suggestedLocation.x + borderItemSize.width > parent.getBottomRight().x - EXTRA_BORDER_DEFAULT_OFFSET) {
- newX = parent.getBottomRight().x - EXTRA_BORDER_DEFAULT_OFFSET - borderItemSize.width;
- }
- break;
- case PositionConstants.EAST:
- case PositionConstants.WEST:
- default:
- if (suggestedLocation.y < parent.y() + EXTRA_BORDER_DEFAULT_OFFSET) {
- newY = parent.y() + EXTRA_BORDER_DEFAULT_OFFSET;
- } else if (suggestedLocation.y + borderItemSize.height > parent.getBottomLeft().y - EXTRA_BORDER_DEFAULT_OFFSET) {
- newY = parent.getBottomLeft().y - EXTRA_BORDER_DEFAULT_OFFSET - borderItemSize.height;
- }
- break;
- }
-
- return new Point(newX, newY);
- }
-
- @Override
- public void relocate(IFigure borderItem) {
-
- // reset bounds of borderItem
- Dimension size = getSize(borderItem);
- Rectangle rectSuggested = getConstraint().getCopy();
- if (rectSuggested.getTopLeft().x == 0 && rectSuggested.getTopLeft().y == 0) {
- rectSuggested.setLocation(getPreferredLocation(borderItem));
- } else {
- // recovered constraint must be translated with the parent location
- // to be absolute
- rectSuggested.setLocation(rectSuggested.getLocation().translate(getParentBorder().getTopLeft()));
- }
- rectSuggested.setSize(size);
- Rectangle validLocation = getValidLocation(rectSuggested, borderItem);
- // the constraint is not reset, but the item bounds are
- borderItem.setBounds(validLocation);
- // ensure the side property is correctly set
- setCurrentSideOfParent(findClosestSideOfParent(borderItem.getBounds(), getParentBorder()));
- }
-
- /**
- *
- * @param proposedLocation
- * the proposed location
- * @return a possible location on parent figure border
- */
- @Override
- public Rectangle getPreferredLocation(Rectangle proposedLocation) {
- // Initialize port location with proposed location
- // and resolve the bounds of it graphical parent
- Rectangle realLocation = new Rectangle(proposedLocation);
- Rectangle parentRec = getParentFigure().getBounds().getCopy();
- // Calculate Max position around the graphical parent (1/2 size or the
- // port around
- // the graphical parent bounds.
- int xMin = parentRec.x + borderItemOffset;
- int xMax = parentRec.x + parentRec.width - borderItemOffset;
- int yMin = parentRec.y + borderItemOffset;
- int yMax = parentRec.y + parentRec.height - borderItemOffset;
- // Modify Port location if MAX X or Y are exceeded
- if (realLocation.x < xMin) {
- realLocation.x = xMin;
- }
- if (realLocation.x > xMax) {
- realLocation.x = xMax;
- }
- if (realLocation.y < yMin) {
- realLocation.y = yMin;
- }
- if (realLocation.y > yMax) {
- realLocation.y = yMax;
- }
- // Ensure the port is positioned on its parent borders and not in the
- // middle.
- // Modify position if needed.
- if ((realLocation.y != yMin) && (realLocation.y != yMax)) {
- if ((realLocation.x != xMin) && (realLocation.x != xMax)) {
- int preferedSide = findClosestSideOfParent(realLocation, parentRec);
- switch (preferedSide) {
- case PositionConstants.NORTH:
- realLocation.y = yMin;
- break;
- case PositionConstants.SOUTH:
- realLocation.y = yMax;
- break;
- case PositionConstants.WEST:
- realLocation.x = xMin;
- break;
- case PositionConstants.EAST:
- default:
- realLocation.x = xMax;
- break;
- }
- }
- }
- // Return constrained location
- return realLocation;
- }
-}
+/***************************************************************************** + * 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: + * Emilien Perico (Atos Origin) emilien.perico@atosorigin.com - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.locator; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator; +import org.eclipse.papyrus.uml.diagram.common.locator.AdvancedBorderItemLocator; +import org.eclipse.papyrus.uml.diagram.common.locator.ISideAffixedNodeBorderItemLocator; + +public class ActivityParameterNodePositionLocator extends AdvancedBorderItemLocator implements ISideAffixedNodeBorderItemLocator { + + /** + * The offset to add to default position. (to avoid corner of rounded + * rectangles) + */ + public static final int EXTRA_BORDER_DEFAULT_OFFSET = 8; + + /** The default size of a pin */ + public static final int DEFAULT_PIN_SIZE = 16; + + protected int borderItemOffset = 10; + + /** Constructor **/ + public ActivityParameterNodePositionLocator(IFigure parentFigure) { + super(parentFigure); + } + + /** Constructor **/ + public ActivityParameterNodePositionLocator(IFigure borderItem, IFigure parentFigure, Rectangle constraint) { + super(borderItem, parentFigure, constraint); + } + + /** Constructor **/ + public ActivityParameterNodePositionLocator(IFigure parentFigure, int preferredSide) { + super(parentFigure, preferredSide); + } + + @Override + public Rectangle getValidLocation(Rectangle proposedLocation, IFigure borderItem) { + + Rectangle realLocation = new Rectangle(proposedLocation); + + if (realLocation.width < DEFAULT_PIN_SIZE) { + realLocation.setWidth(DEFAULT_PIN_SIZE); + } + if (realLocation.height < DEFAULT_PIN_SIZE) { + realLocation.setHeight(DEFAULT_PIN_SIZE); + } + + int side = findClosestSideOfParent(proposedLocation, getParentBorder()); + Point newTopLeft = locateOnBorder(realLocation.getTopLeft(), side, 0, borderItem); + realLocation.setLocation(newTopLeft); + return realLocation; + } + + /** + * Find the closest side when x,y is inside parent. + * + * @param proposedLocation + * @param parentBorder + * @return draw constant + */ + public static int findClosestSideOfParent(Rectangle proposedLocation, Rectangle parentBorder) { + + int side = BorderItemLocator.findClosestSideOfParent(proposedLocation, parentBorder); + + // relocate side for North + if (side == PositionConstants.NORTH) { + Point parentCenter = parentBorder.getCenter(); + Point childCenter = proposedLocation.getCenter(); + if (childCenter.x < parentCenter.x) { + return PositionConstants.WEST; + } else { + return PositionConstants.EAST; + } + } + return side; + } + + /** + * Ensure the suggested location actually lies on the parent boundary. The + * side takes precedence. + * + * @param suggestedLocation + * @param suggestedSide + * @return point + */ + @Override + protected Point locateOnParent(Point suggestedLocation, int suggestedSide, IFigure borderItem) { + + Rectangle parent = getParentBorder(); + Dimension borderItemSize = borderItem.getSize(); + int newX = suggestedLocation.x; + int newY = suggestedLocation.y; + + // default position is WEST + // set fixed coordinate + switch (suggestedSide) { + + case PositionConstants.NORTH: + int northY = parent.y() - borderItemSize.height / 2; + if (suggestedLocation.y != northY) { + newY = northY; + } + break; + case PositionConstants.SOUTH: + int southY = parent.bottom() - borderItemSize.height / 2; + if (suggestedLocation.y != southY) { + newY = southY; + } + break; + case PositionConstants.EAST: + int eastX = parent.right() - borderItemSize.width / 2; + if (suggestedLocation.x != eastX) { + newX = eastX; + } + break; + case PositionConstants.WEST: + default: + int westX = parent.x() - borderItemSize.width / 2; + if (suggestedLocation.x != westX) { + newX = westX; + } + break; + } + + /* set moving coordinate */ + switch (suggestedSide) { + case PositionConstants.NORTH: + case PositionConstants.SOUTH: + if (suggestedLocation.x < parent.x() + EXTRA_BORDER_DEFAULT_OFFSET) { + newX = parent.x() + EXTRA_BORDER_DEFAULT_OFFSET; + } else if (suggestedLocation.x + borderItemSize.width > parent.getBottomRight().x - EXTRA_BORDER_DEFAULT_OFFSET) { + newX = parent.getBottomRight().x - EXTRA_BORDER_DEFAULT_OFFSET - borderItemSize.width; + } + break; + case PositionConstants.EAST: + case PositionConstants.WEST: + default: + if (suggestedLocation.y < parent.y() + EXTRA_BORDER_DEFAULT_OFFSET) { + newY = parent.y() + EXTRA_BORDER_DEFAULT_OFFSET; + } else if (suggestedLocation.y + borderItemSize.height > parent.getBottomLeft().y - EXTRA_BORDER_DEFAULT_OFFSET) { + newY = parent.getBottomLeft().y - EXTRA_BORDER_DEFAULT_OFFSET - borderItemSize.height; + } + break; + } + + return new Point(newX, newY); + } + + @Override + public void relocate(IFigure borderItem) { + + // reset bounds of borderItem + Dimension size = getSize(borderItem); + Rectangle rectSuggested = getConstraint().getCopy(); + if (rectSuggested.getTopLeft().x == 0 && rectSuggested.getTopLeft().y == 0) { + rectSuggested.setLocation(getPreferredLocation(borderItem)); + } else { + // recovered constraint must be translated with the parent location + // to be absolute + rectSuggested.setLocation(rectSuggested.getLocation().translate(getParentBorder().getTopLeft())); + } + rectSuggested.setSize(size); + Rectangle validLocation = getValidLocation(rectSuggested, borderItem); + // the constraint is not reset, but the item bounds are + borderItem.setBounds(validLocation); + // ensure the side property is correctly set + setCurrentSideOfParent(findClosestSideOfParent(borderItem.getBounds(), getParentBorder())); + } + + /** + * + * @param proposedLocation + * the proposed location + * @return a possible location on parent figure border + */ + @Override + public Rectangle getPreferredLocation(Rectangle proposedLocation) { + // Initialize port location with proposed location + // and resolve the bounds of it graphical parent + Rectangle realLocation = new Rectangle(proposedLocation); + Rectangle parentRec = getParentFigure().getBounds().getCopy(); + // Calculate Max position around the graphical parent (1/2 size or the + // port around + // the graphical parent bounds. + int xMin = parentRec.x + borderItemOffset; + int xMax = parentRec.x + parentRec.width - borderItemOffset; + int yMin = parentRec.y + borderItemOffset; + int yMax = parentRec.y + parentRec.height - borderItemOffset; + // Modify Port location if MAX X or Y are exceeded + if (realLocation.x < xMin) { + realLocation.x = xMin; + } + if (realLocation.x > xMax) { + realLocation.x = xMax; + } + if (realLocation.y < yMin) { + realLocation.y = yMin; + } + if (realLocation.y > yMax) { + realLocation.y = yMax; + } + // Ensure the port is positioned on its parent borders and not in the + // middle. + // Modify position if needed. + if ((realLocation.y != yMin) && (realLocation.y != yMax)) { + if ((realLocation.x != xMin) && (realLocation.x != xMax)) { + int preferedSide = findClosestSideOfParent(realLocation, parentRec); + switch (preferedSide) { + case PositionConstants.NORTH: + realLocation.y = yMin; + break; + case PositionConstants.SOUTH: + realLocation.y = yMax; + break; + case PositionConstants.WEST: + realLocation.x = xMin; + break; + case PositionConstants.EAST: + default: + realLocation.x = xMax; + break; + } + } + } + // Return constrained location + return realLocation; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/ExpansionNodePositionLocator.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/ExpansionNodePositionLocator.java index 69e8a70f49c..327497c2394 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/ExpansionNodePositionLocator.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/ExpansionNodePositionLocator.java @@ -1,75 +1,75 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.locator;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.papyrus.uml.diagram.common.locator.AdvancedBorderItemLocator;
-
-/**
- * This class is used to constrain the position of an Expansion Node
- *
- * TODO : The node is not re-sizable
- */
-public class ExpansionNodePositionLocator extends AdvancedBorderItemLocator {
-
- /** Constructor **/
- public ExpansionNodePositionLocator(IFigure parentFigure) {
- super(parentFigure);
- }
-
- /** Constructor **/
- public ExpansionNodePositionLocator(IFigure borderItem, IFigure parentFigure, Rectangle constraint) {
- super(borderItem, parentFigure, constraint);
- }
-
- /** Constructor **/
- public ExpansionNodePositionLocator(IFigure parentFigure, int preferredSide) {
- super(parentFigure, preferredSide);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Rectangle getValidLocation(Rectangle proposedLocation, IFigure borderItem) {
- Rectangle realLocation = new Rectangle(proposedLocation);
- int side = findClosestSideOfParent(proposedLocation, getParentBorder());
- Point newTopLeft = locateOnBorder(realLocation.getTopLeft(), side, 0, borderItem);
- realLocation.setLocation(newTopLeft);
- return realLocation;
- }
-
- @Override
- public void relocate(IFigure borderItem) {
- // reset bounds of borderItem
- Dimension size = getSize(borderItem);
- Rectangle rectSuggested = getConstraint().getCopy();
- if (rectSuggested.getTopLeft().x == 0 && rectSuggested.getTopLeft().y == 0) {
- rectSuggested.setLocation(getPreferredLocation(borderItem));
- } else {
- // recovered constraint must be translated with the parent location
- // to be absolute
- rectSuggested.setLocation(rectSuggested.getLocation().translate(getParentBorder().getTopLeft()));
- }
- rectSuggested.setSize(size);
- Rectangle validLocation = getValidLocation(rectSuggested, borderItem);
- // the constraint is not reset, but the item bounds are
- borderItem.setBounds(validLocation);
- // ensure the side property is correctly set
- setCurrentSideOfParent(findClosestSideOfParent(borderItem.getBounds(), getParentBorder()));
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.locator; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.papyrus.uml.diagram.common.locator.AdvancedBorderItemLocator; + +/** + * This class is used to constrain the position of an Expansion Node + * + * TODO : The node is not re-sizable + */ +public class ExpansionNodePositionLocator extends AdvancedBorderItemLocator { + + /** Constructor **/ + public ExpansionNodePositionLocator(IFigure parentFigure) { + super(parentFigure); + } + + /** Constructor **/ + public ExpansionNodePositionLocator(IFigure borderItem, IFigure parentFigure, Rectangle constraint) { + super(borderItem, parentFigure, constraint); + } + + /** Constructor **/ + public ExpansionNodePositionLocator(IFigure parentFigure, int preferredSide) { + super(parentFigure, preferredSide); + } + + /** + * {@inheritDoc} + */ + @Override + public Rectangle getValidLocation(Rectangle proposedLocation, IFigure borderItem) { + Rectangle realLocation = new Rectangle(proposedLocation); + int side = findClosestSideOfParent(proposedLocation, getParentBorder()); + Point newTopLeft = locateOnBorder(realLocation.getTopLeft(), side, 0, borderItem); + realLocation.setLocation(newTopLeft); + return realLocation; + } + + @Override + public void relocate(IFigure borderItem) { + // reset bounds of borderItem + Dimension size = getSize(borderItem); + Rectangle rectSuggested = getConstraint().getCopy(); + if (rectSuggested.getTopLeft().x == 0 && rectSuggested.getTopLeft().y == 0) { + rectSuggested.setLocation(getPreferredLocation(borderItem)); + } else { + // recovered constraint must be translated with the parent location + // to be absolute + rectSuggested.setLocation(rectSuggested.getLocation().translate(getParentBorder().getTopLeft())); + } + rectSuggested.setSize(size); + Rectangle validLocation = getValidLocation(rectSuggested, borderItem); + // the constraint is not reset, but the item bounds are + borderItem.setBounds(validLocation); + // ensure the side property is correctly set + setCurrentSideOfParent(findClosestSideOfParent(borderItem.getBounds(), getParentBorder())); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/LinkedBehaviorLocator.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/LinkedBehaviorLocator.java index 4ea1a5909d1..9f6f887279a 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/LinkedBehaviorLocator.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/LinkedBehaviorLocator.java @@ -1,100 +1,100 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.locator;
-
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.PositionConstants;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.papyrus.uml.diagram.common.locator.AdvancedBorderItemLocator;
-
-/**
- * This class is used to constrain the position of a linked Behavior
- */
-public class LinkedBehaviorLocator extends AdvancedBorderItemLocator {
- private final static Dimension OFFSET = new Dimension(-20, -20);
- /**
- * The margin to leave between the property node and its parent when
- * relocating
- */
- private static final int MARGIN = 5;
-
- /** Constructor **/
- public LinkedBehaviorLocator(IFigure parentFigure) {
- this(parentFigure, PositionConstants.NORTH);
- this.setBorderItemOffset(OFFSET);
- }
-
- /** Constructor **/
- public LinkedBehaviorLocator(IFigure borderItem, IFigure parentFigure, Rectangle constraint) {
- super(borderItem, parentFigure, constraint);
- this.setBorderItemOffset(OFFSET); }
-
- /** Constructor **/
- public LinkedBehaviorLocator(IFigure parentFigure, int preferredSide) {
- super(parentFigure, preferredSide);
- this.setBorderItemOffset(OFFSET);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Rectangle getValidLocation(Rectangle proposedLocation, IFigure borderItem) {
- Rectangle realLocation = proposedLocation.getCopy();
- if (getParentBorder().intersects(proposedLocation)) {
- int heightGap = getParentBorder().y - proposedLocation.y - proposedLocation.height - MARGIN;
- realLocation.translate(0, heightGap);
- }
- return realLocation;
- }
-
- /**
- * Re-arrange the location of the border item.
- *
- * @see org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator#relocate(org.eclipse.draw2d.IFigure)
- *
- * @param borderItem
- */
- @Override
- public void relocate(IFigure borderItem) {
- // reset bounds of borderItem
- Rectangle validLocation = getCorrectItemLocation(borderItem);
- // the constraint is not reset, but the item bounds are
- borderItem.setBounds(validLocation);
- // ensure the side property is correctly set
- setCurrentSideOfParent(findClosestSideOfParent(borderItem.getBounds(), getParentBorder()));
- }
-
- /**
- * Get the current location
- *
- * @param borderItem
- * the item to get location
- * @return location of item
- */
- public Rectangle getCorrectItemLocation(IFigure borderItem) {
- Dimension size = getSize(borderItem);
- Rectangle rectSuggested = getConstraint().getCopy();
- if (rectSuggested.getTopLeft().x == 0 && rectSuggested.getTopLeft().y == 0) {
- rectSuggested.setLocation(getPreferredLocation(borderItem));
- } else {
- // recovered constraint must be translated with the parent location
- // to be absolute
- rectSuggested.setLocation(rectSuggested.getLocation().translate(getParentBorder().getTopLeft()));
- }
- rectSuggested.setSize(size);
- return getValidLocation(rectSuggested, borderItem);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.locator; + +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.papyrus.uml.diagram.common.locator.AdvancedBorderItemLocator; + +/** + * This class is used to constrain the position of a linked Behavior + */ +public class LinkedBehaviorLocator extends AdvancedBorderItemLocator { + private final static Dimension OFFSET = new Dimension(-20, -20); + /** + * The margin to leave between the property node and its parent when + * relocating + */ + private static final int MARGIN = 5; + + /** Constructor **/ + public LinkedBehaviorLocator(IFigure parentFigure) { + this(parentFigure, PositionConstants.NORTH); + this.setBorderItemOffset(OFFSET); + } + + /** Constructor **/ + public LinkedBehaviorLocator(IFigure borderItem, IFigure parentFigure, Rectangle constraint) { + super(borderItem, parentFigure, constraint); + this.setBorderItemOffset(OFFSET); } + + /** Constructor **/ + public LinkedBehaviorLocator(IFigure parentFigure, int preferredSide) { + super(parentFigure, preferredSide); + this.setBorderItemOffset(OFFSET); + } + + /** + * {@inheritDoc} + */ + @Override + public Rectangle getValidLocation(Rectangle proposedLocation, IFigure borderItem) { + Rectangle realLocation = proposedLocation.getCopy(); + if (getParentBorder().intersects(proposedLocation)) { + int heightGap = getParentBorder().y - proposedLocation.y - proposedLocation.height - MARGIN; + realLocation.translate(0, heightGap); + } + return realLocation; + } + + /** + * Re-arrange the location of the border item. + * + * @see org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator#relocate(org.eclipse.draw2d.IFigure) + * + * @param borderItem + */ + @Override + public void relocate(IFigure borderItem) { + // reset bounds of borderItem + Rectangle validLocation = getCorrectItemLocation(borderItem); + // the constraint is not reset, but the item bounds are + borderItem.setBounds(validLocation); + // ensure the side property is correctly set + setCurrentSideOfParent(findClosestSideOfParent(borderItem.getBounds(), getParentBorder())); + } + + /** + * Get the current location + * + * @param borderItem + * the item to get location + * @return location of item + */ + public Rectangle getCorrectItemLocation(IFigure borderItem) { + Dimension size = getSize(borderItem); + Rectangle rectSuggested = getConstraint().getCopy(); + if (rectSuggested.getTopLeft().x == 0 && rectSuggested.getTopLeft().y == 0) { + rectSuggested.setLocation(getPreferredLocation(borderItem)); + } else { + // recovered constraint must be translated with the parent location + // to be absolute + rectSuggested.setLocation(rectSuggested.getLocation().translate(getParentBorder().getTopLeft())); + } + rectSuggested.setSize(size); + return getValidLocation(rectSuggested, borderItem); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/PinPositionLocator.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/PinPositionLocator.java index f3fc95ffec0..2bac3856b84 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/PinPositionLocator.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/locator/PinPositionLocator.java @@ -1,464 +1,464 @@ -/*****************************************************************************
- * Copyright (c) 2009 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.locator;
-
-import org.eclipse.draw2d.AbstractPointListShape;
-import org.eclipse.draw2d.IFigure;
-import org.eclipse.draw2d.PositionConstants;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.draw2d.geometry.Rectangle;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode;
-import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil;
-import org.eclipse.gmf.runtime.notation.Bounds;
-import org.eclipse.papyrus.uml.diagram.activity.figures.AcceptEventActionFigure;
-import org.eclipse.papyrus.uml.diagram.activity.figures.OutputPinFigure;
-import org.eclipse.papyrus.uml.diagram.activity.figures.PinFigure;
-import org.eclipse.papyrus.uml.diagram.activity.helper.ActivityFigureDrawer;
-import org.eclipse.papyrus.uml.diagram.common.figure.node.PapyrusSendNodeFigure;
-import org.eclipse.papyrus.uml.diagram.common.locator.AdvancedBorderItemLocator;
-import org.eclipse.uml2.uml.Action;
-import org.eclipse.uml2.uml.CallOperationAction;
-
-/**
- * This class is used to constrain the position of Pin
- *
- * TODO : The pin is not re-sizable
- */
-public class PinPositionLocator extends AdvancedBorderItemLocator {
-
- /**
- * The offset to add to default position. (to avoid corner of rounded
- * rectangles)
- */
- public static final int EXTRA_BORDER_DEFAULT_OFFSET = 8;
-
- /** The default size of a pin */
- public static final int DEFAULT_PIN_SIZE = 16;
-
- /**
- * the maximum authorized x position on the template of a Send Signal Action
- * figure
- */
- private static final int SEND_SIGNAL_ACTION_MAX_X = 150;
-
- /** the width of the template of a Send Signal Action figure */
- private static final int SEND_SIGNAL_ACTION_WIDTH = 200;
-
- /** Constructor **/
- public PinPositionLocator(IFigure parentFigure) {
- super(parentFigure);
- }
-
- /** Constructor **/
- public PinPositionLocator(IFigure borderItem, IFigure parentFigure, Rectangle constraint) {
- super(borderItem, parentFigure, constraint);
- }
-
- /** Constructor **/
- public PinPositionLocator(IFigure parentFigure, int preferredSide) {
- super(parentFigure, preferredSide);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Rectangle getValidLocation(Rectangle proposedLocation, IFigure borderItem) {
- Rectangle realLocation = new Rectangle(proposedLocation);
- realLocation.width = Math.max(realLocation.width, realLocation.height);
- realLocation.height = realLocation.width;
- int side = findClosestAuthorizedSideOfParent(proposedLocation, getParentBorder());
- Point newTopLeft = locateOnBorder(realLocation.getTopLeft(), side, 0, borderItem);
- realLocation.setLocation(newTopLeft);
- return realLocation;
- }
-
- /**
- * The preferred side takes precedence.
- *
- * @param suggestedLocation
- * @param suggestedSide
- * @param circuitCount
- * recursion count to avoid an infinite loop
- * @return point
- */
- @Override
- protected Point locateOnBorder(Point suggestedLocation, int suggestedSide, int circuitCount, IFigure borderItem) {
- Point suggestedCenter = borderItem.getBounds().getCopy().setLocation(suggestedLocation).getCenter();
- suggestedSide = redefineSuggestedSide(suggestedCenter, suggestedSide);
- if (isInSendSignalAction()) {
- // prevent a pin too far EAST that would be on the convex sides of
- // the pentagon
- if (suggestedSide == PositionConstants.SOUTH || suggestedSide == PositionConstants.NORTH) {
- int maxLocation = getParentBorder().x + getParentBorder().width * SEND_SIGNAL_ACTION_MAX_X / SEND_SIGNAL_ACTION_WIDTH - getSize(borderItem).width;
- if (suggestedLocation.x > maxLocation) {
- suggestedLocation.x = maxLocation;
- }
- }
- }
- Point recommendedLocation = super.locateOnBorder(suggestedLocation, suggestedSide, circuitCount, borderItem);
- return recommendedLocation;
- }
-
- /**
- * Ensure the suggested location actually lies on the parent boundary. The
- * side takes precedence.
- *
- * @param suggestedLocation
- * suggested location
- * @param suggestedSide
- * suggested side
- * @param borderItem
- * the item figure
- * @return point
- */
- @Override
- protected Point locateOnParent(Point suggestedLocation, int suggestedSide, IFigure borderItem) {
- Rectangle bounds = getParentBorder();
- int parentFigureWidth = bounds.width;
- int parentFigureHeight = bounds.height;
- int parentFigureX = bounds.x;
- int parentFigureY = bounds.y;
- Dimension borderItemSize = getSize(borderItem);
- int newX = suggestedLocation.x;
- int newY = suggestedLocation.y;
- int westX = parentFigureX - borderItemSize.width + getBorderItemOffset().width;
- int eastX = parentFigureX + parentFigureWidth - getBorderItemOffset().width;
- int maxX = 0;
- if (isInSendSignalAction()) {
- // prevent a pin too far EAST that would be on the convex sides of
- // the pentagon
- if (suggestedSide == PositionConstants.SOUTH || suggestedSide == PositionConstants.NORTH) {
- maxX = parentFigureX + parentFigureWidth * SEND_SIGNAL_ACTION_MAX_X / SEND_SIGNAL_ACTION_WIDTH - getBorderItemOffset().width;
- }
- }
- int southY = parentFigureY + parentFigureHeight - getBorderItemOffset().height;
- int northY = parentFigureY - borderItemSize.height + getBorderItemOffset().height;
- if (suggestedSide == PositionConstants.WEST) {
- if (suggestedLocation.x != westX) {
- newX = westX;
- }
- if (suggestedLocation.y < bounds.getTopLeft().y) {
- newY = northY + borderItemSize.height;
- } else if (suggestedLocation.y > bounds.getBottomLeft().y - borderItemSize.height) {
- newY = southY - borderItemSize.height;
- }
- } else if (suggestedSide == PositionConstants.EAST) {
- if (suggestedLocation.x != eastX) {
- newX = eastX;
- }
- if (suggestedLocation.y < bounds.getTopLeft().y) {
- newY = northY + borderItemSize.height;
- } else if (suggestedLocation.y > bounds.getBottomLeft().y - borderItemSize.height) {
- newY = southY - borderItemSize.height;
- }
- } else if (suggestedSide == PositionConstants.SOUTH) {
- if (suggestedLocation.y != southY) {
- newY = southY;
- }
- if (suggestedLocation.x < bounds.getBottomLeft().x) {
- newX = westX + borderItemSize.width;
- } else if (suggestedLocation.x > bounds.getBottomRight().x - borderItemSize.width) {
- newX = eastX - borderItemSize.width;
- }
- } else { // NORTH
- if (suggestedLocation.y != northY) {
- newY = northY;
- }
- if (suggestedLocation.x < bounds.getBottomLeft().x) {
- newX = westX + borderItemSize.width;
- } else if (suggestedLocation.x > bounds.getBottomRight().x - borderItemSize.width) {
- newX = eastX - borderItemSize.width;
- }
- }
- if (maxX > 0 && newX > maxX) {
- newX = maxX;
- }
- return new Point(newX, newY);
- }
-
- /**
- * Recomputes the suggested side by eliminating unauthorized sides depending
- * on the action type
- *
- * @param childCenter
- * suggested location center
- * @param suggestedSide
- * suggested side
- * @return correct side
- */
- private int redefineSuggestedSide(Point childCenter, int suggestedSide) {
- if (isInSendSignalAction()) {
- // EAST side is not authorized
- if (suggestedSide == PositionConstants.EAST) {
- Point parentCenter = getParentBorder().getCenter();
- if (childCenter.y < parentCenter.y) {
- suggestedSide = PositionConstants.NORTH;
- } else {
- suggestedSide = PositionConstants.SOUTH;
- }
- }
- } else if (isInAcceptEventAction()) {
- // WEST side is not authorized
- if (suggestedSide == PositionConstants.WEST) {
- Point parentCenter = getParentBorder().getCenter();
- if (childCenter.y < parentCenter.y) {
- suggestedSide = PositionConstants.NORTH;
- } else {
- suggestedSide = PositionConstants.SOUTH;
- }
- }
- // EAST side is not authorized for AcceptTimeEventAction
- if (suggestedSide == PositionConstants.EAST && isInAcceptTimeEventAction()) {
- Point parentCenter = getParentBorder().getCenter();
- if (childCenter.y < parentCenter.y) {
- suggestedSide = PositionConstants.NORTH;
- } else {
- suggestedSide = PositionConstants.SOUTH;
- }
- }
- }
- return suggestedSide;
- }
-
- /**
- * Find the closest side when x,y is inside parent.
- *
- * @param proposedLocation
- * @param parentBorder
- * @return draw constant
- */
- public int findClosestAuthorizedSideOfParent(Rectangle proposedLocation, Rectangle parentBorder) {
- int side = findClosestSideOfParent(proposedLocation, parentBorder);
- side = redefineSuggestedSide(proposedLocation.getCenter(), side);
- return side;
- }
-
- /**
- * Know whether containing action is a SendSignalAction
- *
- * @return true is containing action is a SendSignalAction
- */
- private boolean isInSendSignalAction() {
- IFigure parentFigure = getParentFigure();
- for (Object child : parentFigure.getChildren()) {
- if (child instanceof PapyrusSendNodeFigure) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Know whether containing action is an AcceptEventAction
- *
- * @return true is containing action is an AcceptEventAction
- */
- private boolean isInAcceptEventAction() {
- IFigure parentFigure = getParentFigure();
- for (Object child : parentFigure.getChildren()) {
- if (child instanceof AcceptEventActionFigure) {
- ((AcceptEventActionFigure) child).isTemplateForAcceptTimeEventActionUsed();
- return true;
- }
- }
- return false;
- }
-
- /**
- * Know whether containing action is an AcceptTimeEventAction
- *
- * @return true is containing action is an AcceptEventAction with
- * AcceptTimeEventAction representation
- */
- private boolean isInAcceptTimeEventAction() {
- IFigure parentFigure = getParentFigure();
- for (Object child : parentFigure.getChildren()) {
- if (child instanceof AcceptEventActionFigure) {
- return ((AcceptEventActionFigure) child).isTemplateForAcceptTimeEventActionUsed();
- }
- }
- return false;
- }
-
- /**
- * Re-arrange the location of the border item, and also the contained arrow.
- *
- * @see org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator#relocate(org.eclipse.draw2d.IFigure)
- *
- * @param borderItem
- */
- @Override
- public void relocate(IFigure borderItem) {
- // reset bounds of borderItem
- Dimension size = getSize(borderItem);
- Rectangle rectSuggested = getConstraint().getCopy();
- if (rectSuggested.getTopLeft().x == 0 && rectSuggested.getTopLeft().y == 0) {
- rectSuggested.setLocation(getPreferredLocation(borderItem));
- } else {
- // recovered constraint must be translated with the parent location
- // to be absolute
- rectSuggested.setLocation(rectSuggested.getLocation().translate(getParentBorder().getTopLeft()));
- }
- rectSuggested.setSize(size);
- Rectangle validLocation = getValidLocation(rectSuggested, borderItem);
- // the constraint is not reset, but the item bounds are
- borderItem.setBounds(validLocation);
- // ensure the side property is correctly set
- setCurrentSideOfParent(findClosestAuthorizedSideOfParent(borderItem.getBounds(), getParentBorder()));
- // refresh the arrow depending on the Pin type and the side on which it
- // is located
- for (Object subfigure : borderItem.getChildren()) {
- if (subfigure instanceof IFigure) {
- for (Object child : ((IFigure) subfigure).getChildren()) {
- refreshPinDescriptorArrow(child, MapModeUtil.getMapMode(borderItem), size);
- }
- }
- }
- }
-
- /**
- * Refresh the arrow in case child is a Pin Descriptor
- *
- * @param child
- * the Pin Descriptor (no effect otherwise)
- * @param mapMode
- * the IMapMode
- * @param size
- * the size of the border item
- */
- private void refreshPinDescriptorArrow(Object child, IMapMode mapMode, Dimension size) {
- boolean arrowIn = false;
- AbstractPointListShape arrow = null;
- if (child instanceof PinFigure) {
- arrowIn = true;
- arrow = ((PinFigure) child).getOptionalArrowFigure();
- }
-
- if (child instanceof OutputPinFigure) {
- arrowIn = false;
- arrow = ((PinFigure) child).getOptionalArrowFigure();
- }
-
- if (arrow != null && arrow.getPoints().size() > 0) {
- int arrowDirection;
- int side = getCurrentSideOfParent();
- switch (side) {
- case PositionConstants.NORTH:
- if (arrowIn) {
- arrowDirection = PositionConstants.SOUTH;
- } else {
- arrowDirection = PositionConstants.NORTH;
- }
- break;
- case PositionConstants.EAST:
- if (arrowIn) {
- arrowDirection = PositionConstants.WEST;
- } else {
- arrowDirection = PositionConstants.EAST;
- }
- break;
- case PositionConstants.SOUTH:
- if (arrowIn) {
- arrowDirection = PositionConstants.NORTH;
- } else {
- arrowDirection = PositionConstants.SOUTH;
- }
- break;
- case PositionConstants.WEST:
- default:
- if (arrowIn) {
- arrowDirection = PositionConstants.EAST;
- } else {
- arrowDirection = PositionConstants.WEST;
- }
- }
- ActivityFigureDrawer.redrawPinArrow(arrow, mapMode, size, arrowDirection);
- }
- }
-
- /**
- * Get an initial location based on the side. ( appropriate extremity of the
- * side )
- *
- * @param side
- * the preferred side of the parent figure on which to place this
- * border item as defined in {@link PositionConstants}
- * @return point
- */
- @Override
- protected Point getPreferredLocation(int side, IFigure borderItem) {
- Rectangle bounds = getParentBorder();
- int parentFigureWidth = bounds.width;
- int parentFigureHeight = bounds.height;
- int parentFigureX = bounds.x;
- int parentFigureY = bounds.y;
- int x = parentFigureX;
- int y = parentFigureY;
- Dimension borderItemSize = getSize(borderItem);
- switch (side) {
- case PositionConstants.NORTH:
- x += EXTRA_BORDER_DEFAULT_OFFSET + getBorderItemOffset().width;
- y += -borderItemSize.height + getBorderItemOffset().height;
- break;
- case PositionConstants.EAST:
- // take south east extremity to allow following pins placing above
- x += parentFigureWidth - getBorderItemOffset().width;
- y += parentFigureHeight - borderItemSize.height - EXTRA_BORDER_DEFAULT_OFFSET - getBorderItemOffset().height;
- break;
- case PositionConstants.SOUTH:
- x += EXTRA_BORDER_DEFAULT_OFFSET + getBorderItemOffset().width;
- y += parentFigureHeight - getBorderItemOffset().height;
- break;
- case PositionConstants.WEST:
- default:
- x += -borderItemSize.width + getBorderItemOffset().width;
- y += EXTRA_BORDER_DEFAULT_OFFSET + getBorderItemOffset().height;
- }
- return new Point(x, y);
- }
-
- /**
- * Adapt the bounds constraint to fit to the action's contained pins
- *
- * @param boundsConstraint
- * the constraint to adapt
- * @param domainElement
- * the model action
- * @return
- * @return boundsConstraint for convenience
- *
- */
- public static Bounds adaptActionHeight(Bounds boundsConstraint, EObject domainElement) {
- if (domainElement instanceof Action) {
- int pinsOnHeight = 0;
- int numberOfInputs = ((Action) domainElement).getInputs().size();
- int numberOfOutputs = ((Action) domainElement).getOutputs().size();
- if (domainElement instanceof CallOperationAction) {
- // target is located on top
- pinsOnHeight = Math.max(numberOfInputs - 1, numberOfOutputs);
- } else {
- pinsOnHeight = Math.max(numberOfInputs, numberOfOutputs);
- }
- if (pinsOnHeight > 0) {
- // each pin is 16 px height, consider extra px for margins
- int heightInPx = 2 * EXTRA_BORDER_DEFAULT_OFFSET + pinsOnHeight * (DEFAULT_PIN_SIZE + 8) - 8;
- boundsConstraint.setHeight(heightInPx);
- }
- }
- return boundsConstraint;
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.locator; + +import org.eclipse.draw2d.AbstractPointListShape; +import org.eclipse.draw2d.IFigure; +import org.eclipse.draw2d.PositionConstants; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.draw2d.geometry.Rectangle; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.draw2d.ui.mapmode.IMapMode; +import org.eclipse.gmf.runtime.draw2d.ui.mapmode.MapModeUtil; +import org.eclipse.gmf.runtime.notation.Bounds; +import org.eclipse.papyrus.uml.diagram.activity.figures.AcceptEventActionFigure; +import org.eclipse.papyrus.uml.diagram.activity.figures.OutputPinFigure; +import org.eclipse.papyrus.uml.diagram.activity.figures.PinFigure; +import org.eclipse.papyrus.uml.diagram.activity.helper.ActivityFigureDrawer; +import org.eclipse.papyrus.uml.diagram.common.figure.node.PapyrusSendNodeFigure; +import org.eclipse.papyrus.uml.diagram.common.locator.AdvancedBorderItemLocator; +import org.eclipse.uml2.uml.Action; +import org.eclipse.uml2.uml.CallOperationAction; + +/** + * This class is used to constrain the position of Pin + * + * TODO : The pin is not re-sizable + */ +public class PinPositionLocator extends AdvancedBorderItemLocator { + + /** + * The offset to add to default position. (to avoid corner of rounded + * rectangles) + */ + public static final int EXTRA_BORDER_DEFAULT_OFFSET = 8; + + /** The default size of a pin */ + public static final int DEFAULT_PIN_SIZE = 16; + + /** + * the maximum authorized x position on the template of a Send Signal Action + * figure + */ + private static final int SEND_SIGNAL_ACTION_MAX_X = 150; + + /** the width of the template of a Send Signal Action figure */ + private static final int SEND_SIGNAL_ACTION_WIDTH = 200; + + /** Constructor **/ + public PinPositionLocator(IFigure parentFigure) { + super(parentFigure); + } + + /** Constructor **/ + public PinPositionLocator(IFigure borderItem, IFigure parentFigure, Rectangle constraint) { + super(borderItem, parentFigure, constraint); + } + + /** Constructor **/ + public PinPositionLocator(IFigure parentFigure, int preferredSide) { + super(parentFigure, preferredSide); + } + + /** + * {@inheritDoc} + */ + @Override + public Rectangle getValidLocation(Rectangle proposedLocation, IFigure borderItem) { + Rectangle realLocation = new Rectangle(proposedLocation); + realLocation.width = Math.max(realLocation.width, realLocation.height); + realLocation.height = realLocation.width; + int side = findClosestAuthorizedSideOfParent(proposedLocation, getParentBorder()); + Point newTopLeft = locateOnBorder(realLocation.getTopLeft(), side, 0, borderItem); + realLocation.setLocation(newTopLeft); + return realLocation; + } + + /** + * The preferred side takes precedence. + * + * @param suggestedLocation + * @param suggestedSide + * @param circuitCount + * recursion count to avoid an infinite loop + * @return point + */ + @Override + protected Point locateOnBorder(Point suggestedLocation, int suggestedSide, int circuitCount, IFigure borderItem) { + Point suggestedCenter = borderItem.getBounds().getCopy().setLocation(suggestedLocation).getCenter(); + suggestedSide = redefineSuggestedSide(suggestedCenter, suggestedSide); + if (isInSendSignalAction()) { + // prevent a pin too far EAST that would be on the convex sides of + // the pentagon + if (suggestedSide == PositionConstants.SOUTH || suggestedSide == PositionConstants.NORTH) { + int maxLocation = getParentBorder().x + getParentBorder().width * SEND_SIGNAL_ACTION_MAX_X / SEND_SIGNAL_ACTION_WIDTH - getSize(borderItem).width; + if (suggestedLocation.x > maxLocation) { + suggestedLocation.x = maxLocation; + } + } + } + Point recommendedLocation = super.locateOnBorder(suggestedLocation, suggestedSide, circuitCount, borderItem); + return recommendedLocation; + } + + /** + * Ensure the suggested location actually lies on the parent boundary. The + * side takes precedence. + * + * @param suggestedLocation + * suggested location + * @param suggestedSide + * suggested side + * @param borderItem + * the item figure + * @return point + */ + @Override + protected Point locateOnParent(Point suggestedLocation, int suggestedSide, IFigure borderItem) { + Rectangle bounds = getParentBorder(); + int parentFigureWidth = bounds.width; + int parentFigureHeight = bounds.height; + int parentFigureX = bounds.x; + int parentFigureY = bounds.y; + Dimension borderItemSize = getSize(borderItem); + int newX = suggestedLocation.x; + int newY = suggestedLocation.y; + int westX = parentFigureX - borderItemSize.width + getBorderItemOffset().width; + int eastX = parentFigureX + parentFigureWidth - getBorderItemOffset().width; + int maxX = 0; + if (isInSendSignalAction()) { + // prevent a pin too far EAST that would be on the convex sides of + // the pentagon + if (suggestedSide == PositionConstants.SOUTH || suggestedSide == PositionConstants.NORTH) { + maxX = parentFigureX + parentFigureWidth * SEND_SIGNAL_ACTION_MAX_X / SEND_SIGNAL_ACTION_WIDTH - getBorderItemOffset().width; + } + } + int southY = parentFigureY + parentFigureHeight - getBorderItemOffset().height; + int northY = parentFigureY - borderItemSize.height + getBorderItemOffset().height; + if (suggestedSide == PositionConstants.WEST) { + if (suggestedLocation.x != westX) { + newX = westX; + } + if (suggestedLocation.y < bounds.getTopLeft().y) { + newY = northY + borderItemSize.height; + } else if (suggestedLocation.y > bounds.getBottomLeft().y - borderItemSize.height) { + newY = southY - borderItemSize.height; + } + } else if (suggestedSide == PositionConstants.EAST) { + if (suggestedLocation.x != eastX) { + newX = eastX; + } + if (suggestedLocation.y < bounds.getTopLeft().y) { + newY = northY + borderItemSize.height; + } else if (suggestedLocation.y > bounds.getBottomLeft().y - borderItemSize.height) { + newY = southY - borderItemSize.height; + } + } else if (suggestedSide == PositionConstants.SOUTH) { + if (suggestedLocation.y != southY) { + newY = southY; + } + if (suggestedLocation.x < bounds.getBottomLeft().x) { + newX = westX + borderItemSize.width; + } else if (suggestedLocation.x > bounds.getBottomRight().x - borderItemSize.width) { + newX = eastX - borderItemSize.width; + } + } else { // NORTH + if (suggestedLocation.y != northY) { + newY = northY; + } + if (suggestedLocation.x < bounds.getBottomLeft().x) { + newX = westX + borderItemSize.width; + } else if (suggestedLocation.x > bounds.getBottomRight().x - borderItemSize.width) { + newX = eastX - borderItemSize.width; + } + } + if (maxX > 0 && newX > maxX) { + newX = maxX; + } + return new Point(newX, newY); + } + + /** + * Recomputes the suggested side by eliminating unauthorized sides depending + * on the action type + * + * @param childCenter + * suggested location center + * @param suggestedSide + * suggested side + * @return correct side + */ + private int redefineSuggestedSide(Point childCenter, int suggestedSide) { + if (isInSendSignalAction()) { + // EAST side is not authorized + if (suggestedSide == PositionConstants.EAST) { + Point parentCenter = getParentBorder().getCenter(); + if (childCenter.y < parentCenter.y) { + suggestedSide = PositionConstants.NORTH; + } else { + suggestedSide = PositionConstants.SOUTH; + } + } + } else if (isInAcceptEventAction()) { + // WEST side is not authorized + if (suggestedSide == PositionConstants.WEST) { + Point parentCenter = getParentBorder().getCenter(); + if (childCenter.y < parentCenter.y) { + suggestedSide = PositionConstants.NORTH; + } else { + suggestedSide = PositionConstants.SOUTH; + } + } + // EAST side is not authorized for AcceptTimeEventAction + if (suggestedSide == PositionConstants.EAST && isInAcceptTimeEventAction()) { + Point parentCenter = getParentBorder().getCenter(); + if (childCenter.y < parentCenter.y) { + suggestedSide = PositionConstants.NORTH; + } else { + suggestedSide = PositionConstants.SOUTH; + } + } + } + return suggestedSide; + } + + /** + * Find the closest side when x,y is inside parent. + * + * @param proposedLocation + * @param parentBorder + * @return draw constant + */ + public int findClosestAuthorizedSideOfParent(Rectangle proposedLocation, Rectangle parentBorder) { + int side = findClosestSideOfParent(proposedLocation, parentBorder); + side = redefineSuggestedSide(proposedLocation.getCenter(), side); + return side; + } + + /** + * Know whether containing action is a SendSignalAction + * + * @return true is containing action is a SendSignalAction + */ + private boolean isInSendSignalAction() { + IFigure parentFigure = getParentFigure(); + for (Object child : parentFigure.getChildren()) { + if (child instanceof PapyrusSendNodeFigure) { + return true; + } + } + return false; + } + + /** + * Know whether containing action is an AcceptEventAction + * + * @return true is containing action is an AcceptEventAction + */ + private boolean isInAcceptEventAction() { + IFigure parentFigure = getParentFigure(); + for (Object child : parentFigure.getChildren()) { + if (child instanceof AcceptEventActionFigure) { + ((AcceptEventActionFigure) child).isTemplateForAcceptTimeEventActionUsed(); + return true; + } + } + return false; + } + + /** + * Know whether containing action is an AcceptTimeEventAction + * + * @return true is containing action is an AcceptEventAction with + * AcceptTimeEventAction representation + */ + private boolean isInAcceptTimeEventAction() { + IFigure parentFigure = getParentFigure(); + for (Object child : parentFigure.getChildren()) { + if (child instanceof AcceptEventActionFigure) { + return ((AcceptEventActionFigure) child).isTemplateForAcceptTimeEventActionUsed(); + } + } + return false; + } + + /** + * Re-arrange the location of the border item, and also the contained arrow. + * + * @see org.eclipse.gmf.runtime.diagram.ui.figures.BorderItemLocator#relocate(org.eclipse.draw2d.IFigure) + * + * @param borderItem + */ + @Override + public void relocate(IFigure borderItem) { + // reset bounds of borderItem + Dimension size = getSize(borderItem); + Rectangle rectSuggested = getConstraint().getCopy(); + if (rectSuggested.getTopLeft().x == 0 && rectSuggested.getTopLeft().y == 0) { + rectSuggested.setLocation(getPreferredLocation(borderItem)); + } else { + // recovered constraint must be translated with the parent location + // to be absolute + rectSuggested.setLocation(rectSuggested.getLocation().translate(getParentBorder().getTopLeft())); + } + rectSuggested.setSize(size); + Rectangle validLocation = getValidLocation(rectSuggested, borderItem); + // the constraint is not reset, but the item bounds are + borderItem.setBounds(validLocation); + // ensure the side property is correctly set + setCurrentSideOfParent(findClosestAuthorizedSideOfParent(borderItem.getBounds(), getParentBorder())); + // refresh the arrow depending on the Pin type and the side on which it + // is located + for (Object subfigure : borderItem.getChildren()) { + if (subfigure instanceof IFigure) { + for (Object child : ((IFigure) subfigure).getChildren()) { + refreshPinDescriptorArrow(child, MapModeUtil.getMapMode(borderItem), size); + } + } + } + } + + /** + * Refresh the arrow in case child is a Pin Descriptor + * + * @param child + * the Pin Descriptor (no effect otherwise) + * @param mapMode + * the IMapMode + * @param size + * the size of the border item + */ + private void refreshPinDescriptorArrow(Object child, IMapMode mapMode, Dimension size) { + boolean arrowIn = false; + AbstractPointListShape arrow = null; + if (child instanceof PinFigure) { + arrowIn = true; + arrow = ((PinFigure) child).getOptionalArrowFigure(); + } + + if (child instanceof OutputPinFigure) { + arrowIn = false; + arrow = ((PinFigure) child).getOptionalArrowFigure(); + } + + if (arrow != null && arrow.getPoints().size() > 0) { + int arrowDirection; + int side = getCurrentSideOfParent(); + switch (side) { + case PositionConstants.NORTH: + if (arrowIn) { + arrowDirection = PositionConstants.SOUTH; + } else { + arrowDirection = PositionConstants.NORTH; + } + break; + case PositionConstants.EAST: + if (arrowIn) { + arrowDirection = PositionConstants.WEST; + } else { + arrowDirection = PositionConstants.EAST; + } + break; + case PositionConstants.SOUTH: + if (arrowIn) { + arrowDirection = PositionConstants.NORTH; + } else { + arrowDirection = PositionConstants.SOUTH; + } + break; + case PositionConstants.WEST: + default: + if (arrowIn) { + arrowDirection = PositionConstants.EAST; + } else { + arrowDirection = PositionConstants.WEST; + } + } + ActivityFigureDrawer.redrawPinArrow(arrow, mapMode, size, arrowDirection); + } + } + + /** + * Get an initial location based on the side. ( appropriate extremity of the + * side ) + * + * @param side + * the preferred side of the parent figure on which to place this + * border item as defined in {@link PositionConstants} + * @return point + */ + @Override + protected Point getPreferredLocation(int side, IFigure borderItem) { + Rectangle bounds = getParentBorder(); + int parentFigureWidth = bounds.width; + int parentFigureHeight = bounds.height; + int parentFigureX = bounds.x; + int parentFigureY = bounds.y; + int x = parentFigureX; + int y = parentFigureY; + Dimension borderItemSize = getSize(borderItem); + switch (side) { + case PositionConstants.NORTH: + x += EXTRA_BORDER_DEFAULT_OFFSET + getBorderItemOffset().width; + y += -borderItemSize.height + getBorderItemOffset().height; + break; + case PositionConstants.EAST: + // take south east extremity to allow following pins placing above + x += parentFigureWidth - getBorderItemOffset().width; + y += parentFigureHeight - borderItemSize.height - EXTRA_BORDER_DEFAULT_OFFSET - getBorderItemOffset().height; + break; + case PositionConstants.SOUTH: + x += EXTRA_BORDER_DEFAULT_OFFSET + getBorderItemOffset().width; + y += parentFigureHeight - getBorderItemOffset().height; + break; + case PositionConstants.WEST: + default: + x += -borderItemSize.width + getBorderItemOffset().width; + y += EXTRA_BORDER_DEFAULT_OFFSET + getBorderItemOffset().height; + } + return new Point(x, y); + } + + /** + * Adapt the bounds constraint to fit to the action's contained pins + * + * @param boundsConstraint + * the constraint to adapt + * @param domainElement + * the model action + * @return + * @return boundsConstraint for convenience + * + */ + public static Bounds adaptActionHeight(Bounds boundsConstraint, EObject domainElement) { + if (domainElement instanceof Action) { + int pinsOnHeight = 0; + int numberOfInputs = ((Action) domainElement).getInputs().size(); + int numberOfOutputs = ((Action) domainElement).getOutputs().size(); + if (domainElement instanceof CallOperationAction) { + // target is located on top + pinsOnHeight = Math.max(numberOfInputs - 1, numberOfOutputs); + } else { + pinsOnHeight = Math.max(numberOfInputs, numberOfOutputs); + } + if (pinsOnHeight > 0) { + // each pin is 16 px height, consider extra px for margins + int heightInPx = 2 * EXTRA_BORDER_DEFAULT_OFFSET + pinsOnHeight * (DEFAULT_PIN_SIZE + 8) - 8; + boundsConstraint.setHeight(heightInPx); + } + } + return boundsConstraint; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ActivitySingleExecutionParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ActivitySingleExecutionParser.java index dd48ffa7d1c..c49b8e4af36 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ActivitySingleExecutionParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ActivitySingleExecutionParser.java @@ -1,132 +1,132 @@ -/*****************************************************************************
- * Copyright (c) 2009 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
-import org.eclipse.papyrus.uml.diagram.activity.parsers.MessageFormatParser;
-import org.eclipse.uml2.uml.Activity;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * A specific parser for the Activity. This parser refreshes the text displayed
- * by the Activity.
- */
-public class ActivitySingleExecutionParser extends MessageFormatParser implements ISemanticParser {
-
- private static final String SINGLE_EXECUTION_LABEL = "<<singleExecution>>";
-
- public ActivitySingleExecutionParser(EAttribute[] features, EAttribute[] editableFeatures) {
- super(features, editableFeatures);
- }
-
- public ActivitySingleExecutionParser(EAttribute[] features) {
- super(features);
- }
-
- public ActivitySingleExecutionParser() {
- super(new EAttribute[] { UMLPackage.eINSTANCE.getActivity_IsSingleExecution() });
- }
-
- protected EStructuralFeature getEStructuralFeature(Object notification) {
- EStructuralFeature featureImpl = null;
- if (notification instanceof Notification) {
- Object feature = ((Notification) notification).getFeature();
- if (feature instanceof EStructuralFeature) {
- featureImpl = (EStructuralFeature) feature;
- }
- }
- return featureImpl;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.papyrus.uml.diagram.sequence.parsers.AbstractParser#isAffectingEvent
- * (java.lang.Object , int)
- */
- @Override
- public boolean isAffectingEvent(Object event, int flags) {
- EStructuralFeature feature = getEStructuralFeature(event);
- return isValidFeature(feature);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.sequence.parsers.MessageFormatParser#
- * getPrintString(org.eclipse .core.runtime.IAdaptable, int)
- */
- @Override
- public String getPrintString(IAdaptable element, int flags) {
- Object obj = element.getAdapter(EObject.class);
- if (obj instanceof Activity) {
- Activity activity = (Activity) obj;
- if (activity.isSingleExecution()) {
- return SINGLE_EXECUTION_LABEL;
- }
- }
- return "";
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser#
- * areSemanticElementsAffected (org.eclipse.emf.ecore.EObject,
- * java.lang.Object)
- */
- @Override
- public boolean areSemanticElementsAffected(EObject listener, Object notification) {
- EStructuralFeature feature = getEStructuralFeature(notification);
- return isValidFeature(feature);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser#
- * getSemanticElementsBeingParsed (org.eclipse.emf.ecore.EObject)
- */
- @Override
- public List<?> getSemanticElementsBeingParsed(EObject element) {
- List<Element> semanticElementsBeingParsed = new ArrayList<Element>();
- if (element instanceof Activity) {
- Activity activity = (Activity) element;
- semanticElementsBeingParsed.add(activity);
- }
- return semanticElementsBeingParsed;
- }
-
- /**
- * Determines if the given feature has to be taken into account in this
- * parser
- *
- * @param feature
- * the feature to test
- * @return true if is valid, false otherwise
- */
- private boolean isValidFeature(EStructuralFeature feature) {
- return UMLPackage.eINSTANCE.getActivity_IsSingleExecution().equals(feature);
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser; +import org.eclipse.papyrus.uml.diagram.activity.parsers.MessageFormatParser; +import org.eclipse.uml2.uml.Activity; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * A specific parser for the Activity. This parser refreshes the text displayed + * by the Activity. + */ +public class ActivitySingleExecutionParser extends MessageFormatParser implements ISemanticParser { + + private static final String SINGLE_EXECUTION_LABEL = "<<singleExecution>>"; + + public ActivitySingleExecutionParser(EAttribute[] features, EAttribute[] editableFeatures) { + super(features, editableFeatures); + } + + public ActivitySingleExecutionParser(EAttribute[] features) { + super(features); + } + + public ActivitySingleExecutionParser() { + super(new EAttribute[] { UMLPackage.eINSTANCE.getActivity_IsSingleExecution() }); + } + + protected EStructuralFeature getEStructuralFeature(Object notification) { + EStructuralFeature featureImpl = null; + if (notification instanceof Notification) { + Object feature = ((Notification) notification).getFeature(); + if (feature instanceof EStructuralFeature) { + featureImpl = (EStructuralFeature) feature; + } + } + return featureImpl; + } + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.papyrus.uml.diagram.sequence.parsers.AbstractParser#isAffectingEvent + * (java.lang.Object , int) + */ + @Override + public boolean isAffectingEvent(Object event, int flags) { + EStructuralFeature feature = getEStructuralFeature(event); + return isValidFeature(feature); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.sequence.parsers.MessageFormatParser# + * getPrintString(org.eclipse .core.runtime.IAdaptable, int) + */ + @Override + public String getPrintString(IAdaptable element, int flags) { + Object obj = element.getAdapter(EObject.class); + if (obj instanceof Activity) { + Activity activity = (Activity) obj; + if (activity.isSingleExecution()) { + return SINGLE_EXECUTION_LABEL; + } + } + return ""; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser# + * areSemanticElementsAffected (org.eclipse.emf.ecore.EObject, + * java.lang.Object) + */ + @Override + public boolean areSemanticElementsAffected(EObject listener, Object notification) { + EStructuralFeature feature = getEStructuralFeature(notification); + return isValidFeature(feature); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser# + * getSemanticElementsBeingParsed (org.eclipse.emf.ecore.EObject) + */ + @Override + public List<?> getSemanticElementsBeingParsed(EObject element) { + List<Element> semanticElementsBeingParsed = new ArrayList<Element>(); + if (element instanceof Activity) { + Activity activity = (Activity) element; + semanticElementsBeingParsed.add(activity); + } + return semanticElementsBeingParsed; + } + + /** + * Determines if the given feature has to be taken into account in this + * parser + * + * @param feature + * the feature to test + * @return true if is valid, false otherwise + */ + private boolean isValidFeature(EStructuralFeature feature) { + return UMLPackage.eINSTANCE.getActivity_IsSingleExecution().equals(feature); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/DecisionInputFlowParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/DecisionInputFlowParser.java index 75a94719fe1..b17ba3db749 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/DecisionInputFlowParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/DecisionInputFlowParser.java @@ -1,142 +1,142 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
-import org.eclipse.papyrus.uml.diagram.activity.parsers.MessageFormatParser;
-import org.eclipse.uml2.uml.ActivityNode;
-import org.eclipse.uml2.uml.DecisionNode;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.ObjectFlow;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * A specific parser for the Object Flow to know whether it is decision input
- * flow of a Decision Node. This parser refreshes the text displayed by the
- * Object Flow.
- */
-public class DecisionInputFlowParser extends MessageFormatParser implements ISemanticParser {
-
- private static final String DECISION_INPUT_FLOW_LABEL = "<<decisionInputFlow>>";
-
- public DecisionInputFlowParser(EAttribute[] features, EAttribute[] editableFeatures) {
- super(features, editableFeatures);
- }
-
- public DecisionInputFlowParser(EAttribute[] features) {
- super(features);
- }
-
- public DecisionInputFlowParser() {
- super(new EAttribute[] { UMLPackage.eINSTANCE.getActivity_IsSingleExecution() });
- }
-
- protected EStructuralFeature getEStructuralFeature(Object notification) {
- EStructuralFeature featureImpl = null;
- if (notification instanceof Notification) {
- Object feature = ((Notification) notification).getFeature();
- if (feature instanceof EStructuralFeature) {
- featureImpl = (EStructuralFeature) feature;
- }
- }
- return featureImpl;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.papyrus.uml.diagram.sequence.parsers.AbstractParser#isAffectingEvent
- * (java.lang.Object , int)
- */
- @Override
- public boolean isAffectingEvent(Object event, int flags) {
- EStructuralFeature feature = getEStructuralFeature(event);
- return isValidFeature(feature);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.sequence.parsers.MessageFormatParser#
- * getPrintString(org.eclipse .core.runtime.IAdaptable, int)
- */
- @Override
- public String getPrintString(IAdaptable element, int flags) {
- Object obj = element.getAdapter(EObject.class);
- if (obj instanceof ObjectFlow) {
- ActivityNode target = ((ObjectFlow) obj).getTarget();
- if (target instanceof DecisionNode) {
- ObjectFlow decisionInputFlow = ((DecisionNode) target).getDecisionInputFlow();
- if (obj.equals(decisionInputFlow)) {
- return DECISION_INPUT_FLOW_LABEL;
- }
- }
- }
- return "";
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser#
- * areSemanticElementsAffected (org.eclipse.emf.ecore.EObject,
- * java.lang.Object)
- */
- @Override
- public boolean areSemanticElementsAffected(EObject listener, Object notification) {
- EStructuralFeature feature = getEStructuralFeature(notification);
- return isValidFeature(feature);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser#
- * getSemanticElementsBeingParsed (org.eclipse.emf.ecore.EObject)
- */
- @Override
- public List<?> getSemanticElementsBeingParsed(EObject element) {
- List<Element> semanticElementsBeingParsed = new ArrayList<Element>();
- if (element instanceof ObjectFlow) {
- ObjectFlow flow = (ObjectFlow) element;
- semanticElementsBeingParsed.add(flow);
- if (flow.getTarget() instanceof DecisionNode) {
- DecisionNode decision = (DecisionNode) flow.getTarget();
- semanticElementsBeingParsed.add(decision);
- }
- }
- return semanticElementsBeingParsed;
- }
-
- /**
- * Determines if the given feature has to be taken into account in this
- * parser
- *
- * @param feature
- * the feature to test
- * @return true if is valid, false otherwise
- */
- private boolean isValidFeature(EStructuralFeature feature) {
- return UMLPackage.eINSTANCE.getActivityEdge_Target().equals(feature) || UMLPackage.eINSTANCE.getDecisionNode_DecisionInputFlow().equals(feature);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser; +import org.eclipse.papyrus.uml.diagram.activity.parsers.MessageFormatParser; +import org.eclipse.uml2.uml.ActivityNode; +import org.eclipse.uml2.uml.DecisionNode; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.ObjectFlow; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * A specific parser for the Object Flow to know whether it is decision input + * flow of a Decision Node. This parser refreshes the text displayed by the + * Object Flow. + */ +public class DecisionInputFlowParser extends MessageFormatParser implements ISemanticParser { + + private static final String DECISION_INPUT_FLOW_LABEL = "<<decisionInputFlow>>"; + + public DecisionInputFlowParser(EAttribute[] features, EAttribute[] editableFeatures) { + super(features, editableFeatures); + } + + public DecisionInputFlowParser(EAttribute[] features) { + super(features); + } + + public DecisionInputFlowParser() { + super(new EAttribute[] { UMLPackage.eINSTANCE.getActivity_IsSingleExecution() }); + } + + protected EStructuralFeature getEStructuralFeature(Object notification) { + EStructuralFeature featureImpl = null; + if (notification instanceof Notification) { + Object feature = ((Notification) notification).getFeature(); + if (feature instanceof EStructuralFeature) { + featureImpl = (EStructuralFeature) feature; + } + } + return featureImpl; + } + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.papyrus.uml.diagram.sequence.parsers.AbstractParser#isAffectingEvent + * (java.lang.Object , int) + */ + @Override + public boolean isAffectingEvent(Object event, int flags) { + EStructuralFeature feature = getEStructuralFeature(event); + return isValidFeature(feature); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.sequence.parsers.MessageFormatParser# + * getPrintString(org.eclipse .core.runtime.IAdaptable, int) + */ + @Override + public String getPrintString(IAdaptable element, int flags) { + Object obj = element.getAdapter(EObject.class); + if (obj instanceof ObjectFlow) { + ActivityNode target = ((ObjectFlow) obj).getTarget(); + if (target instanceof DecisionNode) { + ObjectFlow decisionInputFlow = ((DecisionNode) target).getDecisionInputFlow(); + if (obj.equals(decisionInputFlow)) { + return DECISION_INPUT_FLOW_LABEL; + } + } + } + return ""; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser# + * areSemanticElementsAffected (org.eclipse.emf.ecore.EObject, + * java.lang.Object) + */ + @Override + public boolean areSemanticElementsAffected(EObject listener, Object notification) { + EStructuralFeature feature = getEStructuralFeature(notification); + return isValidFeature(feature); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser# + * getSemanticElementsBeingParsed (org.eclipse.emf.ecore.EObject) + */ + @Override + public List<?> getSemanticElementsBeingParsed(EObject element) { + List<Element> semanticElementsBeingParsed = new ArrayList<Element>(); + if (element instanceof ObjectFlow) { + ObjectFlow flow = (ObjectFlow) element; + semanticElementsBeingParsed.add(flow); + if (flow.getTarget() instanceof DecisionNode) { + DecisionNode decision = (DecisionNode) flow.getTarget(); + semanticElementsBeingParsed.add(decision); + } + } + return semanticElementsBeingParsed; + } + + /** + * Determines if the given feature has to be taken into account in this + * parser + * + * @param feature + * the feature to test + * @return true if is valid, false otherwise + */ + private boolean isValidFeature(EStructuralFeature feature) { + return UMLPackage.eINSTANCE.getActivityEdge_Target().equals(feature) || UMLPackage.eINSTANCE.getDecisionNode_DecisionInputFlow().equals(feature); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/InputDecisionParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/InputDecisionParser.java index 84693a96405..68f1f6bd757 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/InputDecisionParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/InputDecisionParser.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * A specific parser for displaying the input decision behavior associated to a
- * decision node.
- */
-public class InputDecisionParser extends AssociatedBehaviorParser {
-
- /** The format for displaying Input decision */
- private static final String DECISION_INPUT_FORMAT = "<<decisionInput>>".concat(System.getProperty("line.separator")).concat("%s");
-
- /**
- * Get the format for displaying Input decision
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getFormatString()
- * @return format string
- */
- @Override
- protected String getFormatString() {
- return DECISION_INPUT_FORMAT;
- }
-
- /**
- * Get the feature referencing the decision input
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getReferenceFeature()
- * @return feature
- */
- @Override
- protected EStructuralFeature getReferenceFeature() {
- return UMLPackage.eINSTANCE.getDecisionNode_DecisionInput();
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * A specific parser for displaying the input decision behavior associated to a + * decision node. + */ +public class InputDecisionParser extends AssociatedBehaviorParser { + + /** The format for displaying Input decision */ + private static final String DECISION_INPUT_FORMAT = "<<decisionInput>>".concat(System.getProperty("line.separator")).concat("%s"); + + /** + * Get the format for displaying Input decision + * + * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getFormatString() + * @return format string + */ + @Override + protected String getFormatString() { + return DECISION_INPUT_FORMAT; + } + + /** + * Get the feature referencing the decision input + * + * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getReferenceFeature() + * @return feature + */ + @Override + protected EStructuralFeature getReferenceFeature() { + return UMLPackage.eINSTANCE.getDecisionNode_DecisionInput(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/JoinSpecParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/JoinSpecParser.java index 7d9a0c24a50..05c1d1b6be8 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/JoinSpecParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/JoinSpecParser.java @@ -1,186 +1,186 @@ -/*****************************************************************************
- * Copyright (c) 2009 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.emf.transaction.util.TransactionUtil;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand;
-import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy;
-import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
-import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
-import org.eclipse.papyrus.uml.diagram.activity.parsers.MessageFormatParser;
-import org.eclipse.papyrus.uml.diagram.common.commands.SetValueSpecificationValueCommand;
-import org.eclipse.papyrus.uml.tools.utils.ValueSpecificationUtil;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.JoinNode;
-import org.eclipse.uml2.uml.UMLPackage;
-import org.eclipse.uml2.uml.ValueSpecification;
-
-/**
- * A specific parser for displaying the joinSpec of a Join Node. This parser
- * refreshes the text displayed for the Join Node.
- */
-public class JoinSpecParser extends MessageFormatParser implements ISemanticParser {
-
- /** The format for displaying the join spec */
- private static final String JOIN_SPEC_FORMAT = "{joinSpec = %s}";
-
- public JoinSpecParser(EAttribute[] features, EAttribute[] editableFeatures) {
- super(features, editableFeatures);
- }
-
- public JoinSpecParser(EAttribute[] features) {
- super(features);
- }
-
- public JoinSpecParser() {
- super(new EAttribute[] { UMLPackage.eINSTANCE.getNamedElement_Name() });
- }
-
- protected EStructuralFeature getEStructuralFeature(Object notification) {
- EStructuralFeature featureImpl = null;
- if (notification instanceof Notification) {
- Object feature = ((Notification) notification).getFeature();
- if (feature instanceof EStructuralFeature) {
- featureImpl = (EStructuralFeature) feature;
- }
- }
- return featureImpl;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.papyrus.uml.diagram.sequence.parsers.AbstractParser#isAffectingEvent
- * (java.lang.Object , int)
- */
- @Override
- public boolean isAffectingEvent(Object event, int flags) {
- EStructuralFeature feature = getEStructuralFeature(event);
- return isValidFeature(feature);
- }
-
- @Override
- public String getEditString(IAdaptable adapter, int flags) {
- // ensure valueLabel is never null
- String valueLabel = "";
- Object obj = adapter.getAdapter(EObject.class);
- if (obj instanceof JoinNode) {
- JoinNode join = (JoinNode) obj;
- ValueSpecification valueSpec = join.getJoinSpec();
- if (valueSpec != null) {
- String value = ValueSpecificationUtil.getSpecificationValue(valueSpec);
- if (value != null) {
- valueLabel = value;
- }
- }
- }
- return valueLabel;
- }
-
- @Override
- public ICommand getParseCommand(IAdaptable adapter, String newString, int flags) {
- Object obj = adapter.getAdapter(EObject.class);
- TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(obj);
- if (editingDomain == null) {
- return UnexecutableCommand.INSTANCE;
- }
- if (obj instanceof JoinNode) {
- JoinNode join = (JoinNode) obj;
- ValueSpecification valueSpec = join.getJoinSpec();
- if (valueSpec != null) {
- CompositeTransactionalCommand command = new CompositeTransactionalCommand(editingDomain, "Set Values"); //$NON-NLS-1$
- command.compose(new CommandProxy(new SetValueSpecificationValueCommand(valueSpec, newString)));
- return command;
- }
- }
- return UnexecutableCommand.INSTANCE;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.sequence.parsers.MessageFormatParser#
- * getPrintString(org.eclipse .core.runtime.IAdaptable, int)
- */
- @Override
- public String getPrintString(IAdaptable element, int flags) {
- // ensure valueLabel is never null
- String valueLabel = getEditString(element, flags);
- if (valueLabel.length() == 0) {
- valueLabel = " ";
- } else {
- valueLabel = String.format(JOIN_SPEC_FORMAT, valueLabel);
- }
- return valueLabel;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser#
- * areSemanticElementsAffected (org.eclipse.emf.ecore.EObject,
- * java.lang.Object)
- */
- @Override
- public boolean areSemanticElementsAffected(EObject listener, Object notification) {
- EStructuralFeature feature = getEStructuralFeature(notification);
- return isValidFeature(feature);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser#
- * getSemanticElementsBeingParsed (org.eclipse.emf.ecore.EObject)
- */
- @Override
- public List<?> getSemanticElementsBeingParsed(EObject element) {
- List<Element> semanticElementsBeingParsed = new ArrayList<Element>();
- if (element instanceof JoinNode) {
- JoinNode join = (JoinNode) element;
- semanticElementsBeingParsed.add(join);
- ValueSpecification valueSpec = join.getJoinSpec();
- if (valueSpec != null) {
- semanticElementsBeingParsed.add(valueSpec);
- }
- }
- return semanticElementsBeingParsed;
- }
-
- /**
- * Determines if the given feature has to be taken into account in this
- * parser
- *
- * @param feature
- * the feature to test
- * @return true if is valid, false otherwise
- */
- private boolean isValidFeature(EStructuralFeature feature) {
- if (feature == null){
- return false;
- }
- return UMLPackage.eINSTANCE.getNamedElement_Name().equals(feature) || UMLPackage.eINSTANCE.getJoinNode_JoinSpec().equals(feature) || (feature != null && ValueSpecification.class.isAssignableFrom(feature.getContainerClass()));
- }
-}
+/***************************************************************************** + * Copyright (c) 2009 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.emf.transaction.util.TransactionUtil; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.common.core.command.UnexecutableCommand; +import org.eclipse.gmf.runtime.diagram.ui.commands.CommandProxy; +import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand; +import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser; +import org.eclipse.papyrus.uml.diagram.activity.parsers.MessageFormatParser; +import org.eclipse.papyrus.uml.diagram.common.commands.SetValueSpecificationValueCommand; +import org.eclipse.papyrus.uml.tools.utils.ValueSpecificationUtil; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.JoinNode; +import org.eclipse.uml2.uml.UMLPackage; +import org.eclipse.uml2.uml.ValueSpecification; + +/** + * A specific parser for displaying the joinSpec of a Join Node. This parser + * refreshes the text displayed for the Join Node. + */ +public class JoinSpecParser extends MessageFormatParser implements ISemanticParser { + + /** The format for displaying the join spec */ + private static final String JOIN_SPEC_FORMAT = "{joinSpec = %s}"; + + public JoinSpecParser(EAttribute[] features, EAttribute[] editableFeatures) { + super(features, editableFeatures); + } + + public JoinSpecParser(EAttribute[] features) { + super(features); + } + + public JoinSpecParser() { + super(new EAttribute[] { UMLPackage.eINSTANCE.getNamedElement_Name() }); + } + + protected EStructuralFeature getEStructuralFeature(Object notification) { + EStructuralFeature featureImpl = null; + if (notification instanceof Notification) { + Object feature = ((Notification) notification).getFeature(); + if (feature instanceof EStructuralFeature) { + featureImpl = (EStructuralFeature) feature; + } + } + return featureImpl; + } + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.papyrus.uml.diagram.sequence.parsers.AbstractParser#isAffectingEvent + * (java.lang.Object , int) + */ + @Override + public boolean isAffectingEvent(Object event, int flags) { + EStructuralFeature feature = getEStructuralFeature(event); + return isValidFeature(feature); + } + + @Override + public String getEditString(IAdaptable adapter, int flags) { + // ensure valueLabel is never null + String valueLabel = ""; + Object obj = adapter.getAdapter(EObject.class); + if (obj instanceof JoinNode) { + JoinNode join = (JoinNode) obj; + ValueSpecification valueSpec = join.getJoinSpec(); + if (valueSpec != null) { + String value = ValueSpecificationUtil.getSpecificationValue(valueSpec); + if (value != null) { + valueLabel = value; + } + } + } + return valueLabel; + } + + @Override + public ICommand getParseCommand(IAdaptable adapter, String newString, int flags) { + Object obj = adapter.getAdapter(EObject.class); + TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(obj); + if (editingDomain == null) { + return UnexecutableCommand.INSTANCE; + } + if (obj instanceof JoinNode) { + JoinNode join = (JoinNode) obj; + ValueSpecification valueSpec = join.getJoinSpec(); + if (valueSpec != null) { + CompositeTransactionalCommand command = new CompositeTransactionalCommand(editingDomain, "Set Values"); //$NON-NLS-1$ + command.compose(new CommandProxy(new SetValueSpecificationValueCommand(valueSpec, newString))); + return command; + } + } + return UnexecutableCommand.INSTANCE; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.sequence.parsers.MessageFormatParser# + * getPrintString(org.eclipse .core.runtime.IAdaptable, int) + */ + @Override + public String getPrintString(IAdaptable element, int flags) { + // ensure valueLabel is never null + String valueLabel = getEditString(element, flags); + if (valueLabel.length() == 0) { + valueLabel = " "; + } else { + valueLabel = String.format(JOIN_SPEC_FORMAT, valueLabel); + } + return valueLabel; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser# + * areSemanticElementsAffected (org.eclipse.emf.ecore.EObject, + * java.lang.Object) + */ + @Override + public boolean areSemanticElementsAffected(EObject listener, Object notification) { + EStructuralFeature feature = getEStructuralFeature(notification); + return isValidFeature(feature); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser# + * getSemanticElementsBeingParsed (org.eclipse.emf.ecore.EObject) + */ + @Override + public List<?> getSemanticElementsBeingParsed(EObject element) { + List<Element> semanticElementsBeingParsed = new ArrayList<Element>(); + if (element instanceof JoinNode) { + JoinNode join = (JoinNode) element; + semanticElementsBeingParsed.add(join); + ValueSpecification valueSpec = join.getJoinSpec(); + if (valueSpec != null) { + semanticElementsBeingParsed.add(valueSpec); + } + } + return semanticElementsBeingParsed; + } + + /** + * Determines if the given feature has to be taken into account in this + * parser + * + * @param feature + * the feature to test + * @return true if is valid, false otherwise + */ + private boolean isValidFeature(EStructuralFeature feature) { + if (feature == null){ + return false; + } + return UMLPackage.eINSTANCE.getNamedElement_Name().equals(feature) || UMLPackage.eINSTANCE.getJoinNode_JoinSpec().equals(feature) || (feature != null && ValueSpecification.class.isAssignableFrom(feature.getContainerClass())); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectFlowSelectionParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectFlowSelectionParser.java index 5c15772460b..6a72d2b33e9 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectFlowSelectionParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectFlowSelectionParser.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * A specific parser for displaying the selection behavior associated to an
- * object flow.
- */
-public class ObjectFlowSelectionParser extends AssociatedBehaviorParser {
-
- /** The format for displaying object flow selection */
- private static final String SELECTION_FORMAT = "<<selection>>".concat(System.getProperty("line.separator")).concat("%s");
-
- /**
- * Get the format for displaying object flow selection
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getFormatString()
- * @return format string
- */
- @Override
- protected String getFormatString() {
- return SELECTION_FORMAT;
- }
-
- /**
- * Get the feature referencing the object flow selection
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getReferenceFeature()
- * @return feature
- */
- @Override
- protected EStructuralFeature getReferenceFeature() {
- return UMLPackage.eINSTANCE.getObjectFlow_Selection();
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * A specific parser for displaying the selection behavior associated to an + * object flow. + */ +public class ObjectFlowSelectionParser extends AssociatedBehaviorParser { + + /** The format for displaying object flow selection */ + private static final String SELECTION_FORMAT = "<<selection>>".concat(System.getProperty("line.separator")).concat("%s"); + + /** + * Get the format for displaying object flow selection + * + * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getFormatString() + * @return format string + */ + @Override + protected String getFormatString() { + return SELECTION_FORMAT; + } + + /** + * Get the feature referencing the object flow selection + * + * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getReferenceFeature() + * @return feature + */ + @Override + protected EStructuralFeature getReferenceFeature() { + return UMLPackage.eINSTANCE.getObjectFlow_Selection(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectFlowTransformationParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectFlowTransformationParser.java index 8d26b84cecc..f5e1ddfeda0 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectFlowTransformationParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectFlowTransformationParser.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * A specific parser for displaying the transformation behavior associated to an
- * object flow.
- */
-public class ObjectFlowTransformationParser extends AssociatedBehaviorParser {
-
- /** The format for displaying the object flow transformation */
- private static final String TRANSFORMATION_FORMAT = "<<transformation>>".concat(System.getProperty("line.separator")).concat("%s");
-
- /**
- * Get the format for displaying the object flow transformation
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getFormatString()
- * @return format string
- */
- @Override
- protected String getFormatString() {
- return TRANSFORMATION_FORMAT;
- }
-
- /**
- * Get the feature referencing the object flow transformation
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getReferenceFeature()
- * @return feature
- */
- @Override
- protected EStructuralFeature getReferenceFeature() {
- return UMLPackage.eINSTANCE.getObjectFlow_Transformation();
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * A specific parser for displaying the transformation behavior associated to an + * object flow. + */ +public class ObjectFlowTransformationParser extends AssociatedBehaviorParser { + + /** The format for displaying the object flow transformation */ + private static final String TRANSFORMATION_FORMAT = "<<transformation>>".concat(System.getProperty("line.separator")).concat("%s"); + + /** + * Get the format for displaying the object flow transformation + * + * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getFormatString() + * @return format string + */ + @Override + protected String getFormatString() { + return TRANSFORMATION_FORMAT; + } + + /** + * Get the feature referencing the object flow transformation + * + * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getReferenceFeature() + * @return feature + */ + @Override + protected EStructuralFeature getReferenceFeature() { + return UMLPackage.eINSTANCE.getObjectFlow_Transformation(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectNodeSelectionParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectNodeSelectionParser.java index dfe7f8d2731..50ba6f93fb0 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectNodeSelectionParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/ObjectNodeSelectionParser.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * A specific parser for displaying the selection behavior associated to an
- * object node.
- */
-public class ObjectNodeSelectionParser extends AssociatedBehaviorParser {
-
- /** The format for displaying Data Store selection */
- private static final String SELECTION_FORMAT = "<<selection>>".concat(System.getProperty("line.separator")).concat("%s");
-
- /**
- * Get the format for displaying Input decision
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getFormatString()
- * @return format string
- */
- @Override
- protected String getFormatString() {
- return SELECTION_FORMAT;
- }
-
- /**
- * Get the feature referencing the decision input
- *
- * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getReferenceFeature()
- * @return feature
- */
- @Override
- protected EStructuralFeature getReferenceFeature() {
- return UMLPackage.eINSTANCE.getObjectNode_Selection();
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * A specific parser for displaying the selection behavior associated to an + * object node. + */ +public class ObjectNodeSelectionParser extends AssociatedBehaviorParser { + + /** The format for displaying Data Store selection */ + private static final String SELECTION_FORMAT = "<<selection>>".concat(System.getProperty("line.separator")).concat("%s"); + + /** + * Get the format for displaying Input decision + * + * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getFormatString() + * @return format string + */ + @Override + protected String getFormatString() { + return SELECTION_FORMAT; + } + + /** + * Get the feature referencing the decision input + * + * @see org.eclipse.papyrus.uml.diagram.activity.parser.custom.AssociatedBehaviorParser#getReferenceFeature() + * @return feature + */ + @Override + protected EStructuralFeature getReferenceFeature() { + return UMLPackage.eINSTANCE.getObjectNode_Selection(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/StreamLabelParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/StreamLabelParser.java index 20528746a56..846956c23ea 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/StreamLabelParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/StreamLabelParser.java @@ -1,65 +1,65 @@ -/*****************************************************************************
- * Copyright (c) 2015 CEA LIST and others.
- *
- * 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:
- * CEA LIST - Initial API and implementation
- *
- *****************************************************************************/
-
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.common.core.command.ICommand;
-import org.eclipse.gmf.runtime.common.ui.services.parser.IParser;
-import org.eclipse.gmf.runtime.common.ui.services.parser.IParserEditStatus;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.uml2.uml.ActivityParameterNode;
-import org.eclipse.uml2.uml.Parameter;
-
-
-public class StreamLabelParser implements IParser {
-
- @Override
- public String getEditString(IAdaptable element, int flags) {
- return getPrintString(element, flags);
- }
-
- @Override
- public IParserEditStatus isValidEditString(IAdaptable element, String editString) {
- return null;
- }
-
- @Override
- public ICommand getParseCommand(IAdaptable element, String newString, int flags) {
- return null;
- }
-
- @Override
- public String getPrintString(IAdaptable element, int flags) {
- EObject object = element.getAdapter(EObject.class);
- if (false == object instanceof ActivityParameterNode) {
- return "";
- }
- Parameter parameter = ((ActivityParameterNode)object).getParameter();
- if (parameter == null || !parameter.isStream()) {
- return "";
- }
- return "{stream}";
- }
-
- @Override
- public boolean isAffectingEvent(Object event, int flags) {
- return false;
- }
-
- @Override
- public IContentAssistProcessor getCompletionProcessor(IAdaptable element) {
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2015 CEA LIST and others. + * + * 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: + * CEA LIST - Initial API and implementation + * + *****************************************************************************/ + +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.common.core.command.ICommand; +import org.eclipse.gmf.runtime.common.ui.services.parser.IParser; +import org.eclipse.gmf.runtime.common.ui.services.parser.IParserEditStatus; +import org.eclipse.jface.text.contentassist.IContentAssistProcessor; +import org.eclipse.uml2.uml.ActivityParameterNode; +import org.eclipse.uml2.uml.Parameter; + + +public class StreamLabelParser implements IParser { + + @Override + public String getEditString(IAdaptable element, int flags) { + return getPrintString(element, flags); + } + + @Override + public IParserEditStatus isValidEditString(IAdaptable element, String editString) { + return null; + } + + @Override + public ICommand getParseCommand(IAdaptable element, String newString, int flags) { + return null; + } + + @Override + public String getPrintString(IAdaptable element, int flags) { + EObject object = element.getAdapter(EObject.class); + if (false == object instanceof ActivityParameterNode) { + return ""; + } + Parameter parameter = ((ActivityParameterNode)object).getParameter(); + if (parameter == null || !parameter.isStream()) { + return ""; + } + return "{stream}"; + } + + @Override + public boolean isAffectingEvent(Object event, int flags) { + return false; + } + + @Override + public IContentAssistProcessor getCompletionProcessor(IAdaptable element) { + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/StructuredActivityNodeKeywordParser.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/StructuredActivityNodeKeywordParser.java index bd858cd67e6..485c239818a 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/StructuredActivityNodeKeywordParser.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/parser/custom/StructuredActivityNodeKeywordParser.java @@ -1,174 +1,174 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.parser.custom;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.common.notify.Notification;
-import org.eclipse.emf.ecore.EAttribute;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.EStructuralFeature;
-import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.parsers.MessageFormatParser;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants;
-import org.eclipse.uml2.uml.ConditionalNode;
-import org.eclipse.uml2.uml.Element;
-import org.eclipse.uml2.uml.ExpansionRegion;
-import org.eclipse.uml2.uml.LoopNode;
-import org.eclipse.uml2.uml.SequenceNode;
-import org.eclipse.uml2.uml.StructuredActivityNode;
-import org.eclipse.uml2.uml.UMLPackage;
-
-/**
- * A specific parser for displaying the keyword label of a
- * StructuredActivityNode. This parser refreshes the text displayed for the
- * StructuredActivityNode.
- */
-public class StructuredActivityNodeKeywordParser extends MessageFormatParser implements ISemanticParser {
-
- /** The String format for displaying the keyword */
- private static final String KEYWORD_FORMAT = "<<%s>>";
-
- /** Keyword structured */
- private static final Object STRUCTURED_KEYWORD = "structured";
-
- /** Specific loop ode Keyword */
- private static final Object LOOP_NODE_KEYWORD = "loop node";
-
- /** Specific conditional node Keyword */
- private static final Object CONDITIONAL_NODE_KEYWORD = "conditional";
-
- /** Specific sequence node Keyword */
- private static final Object SEQUENCE_NODE_KEYWORD = "sequence";
-
- /**
- * the preference store
- */
- private final IPreferenceStore preferenceStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
-
- public StructuredActivityNodeKeywordParser(EAttribute[] features, EAttribute[] editableFeatures) {
- super(features, editableFeatures);
- }
-
- public StructuredActivityNodeKeywordParser(EAttribute[] features) {
- super(features);
- }
-
- public StructuredActivityNodeKeywordParser() {
- super(new EAttribute[] { UMLPackage.eINSTANCE.getNamedElement_Name() });
- }
-
- protected EStructuralFeature getEStructuralFeature(Object notification) {
- EStructuralFeature featureImpl = null;
- if (notification instanceof Notification) {
- Object feature = ((Notification) notification).getFeature();
- if (feature instanceof EStructuralFeature) {
- featureImpl = (EStructuralFeature) feature;
- }
- }
- return featureImpl;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.papyrus.uml.diagram.sequence.parsers.AbstractParser#isAffectingEvent
- * (java.lang.Object , int)
- */
- @Override
- public boolean isAffectingEvent(Object event, int flags) {
- EStructuralFeature feature = getEStructuralFeature(event);
- return isValidFeature(feature);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.papyrus.uml.diagram.sequence.parsers.MessageFormatParser#
- * getPrintString(org.eclipse .core.runtime.IAdaptable, int)
- */
- @Override
- public String getPrintString(IAdaptable element, int flags) {
- Object obj = element.getAdapter(EObject.class);
- if (obj instanceof StructuredActivityNode) {
- if (obj instanceof ExpansionRegion) {
- ExpansionRegion region = (ExpansionRegion) obj;
- return String.format(KEYWORD_FORMAT, region.getMode().getName());
- } else if (obj instanceof LoopNode) {
- boolean displayNameName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_LOOP_NODE);
- if (displayNameName) {
- return String.format(KEYWORD_FORMAT, LOOP_NODE_KEYWORD);
- }
- } else if (obj instanceof ConditionalNode) {
- boolean displayNameName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_CONDITIONAL_NODE);
- if (displayNameName) {
- return String.format(KEYWORD_FORMAT, CONDITIONAL_NODE_KEYWORD);
- }
- } else if (obj instanceof SequenceNode) {
- boolean displayNameName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_SEQUENCE_NODE);
- if (displayNameName) {
- return String.format(KEYWORD_FORMAT, SEQUENCE_NODE_KEYWORD);
- }
- }
- return String.format(KEYWORD_FORMAT, STRUCTURED_KEYWORD);
- }
- return "";
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser#
- * areSemanticElementsAffected (org.eclipse.emf.ecore.EObject,
- * java.lang.Object)
- */
- @Override
- public boolean areSemanticElementsAffected(EObject listener, Object notification) {
- EStructuralFeature feature = getEStructuralFeature(notification);
- return isValidFeature(feature);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser#
- * getSemanticElementsBeingParsed (org.eclipse.emf.ecore.EObject)
- */
- @Override
- public List<?> getSemanticElementsBeingParsed(EObject element) {
- List<Element> semanticElementsBeingParsed = new ArrayList<Element>();
- if (element instanceof StructuredActivityNode) {
- StructuredActivityNode node = (StructuredActivityNode) element;
- semanticElementsBeingParsed.add(node);
- }
- return semanticElementsBeingParsed;
- }
-
- /**
- * Determines if the given feature has to be taken into account in this
- * parser
- *
- * @param feature
- * the feature to test
- * @return true if is valid, false otherwise
- */
- private boolean isValidFeature(EStructuralFeature feature) {
- return UMLPackage.eINSTANCE.getExpansionRegion_Mode().equals(feature);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.parser.custom; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.common.notify.Notification; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.parsers.MessageFormatParser; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.activity.preferences.IActivityPreferenceConstants; +import org.eclipse.uml2.uml.ConditionalNode; +import org.eclipse.uml2.uml.Element; +import org.eclipse.uml2.uml.ExpansionRegion; +import org.eclipse.uml2.uml.LoopNode; +import org.eclipse.uml2.uml.SequenceNode; +import org.eclipse.uml2.uml.StructuredActivityNode; +import org.eclipse.uml2.uml.UMLPackage; + +/** + * A specific parser for displaying the keyword label of a + * StructuredActivityNode. This parser refreshes the text displayed for the + * StructuredActivityNode. + */ +public class StructuredActivityNodeKeywordParser extends MessageFormatParser implements ISemanticParser { + + /** The String format for displaying the keyword */ + private static final String KEYWORD_FORMAT = "<<%s>>"; + + /** Keyword structured */ + private static final Object STRUCTURED_KEYWORD = "structured"; + + /** Specific loop ode Keyword */ + private static final Object LOOP_NODE_KEYWORD = "loop node"; + + /** Specific conditional node Keyword */ + private static final Object CONDITIONAL_NODE_KEYWORD = "conditional"; + + /** Specific sequence node Keyword */ + private static final Object SEQUENCE_NODE_KEYWORD = "sequence"; + + /** + * the preference store + */ + private final IPreferenceStore preferenceStore = UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + + public StructuredActivityNodeKeywordParser(EAttribute[] features, EAttribute[] editableFeatures) { + super(features, editableFeatures); + } + + public StructuredActivityNodeKeywordParser(EAttribute[] features) { + super(features); + } + + public StructuredActivityNodeKeywordParser() { + super(new EAttribute[] { UMLPackage.eINSTANCE.getNamedElement_Name() }); + } + + protected EStructuralFeature getEStructuralFeature(Object notification) { + EStructuralFeature featureImpl = null; + if (notification instanceof Notification) { + Object feature = ((Notification) notification).getFeature(); + if (feature instanceof EStructuralFeature) { + featureImpl = (EStructuralFeature) feature; + } + } + return featureImpl; + } + + /* + * (non-Javadoc) + * + * @see + * org.eclipse.papyrus.uml.diagram.sequence.parsers.AbstractParser#isAffectingEvent + * (java.lang.Object , int) + */ + @Override + public boolean isAffectingEvent(Object event, int flags) { + EStructuralFeature feature = getEStructuralFeature(event); + return isValidFeature(feature); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.papyrus.uml.diagram.sequence.parsers.MessageFormatParser# + * getPrintString(org.eclipse .core.runtime.IAdaptable, int) + */ + @Override + public String getPrintString(IAdaptable element, int flags) { + Object obj = element.getAdapter(EObject.class); + if (obj instanceof StructuredActivityNode) { + if (obj instanceof ExpansionRegion) { + ExpansionRegion region = (ExpansionRegion) obj; + return String.format(KEYWORD_FORMAT, region.getMode().getName()); + } else if (obj instanceof LoopNode) { + boolean displayNameName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_LOOP_NODE); + if (displayNameName) { + return String.format(KEYWORD_FORMAT, LOOP_NODE_KEYWORD); + } + } else if (obj instanceof ConditionalNode) { + boolean displayNameName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_CONDITIONAL_NODE); + if (displayNameName) { + return String.format(KEYWORD_FORMAT, CONDITIONAL_NODE_KEYWORD); + } + } else if (obj instanceof SequenceNode) { + boolean displayNameName = preferenceStore.getBoolean(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_SEQUENCE_NODE); + if (displayNameName) { + return String.format(KEYWORD_FORMAT, SEQUENCE_NODE_KEYWORD); + } + } + return String.format(KEYWORD_FORMAT, STRUCTURED_KEYWORD); + } + return ""; + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser# + * areSemanticElementsAffected (org.eclipse.emf.ecore.EObject, + * java.lang.Object) + */ + @Override + public boolean areSemanticElementsAffected(EObject listener, Object notification) { + EStructuralFeature feature = getEStructuralFeature(notification); + return isValidFeature(feature); + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.gmf.runtime.emf.ui.services.parser.ISemanticParser# + * getSemanticElementsBeingParsed (org.eclipse.emf.ecore.EObject) + */ + @Override + public List<?> getSemanticElementsBeingParsed(EObject element) { + List<Element> semanticElementsBeingParsed = new ArrayList<Element>(); + if (element instanceof StructuredActivityNode) { + StructuredActivityNode node = (StructuredActivityNode) element; + semanticElementsBeingParsed.add(node); + } + return semanticElementsBeingParsed; + } + + /** + * Determines if the given feature has to be taken into account in this + * parser + * + * @param feature + * the feature to test + * @return true if is valid, false otherwise + */ + private boolean isValidFeature(EStructuralFeature feature) { + return UMLPackage.eINSTANCE.getExpansionRegion_Mode().equals(feature); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/part/CustomMessages.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/part/CustomMessages.java index 22f7f026d9e..3f8ca62bd72 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/part/CustomMessages.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/part/CustomMessages.java @@ -1,204 +1,204 @@ -/*****************************************************************************
- * Copyright (c) 2013 CEA LIST
- *
- *
- * 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:
- * Patrick Tessier - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.part;
-
-import org.eclipse.osgi.util.NLS;
-
-/**
- * custom messages
- *
- * @author Patrick Tessier
- *
- */
-public class CustomMessages extends NLS {
-
- static {
- NLS.initializeMessages("custom-messages", CustomMessages.class); //$NON-NLS-1$
- }
-
- private CustomMessages() {
- }
-
- public static String UMLValidation_ErrorTitle;
-
- public static String UMLValidation_WarningTitle;
-
- public static String CreatePinsForObjectFlowDialog_Title;
-
- public static String CreatePinsForObjectFlowDialog_PinCreationTitle;
-
- public static String CreatePinsForObjectFlowDialog_PinCreationHelp;
-
- public static String CreatePinsForObjectFlowDialog_Name;
-
- public static String CreatePinsForObjectFlowDialog_Type;
-
- public static String PinAndParameterSynchronizer_UndeleteablePinTitle;
-
- public static String PinAndParameterSynchronizer_UndeleteablePinMessage;
-
- public static String PinAndParameterSynchronizer_UnauthorizedModificationTitle;
-
- public static String PinAndParameterSynchronizer_UnauthorizedModificationRedirection;
-
- public static String PinAndParameterSynchronizer_UnauthorizedModification;
-
- public static String ActivityParameterAndParameterSynchronizer_UnauthorizedModificationTitle;
-
- public static String ActivityParameterAndParameterSynchronizer_UnauthorizedModificationRedirection;
-
- public static String ConfirmPinAndParameterSync_Title;
-
- public static String ConfirmPinAndParameterSync_FromParameterMsg;
-
- public static String ConfirmActivityParameterAndParameterSync_Title;
-
- public static String ConfirmActivityParameterAndParameterSync_FromParameterMsg;
-
- public static String CreateCallActionDialog_OperationTitle;
-
- public static String CreateCallActionDialog_SelectOperation;
-
- public static String CreateCallActionDialog_CreateOperation;
-
- public static String CreateCallActionDialog_BehaviorTitle;
-
- public static String CreateCallActionDialog_SelectBehavior;
-
- public static String CreateCallActionDialog_CreateBehavior;
-
- public static String CreateCallActionDialog_SignalTitle;
-
- public static String CreateCallActionDialog_SelectSignal;
-
- public static String CreateCallActionDialog_CreateSignal;
-
- public static String CreateCallActionDialog_ParentLabel;
-
- public static String CreateCallActionDialog_NameLabel;
-
- public static String CreateCallActionDialog_TypeLabel;
-
- public static String CreateCallActionDialog_IsSynchronousTitle;
-
- public static String CreateCallActionDialog_IsSynchronousHelp;
-
- public static String CreateCallActionDialog_IsSynchronous;
-
- public static String CreateCallActionDialog_OperationInvocationCreationTitle;
-
- public static String CreateCallActionDialog_OperationInvocationCreationHelp;
-
- public static String CreateCallActionDialog_OperationInvocationSelectionTitle;
-
- public static String CreateCallActionDialog_BehaviorInvocationCreationTitle;
-
- public static String CreateCallActionDialog_BehaviorInvocationCreationHelp;
-
- public static String CreateCallActionDialog_BehaviorInvocationSelectionTitle;
-
- public static String CreateCallActionDialog_SignalInvocationCreationTitle;
-
- public static String CreateCallActionDialog_SignalInvocationCreationHelp;
-
- public static String CreateCallActionDialog_SignalInvocationSelectionTitle;
-
- public static String CreateActivityParameterNodeDialog_DialogTitle;
-
- public static String CreateActivityParameterNodeDialog_ParameterSelectionTitle;
-
- public static String CreateActivityParameterNodeDialog_ParameterSelectionHelp;
-
- public static String CreateActivityParameterNodeDialog_ParameterSelectionLabel;
-
- public static String CreateActivityParameterNodeDialog_ParameterCreationTitle;
-
- public static String CreateActivityParameterNodeDialog_ParameterCreationHelp;
-
- public static String CreateActivityParameterNodeDialog_ParameterCreationLabel;
-
- public static String CreateActivityParameterNodeDialog_NameLabel;
-
- public static String CreateActivityParameterNodeDialog_TypeLabel;
-
- public static String CreateActivityParameterNodeDialog_DirectionLabel;
-
- public static String CreateParameterDialog_WarnNoImpact;
-
- public static String CreateParameterDialog_WarnImpact;
-
- public static String CreateParameterDialog_Open;
-
- public static String CreateParameterDialog_DialogTitle;
-
- public static String CreateParameterDialog_ParameterCreationTitle;
-
- public static String CreateParameterDialog_ParameterCreationHelp;
-
- public static String CreateParameterDialog_NameLabel;
-
- public static String CreateParameterDialog_TypeLabel;
-
- public static String CreateParameterDialog_DirectionLabel;
-
- public static String CreateAttributeDialog_WarnNoImpact;
-
- public static String CreateAttributeDialog_WarnImpact;
-
- public static String CreateAttributeDialog_Open;
-
- public static String CreateAttributeDialog_DialogTitle;
-
- public static String CreateAttributeDialog_CreationTitle;
-
- public static String CreateAttributeDialog_NameLabel;
-
- public static String CreateAttributeDialog_EClassLabel;
-
- public static String CreateAttributeDialog_TypeLabel;
-
- public static String DiagramsPreferencePage_disableNotification;
-
- public static String DiagramsPreferencePage_notificationGroup_label;
-
- public static String DiagramsPreferencePage_confirmPinSyncFromParameter_label;
-
- public static String DiagramsPreferencePage_confirmActivityParameterNodeSyncFromParameter_label;
-
- public static String ActivityEdgePreferencePage_visibilityGroup;
-
- public static String ActivityEdgePreferencePage_showName;
-
- public static String ForkJoinSegmentSwitchOrientation_actionLabel;
-
- public static String ForkJoinSegmentSwitchOrientation_helpMessage;
-
- public static String SpecificKeywordStructuredActivityNodeVisibility_visibility;
-
- public static String StructuredActivityNodePreferencePage_showSpecificKeyword;
- // TODO: put accessor fields manually
-
- public static String BehaviorToCallBehaviorActionDropStrategy_Label;
- public static String BehaviorToCallBehaviorActionDropStrategy_Description;
-
- /**
- * @since 3.0
- */
- public static String AutomatedModelCompletionPreferencesInitializer_None;
-
- /**
- * @since 3.0
- */
- public static String AutomatedModelCompletionPreferencesInitializer_PinSynchronization;
-}
+/***************************************************************************** + * Copyright (c) 2013 CEA LIST + * + * + * 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: + * Patrick Tessier - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.part; + +import org.eclipse.osgi.util.NLS; + +/** + * custom messages + * + * @author Patrick Tessier + * + */ +public class CustomMessages extends NLS { + + static { + NLS.initializeMessages("custom-messages", CustomMessages.class); //$NON-NLS-1$ + } + + private CustomMessages() { + } + + public static String UMLValidation_ErrorTitle; + + public static String UMLValidation_WarningTitle; + + public static String CreatePinsForObjectFlowDialog_Title; + + public static String CreatePinsForObjectFlowDialog_PinCreationTitle; + + public static String CreatePinsForObjectFlowDialog_PinCreationHelp; + + public static String CreatePinsForObjectFlowDialog_Name; + + public static String CreatePinsForObjectFlowDialog_Type; + + public static String PinAndParameterSynchronizer_UndeleteablePinTitle; + + public static String PinAndParameterSynchronizer_UndeleteablePinMessage; + + public static String PinAndParameterSynchronizer_UnauthorizedModificationTitle; + + public static String PinAndParameterSynchronizer_UnauthorizedModificationRedirection; + + public static String PinAndParameterSynchronizer_UnauthorizedModification; + + public static String ActivityParameterAndParameterSynchronizer_UnauthorizedModificationTitle; + + public static String ActivityParameterAndParameterSynchronizer_UnauthorizedModificationRedirection; + + public static String ConfirmPinAndParameterSync_Title; + + public static String ConfirmPinAndParameterSync_FromParameterMsg; + + public static String ConfirmActivityParameterAndParameterSync_Title; + + public static String ConfirmActivityParameterAndParameterSync_FromParameterMsg; + + public static String CreateCallActionDialog_OperationTitle; + + public static String CreateCallActionDialog_SelectOperation; + + public static String CreateCallActionDialog_CreateOperation; + + public static String CreateCallActionDialog_BehaviorTitle; + + public static String CreateCallActionDialog_SelectBehavior; + + public static String CreateCallActionDialog_CreateBehavior; + + public static String CreateCallActionDialog_SignalTitle; + + public static String CreateCallActionDialog_SelectSignal; + + public static String CreateCallActionDialog_CreateSignal; + + public static String CreateCallActionDialog_ParentLabel; + + public static String CreateCallActionDialog_NameLabel; + + public static String CreateCallActionDialog_TypeLabel; + + public static String CreateCallActionDialog_IsSynchronousTitle; + + public static String CreateCallActionDialog_IsSynchronousHelp; + + public static String CreateCallActionDialog_IsSynchronous; + + public static String CreateCallActionDialog_OperationInvocationCreationTitle; + + public static String CreateCallActionDialog_OperationInvocationCreationHelp; + + public static String CreateCallActionDialog_OperationInvocationSelectionTitle; + + public static String CreateCallActionDialog_BehaviorInvocationCreationTitle; + + public static String CreateCallActionDialog_BehaviorInvocationCreationHelp; + + public static String CreateCallActionDialog_BehaviorInvocationSelectionTitle; + + public static String CreateCallActionDialog_SignalInvocationCreationTitle; + + public static String CreateCallActionDialog_SignalInvocationCreationHelp; + + public static String CreateCallActionDialog_SignalInvocationSelectionTitle; + + public static String CreateActivityParameterNodeDialog_DialogTitle; + + public static String CreateActivityParameterNodeDialog_ParameterSelectionTitle; + + public static String CreateActivityParameterNodeDialog_ParameterSelectionHelp; + + public static String CreateActivityParameterNodeDialog_ParameterSelectionLabel; + + public static String CreateActivityParameterNodeDialog_ParameterCreationTitle; + + public static String CreateActivityParameterNodeDialog_ParameterCreationHelp; + + public static String CreateActivityParameterNodeDialog_ParameterCreationLabel; + + public static String CreateActivityParameterNodeDialog_NameLabel; + + public static String CreateActivityParameterNodeDialog_TypeLabel; + + public static String CreateActivityParameterNodeDialog_DirectionLabel; + + public static String CreateParameterDialog_WarnNoImpact; + + public static String CreateParameterDialog_WarnImpact; + + public static String CreateParameterDialog_Open; + + public static String CreateParameterDialog_DialogTitle; + + public static String CreateParameterDialog_ParameterCreationTitle; + + public static String CreateParameterDialog_ParameterCreationHelp; + + public static String CreateParameterDialog_NameLabel; + + public static String CreateParameterDialog_TypeLabel; + + public static String CreateParameterDialog_DirectionLabel; + + public static String CreateAttributeDialog_WarnNoImpact; + + public static String CreateAttributeDialog_WarnImpact; + + public static String CreateAttributeDialog_Open; + + public static String CreateAttributeDialog_DialogTitle; + + public static String CreateAttributeDialog_CreationTitle; + + public static String CreateAttributeDialog_NameLabel; + + public static String CreateAttributeDialog_EClassLabel; + + public static String CreateAttributeDialog_TypeLabel; + + public static String DiagramsPreferencePage_disableNotification; + + public static String DiagramsPreferencePage_notificationGroup_label; + + public static String DiagramsPreferencePage_confirmPinSyncFromParameter_label; + + public static String DiagramsPreferencePage_confirmActivityParameterNodeSyncFromParameter_label; + + public static String ActivityEdgePreferencePage_visibilityGroup; + + public static String ActivityEdgePreferencePage_showName; + + public static String ForkJoinSegmentSwitchOrientation_actionLabel; + + public static String ForkJoinSegmentSwitchOrientation_helpMessage; + + public static String SpecificKeywordStructuredActivityNodeVisibility_visibility; + + public static String StructuredActivityNodePreferencePage_showSpecificKeyword; + // TODO: put accessor fields manually + + public static String BehaviorToCallBehaviorActionDropStrategy_Label; + public static String BehaviorToCallBehaviorActionDropStrategy_Description; + + /** + * @since 3.0 + */ + public static String AutomatedModelCompletionPreferencesInitializer_None; + + /** + * @since 3.0 + */ + public static String AutomatedModelCompletionPreferencesInitializer_PinSynchronization; +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/ActivityEdgeLabelVisibilityGroup.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/ActivityEdgeLabelVisibilityGroup.java index af5a8436e18..274876493fb 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/ActivityEdgeLabelVisibilityGroup.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/ActivityEdgeLabelVisibilityGroup.java @@ -1,64 +1,64 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.preferences;
-
-import org.eclipse.jface.dialogs.DialogPage;
-import org.eclipse.jface.preference.BooleanFieldEditor;
-import org.eclipse.papyrus.infra.gmfdiag.preferences.ui.AbstractGroup;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-
-/**
- * The Class ActivityEdgeLabelVisibilityGroup contains editor to edit
- * preferences concerning the visibility of labels of an ActivityEdge
- */
-public class ActivityEdgeLabelVisibilityGroup extends AbstractGroup {
-
- /** Editor for deciding to show the name label */
- private BooleanFieldEditor showNameLabelBooleanFieldEditor;
-
- /**
- * Creation of an ActivityEdgeLabelVisibilityGroup Composite.
- *
- * @param parent
- * the parent of the composite
- * @param dialogPage
- * to set the page in field editor
- * @param title
- * the title
- */
- public ActivityEdgeLabelVisibilityGroup(Composite parent, String title, DialogPage dialogPage) {
- super(parent, title, dialogPage);
- createContent(parent);
- }
-
- /**
- * Creates the content.
- *
- * @param parent
- * the parent
- */
- public void createContent(Composite parent) {
- Group visibilityGroup = new Group(parent, SWT.SCROLL_PAGE);
- visibilityGroup.setLayout(new GridLayout());
- visibilityGroup.setText(CustomMessages.ActivityEdgePreferencePage_visibilityGroup);
- // field for name label visibility
- showNameLabelBooleanFieldEditor = new BooleanFieldEditor(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL, CustomMessages.ActivityEdgePreferencePage_showName, visibilityGroup);
- showNameLabelBooleanFieldEditor.setPage(dialogPage);
- addFieldEditor(showNameLabelBooleanFieldEditor);
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.preferences; + +import org.eclipse.jface.dialogs.DialogPage; +import org.eclipse.jface.preference.BooleanFieldEditor; +import org.eclipse.papyrus.infra.gmfdiag.preferences.ui.AbstractGroup; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Group; + +/** + * The Class ActivityEdgeLabelVisibilityGroup contains editor to edit + * preferences concerning the visibility of labels of an ActivityEdge + */ +public class ActivityEdgeLabelVisibilityGroup extends AbstractGroup { + + /** Editor for deciding to show the name label */ + private BooleanFieldEditor showNameLabelBooleanFieldEditor; + + /** + * Creation of an ActivityEdgeLabelVisibilityGroup Composite. + * + * @param parent + * the parent of the composite + * @param dialogPage + * to set the page in field editor + * @param title + * the title + */ + public ActivityEdgeLabelVisibilityGroup(Composite parent, String title, DialogPage dialogPage) { + super(parent, title, dialogPage); + createContent(parent); + } + + /** + * Creates the content. + * + * @param parent + * the parent + */ + public void createContent(Composite parent) { + Group visibilityGroup = new Group(parent, SWT.SCROLL_PAGE); + visibilityGroup.setLayout(new GridLayout()); + visibilityGroup.setText(CustomMessages.ActivityEdgePreferencePage_visibilityGroup); + // field for name label visibility + showNameLabelBooleanFieldEditor = new BooleanFieldEditor(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL, CustomMessages.ActivityEdgePreferencePage_showName, visibilityGroup); + showNameLabelBooleanFieldEditor.setPage(dialogPage); + addFieldEditor(showNameLabelBooleanFieldEditor); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/DiagramSpecificPreferenceInitializer.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/DiagramSpecificPreferenceInitializer.java index 483a9afe2b1..607ba68e3c9 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/DiagramSpecificPreferenceInitializer.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/DiagramSpecificPreferenceInitializer.java @@ -1,67 +1,67 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.preferences;
-
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-
-/**
- * This preference initializer initializes diagram preferences specific to the
- * activity diagram.
- */
-public class DiagramSpecificPreferenceInitializer extends AbstractPreferenceInitializer {
-
- /**
- * Initialize default preferences specific to the activity diagram
- */
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = getPreferenceStore();
- DiagramGeneralPreferencePage.initSpecificDefaults(store);
- // preference for showing Activity edge name is common to several pages
- store.setDefault(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL, true);
- // preferences for keeping user choices are not displayed
- store.setDefault(IActivityPreferenceConstants.PREF_NEW_CALL_BEHAVIOR_ACTION_SELECT_AS_DEFAULT, false);
- store.setDefault(IActivityPreferenceConstants.PREF_NEW_CALL_OPERATION_ACTION_SELECT_AS_DEFAULT, true);
- store.setDefault(IActivityPreferenceConstants.PREF_NEW_SEND_SIGNAL_ACTION_SELECT_AS_DEFAULT, false);
- store.setDefault(IActivityPreferenceConstants.PREF_NEW_CALL_BEHAVIOR_ACTION_CREATION_OWNER, "");
- store.setDefault(IActivityPreferenceConstants.PREF_NEW_CALL_OPERATION_ACTION_CREATION_OWNER, "");
- store.setDefault(IActivityPreferenceConstants.PREF_NEW_SEND_SIGNAL_ACTION_CREATION_OWNER, "");
- // Specific preferences for groups
- // Opacity Preferences
- store.setDefault(IActivityPreferenceConstants.PREF_ACTIVITY_PARTITION_ALPHA, 50);
- store.setDefault(IActivityPreferenceConstants.PREF_CONDITIONAL_NODE_ALPHA, 50);
- store.setDefault(IActivityPreferenceConstants.PREF_SEQUENCE_NODE_ALPHA, 50);
- store.setDefault(IActivityPreferenceConstants.PREF_EXPANSION_REGION_ALPHA, 50);
- store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_NODE_ALPHA, 50); // TODO
- store.setDefault(IActivityPreferenceConstants.PREF_LOOP_NODE_ALPHA, 50);
- // Show Specific label preferences
- store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_CONDITIONAL_NODE, true);
- store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_LOOP_NODE, true);
- store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_SEQUENCE_NODE, true);
- store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_STRUCTURED_NODE, true);
- // Automated Model Completion Preferences
- AutomatedModelCompletionPreferencesInitializer automatedModelCompletionPreferencesInitializer = new AutomatedModelCompletionPreferencesInitializer();
- automatedModelCompletionPreferencesInitializer.initializeDefaultPreferences();
- }
-
- /**
- * Get the preference store
- */
- protected IPreferenceStore getPreferenceStore() {
- return UMLDiagramEditorPlugin.getInstance().getPreferenceStore();
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.preferences; + +import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.papyrus.uml.diagram.activity.edit.utils.updater.preferences.AutomatedModelCompletionPreferencesInitializer; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; + +/** + * This preference initializer initializes diagram preferences specific to the + * activity diagram. + */ +public class DiagramSpecificPreferenceInitializer extends AbstractPreferenceInitializer { + + /** + * Initialize default preferences specific to the activity diagram + */ + @Override + public void initializeDefaultPreferences() { + IPreferenceStore store = getPreferenceStore(); + DiagramGeneralPreferencePage.initSpecificDefaults(store); + // preference for showing Activity edge name is common to several pages + store.setDefault(IActivityPreferenceConstants.PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL, true); + // preferences for keeping user choices are not displayed + store.setDefault(IActivityPreferenceConstants.PREF_NEW_CALL_BEHAVIOR_ACTION_SELECT_AS_DEFAULT, false); + store.setDefault(IActivityPreferenceConstants.PREF_NEW_CALL_OPERATION_ACTION_SELECT_AS_DEFAULT, true); + store.setDefault(IActivityPreferenceConstants.PREF_NEW_SEND_SIGNAL_ACTION_SELECT_AS_DEFAULT, false); + store.setDefault(IActivityPreferenceConstants.PREF_NEW_CALL_BEHAVIOR_ACTION_CREATION_OWNER, ""); + store.setDefault(IActivityPreferenceConstants.PREF_NEW_CALL_OPERATION_ACTION_CREATION_OWNER, ""); + store.setDefault(IActivityPreferenceConstants.PREF_NEW_SEND_SIGNAL_ACTION_CREATION_OWNER, ""); + // Specific preferences for groups + // Opacity Preferences + store.setDefault(IActivityPreferenceConstants.PREF_ACTIVITY_PARTITION_ALPHA, 50); + store.setDefault(IActivityPreferenceConstants.PREF_CONDITIONAL_NODE_ALPHA, 50); + store.setDefault(IActivityPreferenceConstants.PREF_SEQUENCE_NODE_ALPHA, 50); + store.setDefault(IActivityPreferenceConstants.PREF_EXPANSION_REGION_ALPHA, 50); + store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_NODE_ALPHA, 50); // TODO + store.setDefault(IActivityPreferenceConstants.PREF_LOOP_NODE_ALPHA, 50); + // Show Specific label preferences + store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_CONDITIONAL_NODE, true); + store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_LOOP_NODE, true); + store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_SEQUENCE_NODE, true); + store.setDefault(IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_STRUCTURED_NODE, true); + // Automated Model Completion Preferences + AutomatedModelCompletionPreferencesInitializer automatedModelCompletionPreferencesInitializer = new AutomatedModelCompletionPreferencesInitializer(); + automatedModelCompletionPreferencesInitializer.initializeDefaultPreferences(); + } + + /** + * Get the preference store + */ + protected IPreferenceStore getPreferenceStore() { + return UMLDiagramEditorPlugin.getInstance().getPreferenceStore(); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/IActivityPreferenceConstants.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/IActivityPreferenceConstants.java index 37626fb1c3e..94274e03b5f 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/IActivityPreferenceConstants.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/IActivityPreferenceConstants.java @@ -1,134 +1,134 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.preferences;
-
-/**
- * Defines specific preference constants for the UML activity diagram.
- *
- * @noimplement This interface is not intended to be implemented by clients.
- */
-public interface IActivityPreferenceConstants {
-
- /**
- * the preference for opening the confirmation popup when an attribute
- * property or a parameter is modified. This popup warns the user that
- * invoking actions will be updated with a pin reorganization.
- */
- public static final String PREF_CONFIRM_PIN_SYNC_FROM_PARAMETER = "org.eclipse.papyrus.uml.diagram.activity.confirmPinSyncFromParameter"; //$NON-NLS-1$
-
- /**
- * the preference for opening the confirmation popup when a parameter is
- * removed. This popup warns the user that associated activity parameter
- * nodes will be removed too.
- */
- public static final String PREF_CONFIRM_ACTIVITY_PARAMETER_SYNC_FROM_PARAMETER = "org.eclipse.papyrus.uml.diagram.activity.confirmActivityParameterSyncFromParameter"; //$NON-NLS-1$
-
- /**
- * the preference for displaying the name label of an activity edge.
- */
- public static final String PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL = "org.eclipse.papyrus.uml.diagram.activity.ActivityEdge.showNameLabel"; //$NON-NLS-1$
-
- /**
- * the preference for displaying the specific label of the descent of
- * structured activity node (LoopNode , ConditionalNode ...)
- */
- public static final String PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_LOOP_NODE = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.specificLabel.loopNode"; //$NON-NLS-1$
-
- /**
- * the preference for displaying the specific label of the descent of
- * structured activity node (LoopNode , ConditionalNode ...)
- */
- public static final String PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_CONDITIONAL_NODE = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.specificLabel.conditionalNode"; //$NON-NLS-1$
-
- /**
- * the preference for displaying the specific label of the descent of
- * structured activity node (LoopNode , ConditionalNode ...)
- */
- public static final String PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_SEQUENCE_NODE = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.specificLabel.sequenceNode"; //$NON-NLS-1$
-
- /**
- * the preference for displaying the specific label of the descent of
- * structured activity node (LoopNode , ConditionalNode ...)
- */
- public static final String PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_STRUCTURED_NODE = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.specificLabel.structuredNode"; //$NON-NLS-1$
-
- /**
- * Alpha of the following figure
- */
- public static final String PREF_ACTIVITY_PARTITION_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.activityPartition"; //$NON-NLS-1$
-
- /**
- * Alpha of the following figure
- */
- public static final String PREF_STRUCTURED_NODE_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.structuredNode"; //$NON-NLS-1$
-
- /**
- * Alpha of the following figure
- */
- public static final String PREF_LOOP_NODE_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.loopNode"; //$NON-NLS-1$
-
- /**
- * Alpha of the following figure
- */
- public static final String PREF_CONDITIONAL_NODE_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.conditionalNode"; //$NON-NLS-1$
-
- /**
- * Alpha of the following figure
- */
- public static final String PREF_SEQUENCE_NODE_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.sequenceNode"; //$NON-NLS-1$
-
- /**
- * Alpha of the following figure
- */
- public static final String PREF_EXPANSION_REGION_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.conditionalNode"; //$NON-NLS-1$
-
- /**
- * the preference for keeping user's choice of whether select or create
- * option is selected in the CallBehaviorAction creation dialog.
- */
- public static final String PREF_NEW_CALL_BEHAVIOR_ACTION_SELECT_AS_DEFAULT = "org.eclipse.papyrus.uml.diagram.activity.CallBehaviorAction.CreateDialog.selectAsDefault"; //$NON-NLS-1$
-
- /**
- * the preference for keeping user's choice of whether select or create
- * option is selected in the CallOperationAction creation dialog.
- */
- public static final String PREF_NEW_CALL_OPERATION_ACTION_SELECT_AS_DEFAULT = "org.eclipse.papyrus.uml.diagram.activity.CallOperationAction.CreateDialog.selectAsDefault"; //$NON-NLS-1$
-
- /**
- * the preference for keeping user's choice of whether select or create
- * option is selected in the SendSignalAction creation dialog.
- */
- public static final String PREF_NEW_SEND_SIGNAL_ACTION_SELECT_AS_DEFAULT = "org.eclipse.papyrus.uml.diagram.activity.SendSignalAction.CreateDialog.selectAsDefault"; //$NON-NLS-1$
-
- /**
- * the preference for keeping user's choice of which is the default owner's
- * URI of the new created Behavior in the CallBehaviorAction creation dialog
- * in a given resource.
- */
- public static final String PREF_NEW_CALL_BEHAVIOR_ACTION_CREATION_OWNER = "org.eclipse.papyrus.uml.diagram.activity.CallBehaviorAction.CreateDialog.owner"; //$NON-NLS-1$
-
- /**
- * the preference for keeping user's choice of which is the default owner's
- * URI of the new created Operation in the CallOperationAction creation
- * dialog in a given resource.
- */
- public static final String PREF_NEW_CALL_OPERATION_ACTION_CREATION_OWNER = "org.eclipse.papyrus.uml.diagram.activity.CallOperationAction.CreateDialog.owner"; //$NON-NLS-1$
-
- /**
- * the preference for keeping user's choice of which is the default owner's
- * URI of the new created Signal in the SendSignalAction creation dialog in
- * a given resource.
- */
- public static final String PREF_NEW_SEND_SIGNAL_ACTION_CREATION_OWNER = "org.eclipse.papyrus.uml.diagram.activity.SendSignalAction.CreateDialog.owner"; //$NON-NLS-1$
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.preferences; + +/** + * Defines specific preference constants for the UML activity diagram. + * + * @noimplement This interface is not intended to be implemented by clients. + */ +public interface IActivityPreferenceConstants { + + /** + * the preference for opening the confirmation popup when an attribute + * property or a parameter is modified. This popup warns the user that + * invoking actions will be updated with a pin reorganization. + */ + public static final String PREF_CONFIRM_PIN_SYNC_FROM_PARAMETER = "org.eclipse.papyrus.uml.diagram.activity.confirmPinSyncFromParameter"; //$NON-NLS-1$ + + /** + * the preference for opening the confirmation popup when a parameter is + * removed. This popup warns the user that associated activity parameter + * nodes will be removed too. + */ + public static final String PREF_CONFIRM_ACTIVITY_PARAMETER_SYNC_FROM_PARAMETER = "org.eclipse.papyrus.uml.diagram.activity.confirmActivityParameterSyncFromParameter"; //$NON-NLS-1$ + + /** + * the preference for displaying the name label of an activity edge. + */ + public static final String PREF_ACTIVITY_EDGE_SHOW_NAME_LABEL = "org.eclipse.papyrus.uml.diagram.activity.ActivityEdge.showNameLabel"; //$NON-NLS-1$ + + /** + * the preference for displaying the specific label of the descent of + * structured activity node (LoopNode , ConditionalNode ...) + */ + public static final String PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_LOOP_NODE = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.specificLabel.loopNode"; //$NON-NLS-1$ + + /** + * the preference for displaying the specific label of the descent of + * structured activity node (LoopNode , ConditionalNode ...) + */ + public static final String PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_CONDITIONAL_NODE = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.specificLabel.conditionalNode"; //$NON-NLS-1$ + + /** + * the preference for displaying the specific label of the descent of + * structured activity node (LoopNode , ConditionalNode ...) + */ + public static final String PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_SEQUENCE_NODE = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.specificLabel.sequenceNode"; //$NON-NLS-1$ + + /** + * the preference for displaying the specific label of the descent of + * structured activity node (LoopNode , ConditionalNode ...) + */ + public static final String PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_STRUCTURED_NODE = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.specificLabel.structuredNode"; //$NON-NLS-1$ + + /** + * Alpha of the following figure + */ + public static final String PREF_ACTIVITY_PARTITION_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.activityPartition"; //$NON-NLS-1$ + + /** + * Alpha of the following figure + */ + public static final String PREF_STRUCTURED_NODE_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.structuredNode"; //$NON-NLS-1$ + + /** + * Alpha of the following figure + */ + public static final String PREF_LOOP_NODE_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.loopNode"; //$NON-NLS-1$ + + /** + * Alpha of the following figure + */ + public static final String PREF_CONDITIONAL_NODE_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.conditionalNode"; //$NON-NLS-1$ + + /** + * Alpha of the following figure + */ + public static final String PREF_SEQUENCE_NODE_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.sequenceNode"; //$NON-NLS-1$ + + /** + * Alpha of the following figure + */ + public static final String PREF_EXPANSION_REGION_ALPHA = "org.eclipse.papyrus.uml.diagram.activity.StructuredActivityNode.alpha.conditionalNode"; //$NON-NLS-1$ + + /** + * the preference for keeping user's choice of whether select or create + * option is selected in the CallBehaviorAction creation dialog. + */ + public static final String PREF_NEW_CALL_BEHAVIOR_ACTION_SELECT_AS_DEFAULT = "org.eclipse.papyrus.uml.diagram.activity.CallBehaviorAction.CreateDialog.selectAsDefault"; //$NON-NLS-1$ + + /** + * the preference for keeping user's choice of whether select or create + * option is selected in the CallOperationAction creation dialog. + */ + public static final String PREF_NEW_CALL_OPERATION_ACTION_SELECT_AS_DEFAULT = "org.eclipse.papyrus.uml.diagram.activity.CallOperationAction.CreateDialog.selectAsDefault"; //$NON-NLS-1$ + + /** + * the preference for keeping user's choice of whether select or create + * option is selected in the SendSignalAction creation dialog. + */ + public static final String PREF_NEW_SEND_SIGNAL_ACTION_SELECT_AS_DEFAULT = "org.eclipse.papyrus.uml.diagram.activity.SendSignalAction.CreateDialog.selectAsDefault"; //$NON-NLS-1$ + + /** + * the preference for keeping user's choice of which is the default owner's + * URI of the new created Behavior in the CallBehaviorAction creation dialog + * in a given resource. + */ + public static final String PREF_NEW_CALL_BEHAVIOR_ACTION_CREATION_OWNER = "org.eclipse.papyrus.uml.diagram.activity.CallBehaviorAction.CreateDialog.owner"; //$NON-NLS-1$ + + /** + * the preference for keeping user's choice of which is the default owner's + * URI of the new created Operation in the CallOperationAction creation + * dialog in a given resource. + */ + public static final String PREF_NEW_CALL_OPERATION_ACTION_CREATION_OWNER = "org.eclipse.papyrus.uml.diagram.activity.CallOperationAction.CreateDialog.owner"; //$NON-NLS-1$ + + /** + * the preference for keeping user's choice of which is the default owner's + * URI of the new created Signal in the SendSignalAction creation dialog in + * a given resource. + */ + public static final String PREF_NEW_SEND_SIGNAL_ACTION_CREATION_OWNER = "org.eclipse.papyrus.uml.diagram.activity.SendSignalAction.CreateDialog.owner"; //$NON-NLS-1$ +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/SpecificKeywordStructuredActivityNodeVisibility.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/SpecificKeywordStructuredActivityNodeVisibility.java index d973570a149..d8e7dd1de6d 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/SpecificKeywordStructuredActivityNodeVisibility.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/preferences/SpecificKeywordStructuredActivityNodeVisibility.java @@ -1,91 +1,91 @@ -/*****************************************************************************
- * Copyright (c) 2011 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.preferences;
-
-import org.eclipse.jface.dialogs.DialogPage;
-import org.eclipse.jface.preference.BooleanFieldEditor;
-import org.eclipse.papyrus.infra.gmfdiag.preferences.ui.AbstractGroup;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-
-/**
- * Preference group to define whether the specific keyword of the descendant of
- * structured activity node has to be displayed of not
- *
- * @author adaussy
- *
- */
-public class SpecificKeywordStructuredActivityNodeVisibility extends AbstractGroup {
-
- public enum ElementType {
- LOOP_NODE, CONDITIONAL_NODE, SEQUENCE_NODE
- }
-
- /**
- * if true then display the specific label
- */
- private BooleanFieldEditor specificKeywordVisibility;
-
- /**
- * Type of the element
- */
- private ElementType type;
-
- /**
- *
- * Constructor.
- *
- * @param parent
- * @param key
- * @param dialogPage
- */
- public SpecificKeywordStructuredActivityNodeVisibility(Composite parent, String key, DialogPage dialogPage, ElementType type) {
- super(parent, key, dialogPage);
- this.type = type;
- createContent(parent);
- }
-
- /**
- * Creates the content.
- *
- * @param parent
- * the parent
- */
- public void createContent(Composite parent) {
- Group visibilityGroup = new Group(parent, SWT.SCROLL_PAGE);
- visibilityGroup.setLayout(new GridLayout());
- visibilityGroup.setText(CustomMessages.SpecificKeywordStructuredActivityNodeVisibility_visibility);
- String preferenceName;
- switch (this.type) {
- case LOOP_NODE:
- preferenceName = IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_LOOP_NODE;
- break;
- case CONDITIONAL_NODE:
- preferenceName = IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_CONDITIONAL_NODE;
- break;
- case SEQUENCE_NODE:
- preferenceName = IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_SEQUENCE_NODE;
- break;
- default:
- preferenceName = "";
- break;
- }
- specificKeywordVisibility = new BooleanFieldEditor(preferenceName, CustomMessages.StructuredActivityNodePreferencePage_showSpecificKeyword, visibilityGroup);
- specificKeywordVisibility.setPage(dialogPage);
- addFieldEditor(specificKeywordVisibility);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.preferences; + +import org.eclipse.jface.dialogs.DialogPage; +import org.eclipse.jface.preference.BooleanFieldEditor; +import org.eclipse.papyrus.infra.gmfdiag.preferences.ui.AbstractGroup; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Group; + +/** + * Preference group to define whether the specific keyword of the descendant of + * structured activity node has to be displayed of not + * + * @author adaussy + * + */ +public class SpecificKeywordStructuredActivityNodeVisibility extends AbstractGroup { + + public enum ElementType { + LOOP_NODE, CONDITIONAL_NODE, SEQUENCE_NODE + } + + /** + * if true then display the specific label + */ + private BooleanFieldEditor specificKeywordVisibility; + + /** + * Type of the element + */ + private ElementType type; + + /** + * + * Constructor. + * + * @param parent + * @param key + * @param dialogPage + */ + public SpecificKeywordStructuredActivityNodeVisibility(Composite parent, String key, DialogPage dialogPage, ElementType type) { + super(parent, key, dialogPage); + this.type = type; + createContent(parent); + } + + /** + * Creates the content. + * + * @param parent + * the parent + */ + public void createContent(Composite parent) { + Group visibilityGroup = new Group(parent, SWT.SCROLL_PAGE); + visibilityGroup.setLayout(new GridLayout()); + visibilityGroup.setText(CustomMessages.SpecificKeywordStructuredActivityNodeVisibility_visibility); + String preferenceName; + switch (this.type) { + case LOOP_NODE: + preferenceName = IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_LOOP_NODE; + break; + case CONDITIONAL_NODE: + preferenceName = IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_CONDITIONAL_NODE; + break; + case SEQUENCE_NODE: + preferenceName = IActivityPreferenceConstants.PREF_STRUCTURED_SPECIFIC_KEYWORD_DISPLAY_SEQUENCE_NODE; + break; + default: + preferenceName = ""; + break; + } + specificKeywordVisibility = new BooleanFieldEditor(preferenceName, CustomMessages.StructuredActivityNodePreferencePage_showSpecificKeyword, visibilityGroup); + specificKeywordVisibility.setPage(dialogPage); + addFieldEditor(specificKeywordVisibility); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/providers/ActivityDiagramContributionPolicyClass.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/providers/ActivityDiagramContributionPolicyClass.java index fcd54d9070f..9880566ac67 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/providers/ActivityDiagramContributionPolicyClass.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/providers/ActivityDiagramContributionPolicyClass.java @@ -1,49 +1,49 @@ -/*****************************************************************************
- * Copyright (c) 2011 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.providers;
-
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.gmf.runtime.common.ui.services.action.contributionitem.IPopupMenuContributionPolicy;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityDiagramEditPart;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Reduce the scope of the Menu contribution of the Activity Diagram. implements {@link IPopupMenuContributionPolicy}
- *
- * @author adaussy
- *
- */
-public class ActivityDiagramContributionPolicyClass implements IPopupMenuContributionPolicy {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean appliesTo(ISelection selection, IConfigurationElement configuration) {
- IEditorPart editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- if (editorPart instanceof IMultiDiagramEditor) {
- editorPart = ((IMultiDiagramEditor) editorPart).getActiveEditor();
- if (editorPart instanceof DiagramEditor) {
- DiagramEditPart host = ((DiagramEditor) editorPart).getDiagramEditPart();
- return ActivityDiagramEditPart.MODEL_ID.equals(host.getDiagramView().getType());
- }
- }
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.providers; + +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.gmf.runtime.common.ui.services.action.contributionitem.IPopupMenuContributionPolicy; +import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart; +import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ActivityDiagramEditPart; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.PlatformUI; + +/** + * Reduce the scope of the Menu contribution of the Activity Diagram. implements {@link IPopupMenuContributionPolicy} + * + * @author adaussy + * + */ +public class ActivityDiagramContributionPolicyClass implements IPopupMenuContributionPolicy { + + /** + * {@inheritDoc} + */ + @Override + public boolean appliesTo(ISelection selection, IConfigurationElement configuration) { + IEditorPart editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); + if (editorPart instanceof IMultiDiagramEditor) { + editorPart = ((IMultiDiagramEditor) editorPart).getActiveEditor(); + if (editorPart instanceof DiagramEditor) { + DiagramEditPart host = ((DiagramEditor) editorPart).getDiagramEditPart(); + return ActivityDiagramEditPart.MODEL_ID.equals(host.getDiagramView().getType()); + } + } + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/providers/CustomUMLEditPartProvider.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/providers/CustomUMLEditPartProvider.java index 8e62f7bfd73..7ee538ddbb2 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/providers/CustomUMLEditPartProvider.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/providers/CustomUMLEditPartProvider.java @@ -1,29 +1,29 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Arthur Daussy Bug 366026 - [ActivityDiagram] Refactoring in order to try respect Generation Gap Pattern
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.providers;
-
-import org.eclipse.papyrus.uml.diagram.activity.edit.part.CustomUMLEditPartFactory;
-
-/**
- * This class was introduce to rout the EditPartFactory to our own EditPartFactory {@link CustomUMLEditPartFactory}
- */
-public class CustomUMLEditPartProvider extends UMLEditPartProvider {
-
- public CustomUMLEditPartProvider() {
- super();
- setFactory(new CustomUMLEditPartFactory());
- setAllowCaching(true);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Arthur Daussy Bug 366026 - [ActivityDiagram] Refactoring in order to try respect Generation Gap Pattern + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.providers; + +import org.eclipse.papyrus.uml.diagram.activity.edit.part.CustomUMLEditPartFactory; + +/** + * This class was introduce to rout the EditPartFactory to our own EditPartFactory {@link CustomUMLEditPartFactory} + */ +public class CustomUMLEditPartProvider extends UMLEditPartProvider { + + public CustomUMLEditPartProvider() { + super(); + setFactory(new CustomUMLEditPartFactory()); + setAllowCaching(true); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/request/InterruptibleEdgeRequest.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/request/InterruptibleEdgeRequest.java index 4d0946417b4..748f2c71b01 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/request/InterruptibleEdgeRequest.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/request/InterruptibleEdgeRequest.java @@ -1,45 +1,45 @@ -/*****************************************************************************
- * Copyright (c) 2011 Atos.
- *
- *
- * 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:
- * Atos - Initial API and implementation
- * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.request;
-
-import org.eclipse.gef.Request;
-
-/**
- * Create a request related to Interruptible Edge.
- * For now this request is created but and throw to editPart but there is no edit part which used.
- * The aim is to have for the future a mechanism in place in order to add specific EditPart mechanism
- *
- * @author arthur daussy
- */
-public class InterruptibleEdgeRequest extends Request {
-
- /**
- * Request type to set an activity edge as an interruptible edge
- */
- public static String SET_INTERRUPTIBLE_EDGE = "set_interruptible_edge";
-
- /**
- * Request type to unset an activity edge as an interruptible edge
- */
- public static String UNSET_INTERRUPTIBLE_EDGE = "unset_interruptible_edge";
-
- @Override
- public void setType(Object type) {
- if (!SET_INTERRUPTIBLE_EDGE.equals(type) && !UNSET_INTERRUPTIBLE_EDGE.equals(type)) {
- setType(UNSET_INTERRUPTIBLE_EDGE);
- }
- super.setType(type);
- }
-}
+/***************************************************************************** + * Copyright (c) 2011 Atos. + * + * + * 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: + * Atos - Initial API and implementation + * Bug 366159 - [ActivityDiagram] Activity Diagram should be able to handle correctly Interruptible Edge + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.request; + +import org.eclipse.gef.Request; + +/** + * Create a request related to Interruptible Edge. + * For now this request is created but and throw to editPart but there is no edit part which used. + * The aim is to have for the future a mechanism in place in order to add specific EditPart mechanism + * + * @author arthur daussy + */ +public class InterruptibleEdgeRequest extends Request { + + /** + * Request type to set an activity edge as an interruptible edge + */ + public static String SET_INTERRUPTIBLE_EDGE = "set_interruptible_edge"; + + /** + * Request type to unset an activity edge as an interruptible edge + */ + public static String UNSET_INTERRUPTIBLE_EDGE = "unset_interruptible_edge"; + + @Override + public void setType(Object type) { + if (!SET_INTERRUPTIBLE_EDGE.equals(type) && !UNSET_INTERRUPTIBLE_EDGE.equals(type)) { + setType(UNSET_INTERRUPTIBLE_EDGE); + } + super.setType(type); + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/tabbedproperties/appearance/SwitchSegmentDirectionSection.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/tabbedproperties/appearance/SwitchSegmentDirectionSection.java index ddd499e45f3..58057774e76 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/tabbedproperties/appearance/SwitchSegmentDirectionSection.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/tabbedproperties/appearance/SwitchSegmentDirectionSection.java @@ -1,258 +1,258 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.tabbedproperties.appearance;
-
-import java.io.IOException;
-import java.util.List;
-
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.draw2d.Figure;
-import org.eclipse.draw2d.geometry.Dimension;
-import org.eclipse.draw2d.geometry.Point;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gef.commands.CommandStack;
-import org.eclipse.gmf.runtime.common.core.command.CommandResult;
-import org.eclipse.gmf.runtime.common.core.command.CompositeCommand;
-import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil;
-import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.properties.sections.AbstractNotationPropertiesSection;
-import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.gmf.runtime.notation.NotationPackage;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.papyrus.infra.ui.util.EditorUtils;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ForkNodeEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.JoinNodeEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages;
-import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin;
-import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.ui.forms.widgets.ImageHyperlink;
-
-/**
- * Section to use in the properties view. This section enables to switch the
- * direction of a segment representation (for fork or join).
- */
-public class SwitchSegmentDirectionSection extends AbstractNotationPropertiesSection {
-
- /** path to the switch icon */
- private static final String ICON_PATH = "icons/switchSegmentOrientation.gif";
-
- /** The switch image. */
- public static Image switchImage = null;
- /** Load the switch icon once */
- static {
- try {
- switchImage = new Image(Display.getDefault(), UMLDiagramEditorPlugin.getInstance().getBundle().getResource(ICON_PATH).openStream());
- } catch (IOException e) {
- UMLDiagramEditorPlugin.getInstance().logError(e.getMessage(), e);
- }
- }
-
- /** current edit part */
- protected IGraphicalEditPart editPart;
-
- /**
- * Create controls to enable direction switch
- */
- @Override
- public void initializeControls(Composite parent) {
- super.initializeControls(parent);
- GridLayout layout = new GridLayout(2, false);
- Group switchGroup = getWidgetFactory().createGroup(composite, CustomMessages.ForkJoinSegmentSwitchOrientation_actionLabel);
- switchGroup.setLayout(layout);
- // create switch button
- Button button = new Button(switchGroup, SWT.PUSH);
- button.setImage(switchImage);
- GridData gd = new GridData(SWT.CENTER, SWT.CENTER, true, true);
- button.setLayoutData(gd);
- button.addSelectionListener(new SelectionListener() {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // do nothing
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- switchSelectedSegmentsOrientation();
- refresh();
- }
- });
- // create help
- ImageHyperlink help = HelpComponentFactory.createHelpComponent(switchGroup, getWidgetFactory(), CustomMessages.ForkJoinSegmentSwitchOrientation_helpMessage);
- gd = new GridData(SWT.RIGHT, SWT.CENTER, false, true);
- help.setLayoutData(gd);
- help.setBackground(switchGroup.getBackground());
- }
-
- /**
- * Switch the orientation of each selected segment figure.
- */
- protected void switchSelectedSegmentsOrientation() {
- CompositeCommand globalCommand = new CompositeCommand(CustomMessages.ForkJoinSegmentSwitchOrientation_actionLabel);
- List<?> editparts = getInput();
- for (Object part : editparts) {
- Object view = null;
- Figure figure = null;
- if (part instanceof JoinNodeEditPart) {
- view = ((JoinNodeEditPart) part).getModel();
- figure = ((JoinNodeEditPart) part).getPrimaryShape();
- } else if (part instanceof ForkNodeEditPart) {
- view = ((ForkNodeEditPart) part).getModel();
- figure = ((ForkNodeEditPart) part).getPrimaryShape();
- }
- // append a command for selected part only if correct configuration
- if (view instanceof View && figure != null) {
- TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain();
- SwitchSegmentOrientation switchCom = new SwitchSegmentOrientation(editingdomain, figure, (View) view);
- globalCommand.add(switchCom);
- }
- }
- // execute the command for all parts
- if (!globalCommand.isEmpty() && globalCommand.canExecute()) {
- CommandStack stack = (CommandStack) EditorUtils.getMultiDiagramEditor().getAdapter(CommandStack.class);
- if (stack != null) {
- stack.execute(new ICommandProxy(globalCommand));
- }
- }
- }
-
- /**
- * This class is a command which switches the orientation of a figure. The
- * figure's width and height are switched, rotating the figure on its
- * center. (center location kept)
- */
- private class SwitchSegmentOrientation extends AbstractTransactionalCommand {
-
- /** The figure to switch */
- private Figure selectedFigure = null;
-
- /** The model view for the figure to switch */
- private View selectedView = null;
-
- /**
- * Construct a switch orientation command.
- *
- * @param domain
- * transactional editing domain
- * @param figure
- * the figure to rotate
- * @param view
- * the view which is the model of the figure
- */
- SwitchSegmentOrientation(TransactionalEditingDomain domain, Figure figure, View view) {
- super(domain, CustomMessages.ForkJoinSegmentSwitchOrientation_actionLabel, null);
- selectedFigure = figure;
- selectedView = view;
- }
-
- /**
- * Execute the command, rotating the figure.
- *
- * @see org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doExecuteWithResult(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable)
- *
- * @param monitor
- * progress monitor
- * @param info
- * adapter for information
- * @return the result of the command
- * @throws ExecutionException
- */
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- if (selectedFigure == null || selectedView == null) {
- return CommandResult.newCancelledCommandResult();
- }
- Dimension newSize = selectedFigure.getSize().getTransposed();
- Point newLocation = selectedFigure.getLocation().getCopy();
- newLocation.translate((newSize.height - newSize.width) / 2, (newSize.width - newSize.height) / 2);
- ViewUtil.setStructuralFeatureValue(selectedView, NotationPackage.eINSTANCE.getLocation_X(), newLocation.x);
- ViewUtil.setStructuralFeatureValue(selectedView, NotationPackage.eINSTANCE.getLocation_Y(), newLocation.y);
- ViewUtil.setStructuralFeatureValue(selectedView, NotationPackage.eINSTANCE.getSize_Width(), newSize.width);
- ViewUtil.setStructuralFeatureValue(selectedView, NotationPackage.eINSTANCE.getSize_Height(), newSize.height);
- return CommandResult.newOKCommandResult();
- }
-
- /**
- * @see org.eclipse.emf.workspace.AbstractEMFOperation#canUndo()
- * @return true if command can undo
- */
- @Override
- public boolean canUndo() {
- return selectedFigure != null && selectedView != null;
- }
-
- /**
- * @see org.eclipse.emf.workspace.AbstractEMFOperation#canRedo()
- * @return true if command can redo
- */
- @Override
- public boolean canRedo() {
- return selectedFigure != null && selectedView != null;
- }
-
- /**
- * Undo the switch (by switching again)
- *
- * @see org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doUndo(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable)
- *
- * @param monitor
- * progress monitor
- * @param info
- * adapter for information
- * @return the result of the command
- * @throws ExecutionException
- */
- @Override
- protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- return doExecute(monitor, info);
- }
-
- /**
- * Redo the switch (by switching again)
- *
- * @see org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doRedo(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable)
- *
- * @param monitor
- * progress monitor
- * @param info
- * adapter for information
- * @return the result of the command
- * @throws ExecutionException
- */
- @Override
- protected IStatus doRedo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- return doExecute(monitor, info);
- }
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.tabbedproperties.appearance; + +import java.io.IOException; +import java.util.List; + +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.draw2d.Figure; +import org.eclipse.draw2d.geometry.Dimension; +import org.eclipse.draw2d.geometry.Point; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gef.commands.CommandStack; +import org.eclipse.gmf.runtime.common.core.command.CommandResult; +import org.eclipse.gmf.runtime.common.core.command.CompositeCommand; +import org.eclipse.gmf.runtime.diagram.core.util.ViewUtil; +import org.eclipse.gmf.runtime.diagram.ui.commands.ICommandProxy; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.properties.sections.AbstractNotationPropertiesSection; +import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.gmf.runtime.notation.NotationPackage; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.papyrus.infra.ui.util.EditorUtils; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ForkNodeEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.JoinNodeEditPart; +import org.eclipse.papyrus.uml.diagram.activity.part.CustomMessages; +import org.eclipse.papyrus.uml.diagram.activity.part.UMLDiagramEditorPlugin; +import org.eclipse.papyrus.uml.diagram.common.ui.helper.HelpComponentFactory; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.ui.forms.widgets.ImageHyperlink; + +/** + * Section to use in the properties view. This section enables to switch the + * direction of a segment representation (for fork or join). + */ +public class SwitchSegmentDirectionSection extends AbstractNotationPropertiesSection { + + /** path to the switch icon */ + private static final String ICON_PATH = "icons/switchSegmentOrientation.gif"; + + /** The switch image. */ + public static Image switchImage = null; + /** Load the switch icon once */ + static { + try { + switchImage = new Image(Display.getDefault(), UMLDiagramEditorPlugin.getInstance().getBundle().getResource(ICON_PATH).openStream()); + } catch (IOException e) { + UMLDiagramEditorPlugin.getInstance().logError(e.getMessage(), e); + } + } + + /** current edit part */ + protected IGraphicalEditPart editPart; + + /** + * Create controls to enable direction switch + */ + @Override + public void initializeControls(Composite parent) { + super.initializeControls(parent); + GridLayout layout = new GridLayout(2, false); + Group switchGroup = getWidgetFactory().createGroup(composite, CustomMessages.ForkJoinSegmentSwitchOrientation_actionLabel); + switchGroup.setLayout(layout); + // create switch button + Button button = new Button(switchGroup, SWT.PUSH); + button.setImage(switchImage); + GridData gd = new GridData(SWT.CENTER, SWT.CENTER, true, true); + button.setLayoutData(gd); + button.addSelectionListener(new SelectionListener() { + + /** + * {@inheritDoc} + */ + @Override + public void widgetDefaultSelected(SelectionEvent e) { + // do nothing + } + + /** + * {@inheritDoc} + */ + @Override + public void widgetSelected(SelectionEvent e) { + switchSelectedSegmentsOrientation(); + refresh(); + } + }); + // create help + ImageHyperlink help = HelpComponentFactory.createHelpComponent(switchGroup, getWidgetFactory(), CustomMessages.ForkJoinSegmentSwitchOrientation_helpMessage); + gd = new GridData(SWT.RIGHT, SWT.CENTER, false, true); + help.setLayoutData(gd); + help.setBackground(switchGroup.getBackground()); + } + + /** + * Switch the orientation of each selected segment figure. + */ + protected void switchSelectedSegmentsOrientation() { + CompositeCommand globalCommand = new CompositeCommand(CustomMessages.ForkJoinSegmentSwitchOrientation_actionLabel); + List<?> editparts = getInput(); + for (Object part : editparts) { + Object view = null; + Figure figure = null; + if (part instanceof JoinNodeEditPart) { + view = ((JoinNodeEditPart) part).getModel(); + figure = ((JoinNodeEditPart) part).getPrimaryShape(); + } else if (part instanceof ForkNodeEditPart) { + view = ((ForkNodeEditPart) part).getModel(); + figure = ((ForkNodeEditPart) part).getPrimaryShape(); + } + // append a command for selected part only if correct configuration + if (view instanceof View && figure != null) { + TransactionalEditingDomain editingdomain = EditorUtils.getTransactionalEditingDomain(); + SwitchSegmentOrientation switchCom = new SwitchSegmentOrientation(editingdomain, figure, (View) view); + globalCommand.add(switchCom); + } + } + // execute the command for all parts + if (!globalCommand.isEmpty() && globalCommand.canExecute()) { + CommandStack stack = (CommandStack) EditorUtils.getMultiDiagramEditor().getAdapter(CommandStack.class); + if (stack != null) { + stack.execute(new ICommandProxy(globalCommand)); + } + } + } + + /** + * This class is a command which switches the orientation of a figure. The + * figure's width and height are switched, rotating the figure on its + * center. (center location kept) + */ + private class SwitchSegmentOrientation extends AbstractTransactionalCommand { + + /** The figure to switch */ + private Figure selectedFigure = null; + + /** The model view for the figure to switch */ + private View selectedView = null; + + /** + * Construct a switch orientation command. + * + * @param domain + * transactional editing domain + * @param figure + * the figure to rotate + * @param view + * the view which is the model of the figure + */ + SwitchSegmentOrientation(TransactionalEditingDomain domain, Figure figure, View view) { + super(domain, CustomMessages.ForkJoinSegmentSwitchOrientation_actionLabel, null); + selectedFigure = figure; + selectedView = view; + } + + /** + * Execute the command, rotating the figure. + * + * @see org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doExecuteWithResult(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable) + * + * @param monitor + * progress monitor + * @param info + * adapter for information + * @return the result of the command + * @throws ExecutionException + */ + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + if (selectedFigure == null || selectedView == null) { + return CommandResult.newCancelledCommandResult(); + } + Dimension newSize = selectedFigure.getSize().getTransposed(); + Point newLocation = selectedFigure.getLocation().getCopy(); + newLocation.translate((newSize.height - newSize.width) / 2, (newSize.width - newSize.height) / 2); + ViewUtil.setStructuralFeatureValue(selectedView, NotationPackage.eINSTANCE.getLocation_X(), newLocation.x); + ViewUtil.setStructuralFeatureValue(selectedView, NotationPackage.eINSTANCE.getLocation_Y(), newLocation.y); + ViewUtil.setStructuralFeatureValue(selectedView, NotationPackage.eINSTANCE.getSize_Width(), newSize.width); + ViewUtil.setStructuralFeatureValue(selectedView, NotationPackage.eINSTANCE.getSize_Height(), newSize.height); + return CommandResult.newOKCommandResult(); + } + + /** + * @see org.eclipse.emf.workspace.AbstractEMFOperation#canUndo() + * @return true if command can undo + */ + @Override + public boolean canUndo() { + return selectedFigure != null && selectedView != null; + } + + /** + * @see org.eclipse.emf.workspace.AbstractEMFOperation#canRedo() + * @return true if command can redo + */ + @Override + public boolean canRedo() { + return selectedFigure != null && selectedView != null; + } + + /** + * Undo the switch (by switching again) + * + * @see org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doUndo(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable) + * + * @param monitor + * progress monitor + * @param info + * adapter for information + * @return the result of the command + * @throws ExecutionException + */ + @Override + protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + return doExecute(monitor, info); + } + + /** + * Redo the switch (by switching again) + * + * @see org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand#doRedo(org.eclipse.core.runtime.IProgressMonitor, org.eclipse.core.runtime.IAdaptable) + * + * @param monitor + * progress monitor + * @param info + * adapter for information + * @return the result of the command + * @throws ExecutionException + */ + @Override + protected IStatus doRedo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + return doExecute(monitor, info); + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/tabbedproperties/appearance/SwitchSegmentDirectionSectionFilter.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/tabbedproperties/appearance/SwitchSegmentDirectionSectionFilter.java index 0b4b3cd6c8c..ad939805ba2 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/tabbedproperties/appearance/SwitchSegmentDirectionSectionFilter.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/tabbedproperties/appearance/SwitchSegmentDirectionSectionFilter.java @@ -1,32 +1,32 @@ -/*****************************************************************************
- * 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:
- * Atos Origin - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.tabbedproperties.appearance;
-
-import org.eclipse.jface.viewers.IFilter;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ForkNodeEditPart;
-import org.eclipse.papyrus.uml.diagram.activity.edit.parts.JoinNodeEditPart;
-
-/**
- * Filter for the {@link SwitchSegmentDirectionSection} section
- */
-public class SwitchSegmentDirectionSectionFilter implements IFilter {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean select(Object object) {
- return object instanceof ForkNodeEditPart || object instanceof JoinNodeEditPart;
- }
-}
+/***************************************************************************** + * 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: + * Atos Origin - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.tabbedproperties.appearance; + +import org.eclipse.jface.viewers.IFilter; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.ForkNodeEditPart; +import org.eclipse.papyrus.uml.diagram.activity.edit.parts.JoinNodeEditPart; + +/** + * Filter for the {@link SwitchSegmentDirectionSection} section + */ +public class SwitchSegmentDirectionSectionFilter implements IFilter { + + /** + * {@inheritDoc} + */ + @Override + public boolean select(Object object) { + return object instanceof ForkNodeEditPart || object instanceof JoinNodeEditPart; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/testers/UMLCallActionTester.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/testers/UMLCallActionTester.java index 7cea2b1abb8..c76a05850af 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/testers/UMLCallActionTester.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/testers/UMLCallActionTester.java @@ -1,65 +1,65 @@ -/*****************************************************************************
- * Copyright (c) 2012 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:
- * Anass Radouani (Atos) anass.radouani@atos.com - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.testers;
-
-import org.eclipse.core.expressions.PropertyTester;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.uml2.uml.InvocationAction;
-
-/**
- * This class is a Property tester used to check if current element
- * is a UML Call Action.
- */
-public class UMLCallActionTester extends PropertyTester {
-
- /** Tester ID for UML Call Action nature */
- public final static String IS_CALL_ACTION = "isCallAction";
-
- /** Default constructor */
- public UMLCallActionTester() {
- }
-
- /** Test the receiver against the selected property */
- @Override
- public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
- // Ensure Papyrus is the active editor
- IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- if ((editor == null) || (!(editor instanceof IMultiDiagramEditor))) {
- return false;
- }
- Object currentValue = null;
- if (IS_CALL_ACTION.equals(property)) {
- if (receiver instanceof StructuredSelection) {
- StructuredSelection structuredSelection = (StructuredSelection) receiver;
- Object obj = structuredSelection.getFirstElement();
- EObject element = null;
- if (obj instanceof IAdaptable) {
- element = (EObject) ((IAdaptable) obj).getAdapter(EObject.class);
- if (element instanceof View) {
- element = ((View) element).getElement();
- }
- }
- currentValue = element instanceof InvocationAction;
- }
- return (currentValue == expectedValue);
- }
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2012 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: + * Anass Radouani (Atos) anass.radouani@atos.com - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.testers; + +import org.eclipse.core.expressions.PropertyTester; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.PlatformUI; +import org.eclipse.uml2.uml.InvocationAction; + +/** + * This class is a Property tester used to check if current element + * is a UML Call Action. + */ +public class UMLCallActionTester extends PropertyTester { + + /** Tester ID for UML Call Action nature */ + public final static String IS_CALL_ACTION = "isCallAction"; + + /** Default constructor */ + public UMLCallActionTester() { + } + + /** Test the receiver against the selected property */ + @Override + public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { + // Ensure Papyrus is the active editor + IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); + if ((editor == null) || (!(editor instanceof IMultiDiagramEditor))) { + return false; + } + Object currentValue = null; + if (IS_CALL_ACTION.equals(property)) { + if (receiver instanceof StructuredSelection) { + StructuredSelection structuredSelection = (StructuredSelection) receiver; + Object obj = structuredSelection.getFirstElement(); + EObject element = null; + if (obj instanceof IAdaptable) { + element = (EObject) ((IAdaptable) obj).getAdapter(EObject.class); + if (element instanceof View) { + element = ((View) element).getElement(); + } + } + currentValue = element instanceof InvocationAction; + } + return (currentValue == expectedValue); + } + return false; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/testers/UMLPackageSelectionTester.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/testers/UMLPackageSelectionTester.java index 2eee3c2f7ee..5d78eca8fec 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/testers/UMLPackageSelectionTester.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/testers/UMLPackageSelectionTester.java @@ -1,65 +1,65 @@ -/*****************************************************************************
- * Copyright (c) 2012 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:
- * Arthur Daussy (Atos) arthur.daussy@atos.com - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.testers;
-
-import org.eclipse.core.expressions.PropertyTester;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.uml2.uml.Package;
-
-/**
- * Return true if the selection is a package
- *
- * @author arthur daussy
- *
- */
-public class UMLPackageSelectionTester extends PropertyTester {
-
- /** Tester ID for UML Call Action nature */
- public final static String IS_PACKAGE = "isUMLPackage";
-
- public UMLPackageSelectionTester() {
- }
-
- @Override
- public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
- // Ensure Papyrus is the active editor
- IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
- if ((editor == null) || (!(editor instanceof IMultiDiagramEditor))) {
- return false;
- }
- Object currentValue = null;
- if (IS_PACKAGE.equals(property)) {
- if (receiver instanceof StructuredSelection) {
- StructuredSelection structuredSelection = (StructuredSelection) receiver;
- Object obj = structuredSelection.getFirstElement();
- EObject element = null;
- if (obj instanceof IAdaptable) {
- element = (EObject) ((IAdaptable) obj).getAdapter(EObject.class);
- if (element instanceof View) {
- element = ((View) element).getElement();
- }
- }
- currentValue = element instanceof Package;
- }
- return (currentValue == expectedValue);
- }
- return false;
- }
-}
+/***************************************************************************** + * Copyright (c) 2012 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: + * Arthur Daussy (Atos) arthur.daussy@atos.com - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.testers; + +import org.eclipse.core.expressions.PropertyTester; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.PlatformUI; +import org.eclipse.uml2.uml.Package; + +/** + * Return true if the selection is a package + * + * @author arthur daussy + * + */ +public class UMLPackageSelectionTester extends PropertyTester { + + /** Tester ID for UML Call Action nature */ + public final static String IS_PACKAGE = "isUMLPackage"; + + public UMLPackageSelectionTester() { + } + + @Override + public boolean test(Object receiver, String property, Object[] args, Object expectedValue) { + // Ensure Papyrus is the active editor + IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); + if ((editor == null) || (!(editor instanceof IMultiDiagramEditor))) { + return false; + } + Object currentValue = null; + if (IS_PACKAGE.equals(property)) { + if (receiver instanceof StructuredSelection) { + StructuredSelection structuredSelection = (StructuredSelection) receiver; + Object obj = structuredSelection.getFirstElement(); + EObject element = null; + if (obj instanceof IAdaptable) { + element = (EObject) ((IAdaptable) obj).getAdapter(EObject.class); + if (element instanceof View) { + element = ((View) element).getElement(); + } + } + currentValue = element instanceof Package; + } + return (currentValue == expectedValue); + } + return false; + } +} |