diff options
author | Benoit Maggi | 2014-04-18 15:53:52 +0000 |
---|---|---|
committer | Camille Letavernier | 2014-04-18 16:14:18 +0000 |
commit | 3541995e815cf2a111e439315d9cefdfd8318699 (patch) | |
tree | b1b4cbe19ea4423b248c3195cecb1322f20d98aa | |
parent | 26ca0dd9ac2a74b06d4ae3fed09a801f7706e1cb (diff) | |
download | org.eclipse.papyrus-3541995e815cf2a111e439315d9cefdfd8318699.tar.gz org.eclipse.papyrus-3541995e815cf2a111e439315d9cefdfd8318699.tar.xz org.eclipse.papyrus-3541995e815cf2a111e439315d9cefdfd8318699.zip |
Bug 431298 - NPE in ShowHideRelatedContentsHandler
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService()
there is a non-null activeWindow.
Change-Id: I5b9d471a2b1877bf07e9af46f5a625daf9dc90a5
Signed-off-by: Benoit Maggi <benoit.maggi@cea.fr>
12 files changed, 2175 insertions, 2138 deletions
diff --git a/plugins/infra/emf/org.eclipse.papyrus.infra.emf.readonly/src/org/eclipse/papyrus/infra/emf/readonly/handlers/EnableWriteCommandHandler.java b/plugins/infra/emf/org.eclipse.papyrus.infra.emf.readonly/src/org/eclipse/papyrus/infra/emf/readonly/handlers/EnableWriteCommandHandler.java index 8f736f64fa6..4591d76c4bd 100644 --- a/plugins/infra/emf/org.eclipse.papyrus.infra.emf.readonly/src/org/eclipse/papyrus/infra/emf/readonly/handlers/EnableWriteCommandHandler.java +++ b/plugins/infra/emf/org.eclipse.papyrus.infra.emf.readonly/src/org/eclipse/papyrus/infra/emf/readonly/handlers/EnableWriteCommandHandler.java @@ -1,95 +1,99 @@ -/*****************************************************************************
- * Copyright (c) 2011, 2014 Atos Origin, 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:
- * Mathieu Velten (Atos Origin) mathieu.velten@atosorigin.com - Initial API and implementation
- * Christian W. Damus (CEA) - bug 323802
- * Christian W. Damus (CEA) - bug 429826
- *
- *****************************************************************************/
-package org.eclipse.papyrus.infra.emf.readonly.handlers;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.emf.common.util.URI;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.resource.Resource;
-import org.eclipse.emf.ecore.resource.ResourceSet;
-import org.eclipse.emf.edit.domain.EditingDomain;
-import org.eclipse.emf.workspace.WorkspaceEditingDomainFactory;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.papyrus.infra.core.resource.ReadOnlyAxis;
-import org.eclipse.papyrus.infra.emf.readonly.ReadOnlyManager;
-import org.eclipse.papyrus.infra.emf.utils.BusinessModelResolver;
-import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
-import org.eclipse.papyrus.infra.onefile.model.IPapyrusFile;
-import org.eclipse.papyrus.infra.onefile.model.PapyrusModelHelper;
-import org.eclipse.papyrus.infra.onefile.utils.OneFileUtils;
-import org.eclipse.ui.PlatformUI;
-
-public class EnableWriteCommandHandler extends AbstractHandler {
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- EObject elem = getSelectedElement();
- if(elem != null && elem.eResource() != null && elem.eResource().getResourceSet() != null) {
- Resource res = elem.eResource();
- ResourceSet rs = res.getResourceSet();
-
- if(res.getURI() != null && res.getURI().isPlatformResource()) {
- IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(res.getURI().toPlatformString(true)));
- IPapyrusFile papFile = PapyrusModelHelper.getPapyrusModelFactory().createIPapyrusFile(file);
- IFile[] associatedFiles = OneFileUtils.getAssociatedFiles(papFile);
-
- URI[] associatedUris = new URI[associatedFiles.length];
- for (int i=0 ; i < associatedFiles.length ; i++) {
- associatedUris[i] = URI.createPlatformResourceURI(associatedFiles[i].getFullPath().toString(), true);
- }
-
- ReadOnlyManager.getReadOnlyHandler(WorkspaceEditingDomainFactory.INSTANCE.getEditingDomain(rs)).makeWritable(ReadOnlyAxis.anyAxis(), associatedUris);
- }
- }
- return null;
- }
-
- protected EObject getSelectedElement() {
- ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
- if(selection instanceof IStructuredSelection) {
- Object obj = ((IStructuredSelection)selection).getFirstElement();
- return resolveSemanticObject(obj);
- }
- return null;
- }
-
- /**
- * Resolve semantic element
- *
- * @param object
- * the object to resolve
- * @return <code>null</code> or the semantic element associated to the
- * specified object
- */
- protected EObject resolveSemanticObject(Object object) {
- Object businessObject = BusinessModelResolver.getInstance().getBusinessModel(object);
- if(businessObject instanceof EObject) {
- return (EObject)businessObject;
- }
- return null;
- }
-
- @Override
- public void setEnabled(Object evaluationContext) {
- EObject selected = getSelectedElement();
- EditingDomain domain = (selected == null) ? null : EMFHelper.resolveEditingDomain(selected);
- setBaseEnabled((domain != null) && EMFHelper.canMakeWritable(selected, domain));
- }
-}
+/***************************************************************************** + * Copyright (c) 2011, 2014 Atos Origin, 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: + * Mathieu Velten (Atos Origin) mathieu.velten@atosorigin.com - Initial API and implementation + * Christian W. Damus (CEA) - bug 323802 + * Christian W. Damus (CEA) - bug 429826 + * + *****************************************************************************/ +package org.eclipse.papyrus.infra.emf.readonly.handlers; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.Path; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.ResourceSet; +import org.eclipse.emf.edit.domain.EditingDomain; +import org.eclipse.emf.workspace.WorkspaceEditingDomainFactory; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.papyrus.infra.core.resource.ReadOnlyAxis; +import org.eclipse.papyrus.infra.emf.readonly.ReadOnlyManager; +import org.eclipse.papyrus.infra.emf.utils.BusinessModelResolver; +import org.eclipse.papyrus.infra.emf.utils.EMFHelper; +import org.eclipse.papyrus.infra.onefile.model.IPapyrusFile; +import org.eclipse.papyrus.infra.onefile.model.PapyrusModelHelper; +import org.eclipse.papyrus.infra.onefile.utils.OneFileUtils; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; + +public class EnableWriteCommandHandler extends AbstractHandler { + + public Object execute(ExecutionEvent event) throws ExecutionException { + EObject elem = getSelectedElement(); + if(elem != null && elem.eResource() != null && elem.eResource().getResourceSet() != null) { + Resource res = elem.eResource(); + ResourceSet rs = res.getResourceSet(); + + if(res.getURI() != null && res.getURI().isPlatformResource()) { + IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(res.getURI().toPlatformString(true))); + IPapyrusFile papFile = PapyrusModelHelper.getPapyrusModelFactory().createIPapyrusFile(file); + IFile[] associatedFiles = OneFileUtils.getAssociatedFiles(papFile); + + URI[] associatedUris = new URI[associatedFiles.length]; + for (int i=0 ; i < associatedFiles.length ; i++) { + associatedUris[i] = URI.createPlatformResourceURI(associatedFiles[i].getFullPath().toString(), true); + } + + ReadOnlyManager.getReadOnlyHandler(WorkspaceEditingDomainFactory.INSTANCE.getEditingDomain(rs)).makeWritable(ReadOnlyAxis.anyAxis(), associatedUris); + } + } + return null; + } + + protected EObject getSelectedElement() { + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + ISelection selection = activeWorkbenchWindow.getSelectionService().getSelection(); + if(selection instanceof IStructuredSelection) { + Object obj = ((IStructuredSelection)selection).getFirstElement(); + return resolveSemanticObject(obj); + } + } + return null; + } + + /** + * Resolve semantic element + * + * @param object + * the object to resolve + * @return <code>null</code> or the semantic element associated to the + * specified object + */ + protected EObject resolveSemanticObject(Object object) { + Object businessObject = BusinessModelResolver.getInstance().getBusinessModel(object); + if(businessObject instanceof EObject) { + return (EObject)businessObject; + } + return null; + } + + @Override + public void setEnabled(Object evaluationContext) { + EObject selected = getSelectedElement(); + EditingDomain domain = (selected == null) ? null : EMFHelper.resolveEditingDomain(selected); + setBaseEnabled((domain != null) && EMFHelper.canMakeWritable(selected, domain)); + } +} diff --git a/plugins/infra/gmfdiag/org.eclipse.papyrus.infra.gmfdiag.modelexplorer/src/org/eclipse/papyrus/infra/gmfdiag/modelexplorer/handlers/AbstractDiagramCommandHandler.java b/plugins/infra/gmfdiag/org.eclipse.papyrus.infra.gmfdiag.modelexplorer/src/org/eclipse/papyrus/infra/gmfdiag/modelexplorer/handlers/AbstractDiagramCommandHandler.java index d184675fcc2..8c4e0c8ffa4 100644 --- a/plugins/infra/gmfdiag/org.eclipse.papyrus.infra.gmfdiag.modelexplorer/src/org/eclipse/papyrus/infra/gmfdiag/modelexplorer/handlers/AbstractDiagramCommandHandler.java +++ b/plugins/infra/gmfdiag/org.eclipse.papyrus.infra.gmfdiag.modelexplorer/src/org/eclipse/papyrus/infra/gmfdiag/modelexplorer/handlers/AbstractDiagramCommandHandler.java @@ -1,63 +1,63 @@ -/*****************************************************************************
- * Copyright (c) 2014 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) - Initial API and implementation
- /*****************************************************************************/
-package org.eclipse.papyrus.infra.gmfdiag.modelexplorer.handlers;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.gmf.runtime.notation.Diagram;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
-import org.eclipse.papyrus.views.modelexplorer.NavigatorUtils;
-import org.eclipse.papyrus.views.modelexplorer.handler.AbstractCommandHandler;
-import org.eclipse.ui.PlatformUI;
-
-
-public abstract class AbstractDiagramCommandHandler extends AbstractCommandHandler {
- /**
- * Returns the list of selected diagrams
- *
- * @return
- * the list of selected diagrams
- */
- protected List<Diagram> getSelectedDiagrams() {
- List<Diagram> diagrams = new ArrayList<Diagram>();
- ISelection selection = null;
-
- // Get current selection
- selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
-
- // Get first element if the selection is an IStructuredSelection
- if(selection instanceof IStructuredSelection) {
- IStructuredSelection structuredSelection = (IStructuredSelection)selection;
- Iterator<?> iter = structuredSelection.iterator();
- while(iter.hasNext()) {
- Object current = iter.next();
- /**
- * Get the diagram object.
- * This getElement is used in order to use IAdaptabel mechanism
- * For example for Facet Elements
- */
- EObject diag = EMFHelper.getEObject(current);
- if(diag instanceof Diagram) {
- diagrams.add((Diagram)diag);
- }
- }
- }
-
- return diagrams;
- }
-}
+/***************************************************************************** + * Copyright (c) 2014 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) - Initial API and implementation + /*****************************************************************************/ +package org.eclipse.papyrus.infra.gmfdiag.modelexplorer.handlers; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.emf.ecore.EObject; +import org.eclipse.gmf.runtime.notation.Diagram; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.papyrus.infra.emf.utils.EMFHelper; +import org.eclipse.papyrus.views.modelexplorer.handler.AbstractCommandHandler; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; + + +public abstract class AbstractDiagramCommandHandler extends AbstractCommandHandler { + /** + * Returns the list of selected diagrams + * + * @return + * the list of selected diagrams + */ + protected List<Diagram> getSelectedDiagrams() { + List<Diagram> diagrams = new ArrayList<Diagram>(); + ISelection selection = null; + // Get current selection + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + selection = activeWorkbenchWindow.getSelectionService().getSelection(); + // Get first element if the selection is an IStructuredSelection + if(selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection)selection; + Iterator<?> iter = structuredSelection.iterator(); + while(iter.hasNext()) { + Object current = iter.next(); + /** + * Get the diagram object. + * This getElement is used in order to use IAdaptabel mechanism + * For example for Facet Elements + */ + EObject diag = EMFHelper.getEObject(current); + if(diag instanceof Diagram) { + diagrams.add((Diagram)diag); + } + } + } + } + return diagrams; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/handlers/SynchronizePinsParametersHandler.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/handlers/SynchronizePinsParametersHandler.java index 5ee99f7e591..3d599cdd8e3 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/handlers/SynchronizePinsParametersHandler.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.activity/custom-src/org/eclipse/papyrus/uml/diagram/activity/handlers/SynchronizePinsParametersHandler.java @@ -1,652 +1,656 @@ -/*****************************************************************************
- * 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
- * Olivier Mélois (Atos) : olivier.melois@atos.net - 371712
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.activity.handlers;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.eclipse.core.commands.ExecutionEvent;
-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.core.runtime.IStatus;
-import org.eclipse.emf.common.command.CompoundCommand;
-import org.eclipse.emf.common.util.EList;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.ecore.xmi.XMIResource;
-import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
-import org.eclipse.emf.edit.domain.EditingDomain;
-import org.eclipse.emf.edit.provider.IItemLabelProvider;
-import org.eclipse.emf.transaction.RollbackException;
-import org.eclipse.emf.transaction.Transaction;
-import org.eclipse.emf.transaction.TransactionalCommandStack;
-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.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.emf.core.util.EMFCoreUtil;
-import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand;
-import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.papyrus.commands.DestroyElementPapyrusCommand;
-import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper;
-import org.eclipse.papyrus.infra.core.utils.EditorUtils;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.Type;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder;
-import org.eclipse.papyrus.infra.widgets.toolbox.notification.view.PapyrusNotificationView;
-import org.eclipse.papyrus.uml.diagram.activity.commands.CreatePinToParameterLinkEAnnotation;
-import org.eclipse.papyrus.uml.diagram.activity.helper.IPinToParameterLinkCommand;
-import org.eclipse.papyrus.uml.diagram.activity.helper.PinAndParameterSynchronizer;
-import org.eclipse.papyrus.uml.diagram.activity.helper.datastructure.LinkPinToParameter;
-import org.eclipse.papyrus.uml.diagram.activity.providers.UMLMarkerNavigationProvider;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.handlers.HandlerUtil;
-import org.eclipse.uml2.uml.ActivityEdge;
-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.Element;
-import org.eclipse.uml2.uml.InputPin;
-import org.eclipse.uml2.uml.InvocationAction;
-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.SendSignalAction;
-import org.eclipse.uml2.uml.Signal;
-import org.eclipse.uml2.uml.TypedElement;
-import org.eclipse.uml2.uml.edit.providers.UMLItemProviderAdapterFactory;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
-/**
- * Handler to synchronized the pin and parameter manually
- *
- * @author arthur daussy
- *
- */
-public class SynchronizePinsParametersHandler extends AbstractSynchronizePinsAndParameters {
-
- /**
- * Label for the handler (use in notification and dialog)
- */
- private static final String SYNCHRONIZE_PINS_AND_PARAMETERS = "Synchronize pins and parameters";
-
- /**
- * Constructor
- */
- public SynchronizePinsParametersHandler() {
- }
-
- /**
- * Execute unprotected command
- */
- public Object execute(ExecutionEvent event) throws ExecutionException {
- ISelection selection = HandlerUtil.getActiveMenuSelection(event);
- if(selection instanceof StructuredSelection) {
- StructuredSelection structuredSelection = (StructuredSelection)selection;
- 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();
- }
- if(element instanceof InvocationAction) {
- syncInvocationAction((InvocationAction)element);
- }
- }
- }
- return null;
- }
-
- /**
- * Synchronizes a Call Action
- *
- * @param callAction
- */
- public static void syncInvocationAction(InvocationAction invocationAction) {
- if(!isAccessible(invocationAction)) {
- createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "Unable to synchronize pins on " + invocationAction.getQualifiedName() + " : the ressource is unreachable", Type.WARNING);
- return;
- }
- //Trying to match pins of the callAction with parameters of same index/direction/type.
- //The pins that can not be matched will be destroyed by the "syncCallActionWhenOutdated" method.
- matchPinsAndParams(invocationAction);
- if(isUpToDate(invocationAction)) {
- createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "The call action " + invocationAction.getQualifiedName() + " is up to date", Type.INFO);
- } else {
- //Synchronization when a link between pins and params already exists but is outdated.
- syncCallActionWhenOutdated(invocationAction);
- }
- //Renaming pins according to their associated parameters.
- renamePins(invocationAction);
- }
-
- /**
- * Rename the pins according to their parameters when possible.
- *
- * @param invocationAction
- */
- private static void renamePins(final InvocationAction invocationAction) {
- //Command used as renaming the pins change the model.
- AbstractTransactionalCommand renamePinsCommand = new AbstractTransactionalCommand(EditorUtils.getTransactionalEditingDomain(), "renaming pins", null) {
-
- @Override
- protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
- Iterable<? extends Pin> allPins = Lists.newArrayList(invocationAction.getArguments());
- if(invocationAction instanceof CallAction) {
- allPins = Iterables.concat(((CallAction)invocationAction).getResults(), allPins);
- }
- Element behaviorStructural = null;
- if(invocationAction instanceof CallBehaviorAction) {
- behaviorStructural = ((CallBehaviorAction)invocationAction).getBehavior();
- } else if(invocationAction instanceof CallOperationAction) {
- behaviorStructural = ((CallOperationAction)invocationAction).getOperation();
- } else if(invocationAction instanceof SendSignalAction) {
- behaviorStructural = ((SendSignalAction)invocationAction).getSignal();
- } else if(invocationAction instanceof BroadcastSignalAction) {
- behaviorStructural = ((BroadcastSignalAction)invocationAction).getSignal();
- }
- XMIResource xmiResource = PinAndParameterSynchronizer.getXMIResource(behaviorStructural);
- for(Pin pin : allPins) {
- TypedElement typedElement = PinAndParameterSynchronizer.getLinkedParemeter(pin, xmiResource);
- if(typedElement != null) {
- String paramName = typedElement.getName();
- pin.setName(paramName);
- }
- }
- return CommandResult.newOKCommandResult();
- }
- };
- executeCommand(new GMFtoEMFCommandWrapper(renamePinsCommand), invocationAction);
- }
-
- /**
- * Method used to match the pins of a call action with parameters of that same call action,
- * when the pins do not have eAnnotations already linking to parameters. If no match can
- * be performed, the pin is destroyed along with its edges.
- *
- * @param callAction
- */
- private static void matchPinsAndParams(InvocationAction invocationAction) {
- List<InputPin> inputPins = Lists.newArrayList(invocationAction.getArguments());
- List<OutputPin> outputPins = null;
- if(outputPins instanceof CallAction) {
- CallAction callAction = (CallAction)outputPins;
- outputPins = callAction.getResults();
- } else {
- outputPins = Collections.emptyList();
- }
- //The command that is going to be executed.
- CompoundCommand linkingPinsAndParamsCommand = new CompoundCommand();
- // CompositeTransactionalCommand linkingPinsAndParamsCommand = new CompositeTransactionalCommand(EditorUtils.getTransactionalEditingDomain(), "Pin synchronization");////$NON-NLS-1$
- if(invocationAction instanceof CallAction) {
- CallAction callAction = (CallAction)invocationAction;
- List<Parameter> callActionParams = getParametersFromCallAction(callAction);
- Map<Integer, TypedElement> inputParameters = new HashMap<Integer, TypedElement>();
- Map<Integer, TypedElement> outputParameters = new HashMap<Integer, TypedElement>();
- //Splitting parameters.
- PinAndParameterSynchronizer.splitParameters(callActionParams, Lists.<Parameter> newArrayList(), inputParameters, outputParameters, invocationAction);
- //Matching pins and parameters.
- matchPinsAndParams(inputPins, inputParameters, linkingPinsAndParamsCommand);
- matchPinsAndParams(outputPins, outputParameters, linkingPinsAndParamsCommand);
- } else if(invocationAction instanceof InvocationAction) {
- Map<Integer, TypedElement> invocationActionProperties = getPropertyFromInvocationAction(invocationAction);
- matchPinsAndParams(inputPins, invocationActionProperties, linkingPinsAndParamsCommand);
- }
- //Execution of the command
- executeCommand(linkingPinsAndParamsCommand, invocationAction);
- }
-
- /**
- * Refinement for the matchPinsAndParams(CallAction) method.
- *
- * @param pins
- * : the list of all input (or output) pins. The list will be filtered
- * to try to just perform a matching on pins that do not have eAnnotations linking
- * to parameters.
- * @param parameters
- * : parameters with the same direction as the pins.
- * @param globalCmd
- * : the command used to create the eAnnotations.
- */
- private static void matchPinsAndParams(List<? extends Pin> pins, Map<Integer, ? extends TypedElement> parameters, CompoundCommand globalCmd) {
- for(int pinIndex = 0; pinIndex < pins.size(); pinIndex++) {
- Pin pin = pins.get(pinIndex);
- //The matching is performed only on pins that do not have a pin-to-parameter link.
- if(lacksPinToParameterLink(pin)) {
- TypedElement paramWithSameIndex = parameters.get(pinIndex);
- boolean foundMatchingParam = false;
- if(paramWithSameIndex != null) {
- //A parameter has been found with the same index as the pin. If both have the same type, a link is created.
- if(pin.getType() == paramWithSameIndex.getType()) {
- LinkPinToParameter link = new LinkPinToParameter(pin, paramWithSameIndex);
- CreatePinToParameterLinkEAnnotation linkCommand = new CreatePinToParameterLinkEAnnotation(EditorUtils.getTransactionalEditingDomain(), link);
- if(linkCommand != null) {
- globalCmd.append(linkCommand);
- foundMatchingParam = true;
- }
- createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "The pin " + pin.getQualifiedName() + " " + "has been linked to the parameter " + paramWithSameIndex.getQualifiedName(), Type.INFO);
- }
- }
- if(!foundMatchingParam) {
- createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "The pin " + pin.getQualifiedName() + " will be deleted, along with its edges", Type.WARNING);
- }
- }
- }
- }
-
- /**
- * Checks whether a pin lacks the Pin-to-Parameter link
- */
- private static boolean lacksPinToParameterLink(Pin pin) {
- return pin.getEAnnotation(IPinToParameterLinkCommand.PIN_TO_PARAMETER_LINK) == null;
- }
-
- /**
- * @param callAction
- * @return the parameters from the behavior or the operation of the call action.
- */
- private static List<Parameter> getParametersFromCallAction(CallAction callAction) {
- List<Parameter> result = Lists.newArrayList();
- if(callAction instanceof CallBehaviorAction) {
- Behavior behavior = ((CallBehaviorAction)callAction).getBehavior();
- if(behavior != null) {
- result = behavior.getOwnedParameters();
- }
- } else if(callAction instanceof CallOperationAction) {
- Operation operation = ((CallOperationAction)callAction).getOperation();
- if(operation != null) {
- result = operation.getOwnedParameters();
- }
- }
- return result;
- }
-
- /**
- * @param callAction
- * @return the properties from the signal of the Invocation action (if any)
- */
- private static Map<Integer, TypedElement> getPropertyFromInvocationAction(InvocationAction invocationAction) {
- Map<Integer, TypedElement> result = Maps.newHashMap();
- if(invocationAction instanceof SendSignalAction) {
- Signal signal = ((SendSignalAction)invocationAction).getSignal();
- if(signal != null) {
- EList<Property> properties = signal.getOwnedAttributes();
- for(int index = 0; index < properties.size(); index++) {
- result.put(index, properties.get(index));
- }
- }
- } else if(invocationAction instanceof BroadcastSignalAction) {
- Signal signal = ((BroadcastSignalAction)invocationAction).getSignal();
- if(signal != null) {
- EList<Property> properties = signal.getOwnedAttributes();
- for(int index = 0; index < properties.size(); index++) {
- result.put(index, properties.get(index));
- }
- }
- }
- return result;
- }
-
- /**
- * Refining for the syncCallAction method.
- */
- private static void syncCallActionWhenOutdated(InvocationAction invocationAction) {
- //Command to reset all pins
- CompoundCommand cmd = null;
- if(invocationAction instanceof CallAction) {
- cmd = PinAndParameterSynchronizer.getResetPinsCmd(invocationAction);
- } else if(invocationAction instanceof SendSignalAction) {
- cmd = PinAndParameterSynchronizer.getResetPinsCmd(invocationAction);
- } else if(invocationAction instanceof BroadcastSignalAction) {
- cmd = PinAndParameterSynchronizer.getResetPinsCmd(invocationAction);
- }
- Element behaviorStructural = null;
- if(invocationAction instanceof CallBehaviorAction) {
- behaviorStructural = ((CallBehaviorAction)invocationAction).getBehavior();
- } else if(invocationAction instanceof CallOperationAction) {
- behaviorStructural = ((CallOperationAction)invocationAction).getOperation();
- } else if(invocationAction instanceof SendSignalAction) {
- behaviorStructural = ((SendSignalAction)invocationAction).getSignal();
- } else if(invocationAction instanceof BroadcastSignalAction) {
- behaviorStructural = ((BroadcastSignalAction)invocationAction).getSignal();
- }
- XMIResource xmiResource = PinAndParameterSynchronizer.getXMIResource(behaviorStructural);
- if(!cmd.isEmpty() && cmd.canExecute()) {
- //calculate incoming and outcoming edge
- Iterable<ActivityEdge> outgoing = Collections.emptyList();
- Iterable<ActivityEdge> incoming = Collections.emptyList();
- if(invocationAction instanceof CallAction) {
- for(Pin p : ((CallAction)invocationAction).getResults()) {
- if(!isUpToDate(p, xmiResource)) {
- outgoing = Iterables.concat(outgoing, p.getOutgoings());
- }
- }
- }
- for(Pin p : invocationAction.getArguments()) {
- if(!isUpToDate(p, xmiResource)) {
- incoming = Iterables.concat(incoming, p.getIncomings());
- }
- }
- HashSet<ActivityEdge> newHashSet = Sets.newHashSet(Iterables.concat(outgoing, incoming));
- //Notifify User that Edge will deleted
- DeleteActivityEdgeDialog dialog = new DeleteActivityEdgeDialog(new Shell(), newHashSet, invocationAction);
- if(dialog.open() == MessageDialog.OK) {
- IFile target = invocationAction.eResource() != null ? WorkspaceSynchronizer.getFile(invocationAction.eResource()) : null;
- for(ActivityEdge activityEdge : dialog.getEgdesToDelete()) {
- //Create a marker for all deleted edges
- if(!newHashSet.isEmpty()) {
- UMLItemProviderAdapterFactory umlAdapterFactory = new UMLItemProviderAdapterFactory();
- IItemLabelProvider edgeLabelProvider = (IItemLabelProvider)umlAdapterFactory.adapt(activityEdge, IItemLabelProvider.class);
- IItemLabelProvider callActionLabelProvider = (IItemLabelProvider)umlAdapterFactory.adapt(invocationAction, IItemLabelProvider.class);
- UMLMarkerNavigationProvider.addMarker(target, activityEdge.eResource().getURIFragment(activityEdge), EMFCoreUtil.getQualifiedName(invocationAction, true), "The edge " + edgeLabelProvider.getText(activityEdge) + " has been deleted since " + callActionLabelProvider.getText(invocationAction) + " has been synchronized", IStatus.WARNING);
- }
- //Destroy all edge
- EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(activityEdge);
- if(editingDomain instanceof TransactionalEditingDomain) {
- DestroyElementCommand detryCmd = new DestroyElementPapyrusCommand(new DestroyElementRequest(activityEdge, false));
- if(detryCmd != null && detryCmd.canExecute()) {
- ((TransactionalEditingDomain)editingDomain).getCommandStack().execute(new GMFtoEMFCommandWrapper(detryCmd));
- }
- }
- }
- //Reset all pin
- executeCommand(cmd, invocationAction);
- createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "The call action " + invocationAction.getQualifiedName() + " has been synchronized", Type.INFO);
- }
- }
- }
-
- public static void createNotification(String title, String text, Type type) {
- try {
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(PapyrusNotificationView.ID);
- } catch (PartInitException e) {
- }
- new NotificationBuilder().setAsynchronous(true).setTemporary(false).setTitle(title).setMessage(text).setType(type).run();
- }
-
- /**
- * Calculate if the call action needs to be synchronized
- *
- * @param invocationAction
- * @return
- */
- private static boolean isUpToDate(InvocationAction invocationAction) {
- ArrayList<TypedElement> typedElementArgument = null;
- ArrayList<InputPin> invocationActionArguments = Lists.newArrayList(invocationAction.getArguments());
- ArrayList<OutputPin> callActionResult = Lists.newArrayList();
- if(invocationAction instanceof CallAction) {
- callActionResult.addAll(((CallAction)invocationAction).getResults());
- }
- XMIResource xmiResource = null;
- if(invocationAction instanceof CallOperationAction) {
- CallOperationAction callOperationAction = (CallOperationAction)invocationAction;
- Operation operation = callOperationAction.getOperation();
- if(operation != null) {
- xmiResource = PinAndParameterSynchronizer.getXMIResource(operation);
- typedElementArgument = Lists.newArrayList(transformeToTypedElementIterable(callOperationAction.getOperation().getOwnedParameters()));
- }
- } else if(invocationAction instanceof CallBehaviorAction) {
- CallBehaviorAction callBehaviorAction = (CallBehaviorAction)invocationAction;
- Behavior behavior = callBehaviorAction.getBehavior();
- if(behavior != null) {
- xmiResource = PinAndParameterSynchronizer.getXMIResource(behavior);
- typedElementArgument = Lists.newArrayList(transformeToTypedElementIterable(behavior.getOwnedParameters()));
- }
- } else if(invocationAction instanceof SendSignalAction) {
- Signal signal = ((SendSignalAction)invocationAction).getSignal();
- if(signal != null) {
- xmiResource = PinAndParameterSynchronizer.getXMIResource(signal);
- typedElementArgument = Lists.newArrayList(transformeToTypedElementIterable(signal.getOwnedAttributes()));
- }
- } else if(invocationAction instanceof BroadcastSignalAction) {
- Signal signal = ((BroadcastSignalAction)invocationAction).getSignal();
- if(signal != null) {
- xmiResource = PinAndParameterSynchronizer.getXMIResource(signal);
- typedElementArgument = Lists.newArrayList(transformeToTypedElementIterable(signal.getOwnedAttributes()));
- }
- }
- if(typedElementArgument == null) {
- return true;
- }
- //checking if each pin is up to date.
- final Set<TypedElement> typedElementArgumentFound = new HashSet<TypedElement>();
- for(InputPin p : invocationActionArguments) {
- if(!isUpToDate(p, xmiResource)) {
- return false;
- } else {
- TypedElement pa = PinAndParameterSynchronizer.getLinkedParemeter(p, xmiResource);
- typedElementArgumentFound.add(pa);
- }
- }
- for(OutputPin p : callActionResult) {
- if(!isUpToDate(p, xmiResource)) {
- return false;
- } else {
- TypedElement pa = PinAndParameterSynchronizer.getLinkedParemeter(p, xmiResource);
- typedElementArgumentFound.add(pa);
- }
- }
- // Checking whether new pins should be created (meaning some parameters do not have matching pins)
- Iterable<TypedElement> intersectionBetweenPinParamsAndAllParams = Iterables.filter(typedElementArgument, new Predicate<TypedElement>() {
-
- public boolean apply(TypedElement input) {
- return !typedElementArgumentFound.contains(input);
- }
- });
- return Iterables.size(intersectionBetweenPinParamsAndAllParams) == 0;
- }
-
- /**
- * Transform a eObject to typed elements
- *
- * @param input
- * @return
- */
- private static Iterable<TypedElement> transformeToTypedElementIterable(Iterable<? extends EObject> input) {
- Iterable<TypedElement> typedElements = Iterables.transform(input, new Function<EObject, TypedElement>() {
-
- public TypedElement apply(EObject from) {
- if(from instanceof TypedElement) {
- return (TypedElement)from;
- }
- return null;
- }
- });
- return Iterables.filter(typedElements, Predicates.notNull());
- }
-
- /**
- * Refining of the isUpToDate method (checks whether the pin has the same
- * type & direction than its associated parameter.
- */
- public static boolean isUpToDate(Pin pin, XMIResource xmiResource) {
- boolean result = false;
- TypedElement typedElement = PinAndParameterSynchronizer.getLinkedParemeter(pin, xmiResource);
- if(typedElement != null) {
- if(pin.getType() != null) {
- result = pin.getType().isCompatibleWith(typedElement.getType());
- } else {
- result = (pin.getType() == typedElement.getType());
- }
- if(typedElement instanceof Parameter) {
- Parameter pa = (Parameter)typedElement;
- if(pin instanceof OutputPin) {
- boolean directionIsOut;
- directionIsOut = (pa.getDirection().getValue() == ParameterDirectionKind.OUT);
- directionIsOut |= (pa.getDirection().getValue() == ParameterDirectionKind.INOUT);
- directionIsOut |= (pa.getDirection().getValue() == ParameterDirectionKind.RETURN);
- result &= directionIsOut;
- } else if(pin instanceof InputPin) {
- boolean directionIsIn;
- directionIsIn = (pa.getDirection().getValue() == ParameterDirectionKind.IN);
- directionIsIn |= (pa.getDirection().getValue() == ParameterDirectionKind.INOUT);
- result &= directionIsIn;
- }
- }
- }
- return result;
- }
-
- /**
- * Test if the action can be reached (return false if the CallAction is in a controled package which is not loaded).
- *
- * @param callAction
- * @return
- */
- public static boolean isAccessible(InvocationAction callAction) {
- boolean result = false;
- EObject targetedBehavior = null;
- if(callAction instanceof CallBehaviorAction) {
- CallBehaviorAction cba = (CallBehaviorAction)callAction;
- targetedBehavior = cba.getBehavior();
- } else if(callAction instanceof CallOperationAction) {
- targetedBehavior = ((CallOperationAction)callAction).getOperation();
- } else if(callAction instanceof SendSignalAction) {
- targetedBehavior = ((SendSignalAction)callAction).getSignal();
- } else if(callAction instanceof BroadcastSignalAction) {
- targetedBehavior = ((BroadcastSignalAction)callAction).getSignal();
- }
- if(targetedBehavior != null) {
- result = !targetedBehavior.eIsProxy();
- }
- return result;
- }
-
- /**
- * Executes the supplied command inside an <code>unchecked action</code>
- *
- * @param cmd
- * command that can be executed (i.e., cmd.canExecute() == true)
- */
- protected static void executeCommand(final org.eclipse.emf.common.command.Command cmd, EObject eObject) {
- if(cmd != null && cmd.canExecute()) {
- Map<String, Boolean> options = null;
- options = Collections.singletonMap(Transaction.OPTION_NO_VALIDATION, Boolean.TRUE);
- EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(eObject);
- if(editingDomain instanceof TransactionalEditingDomain) {
- TransactionalEditingDomain d = (TransactionalEditingDomain)editingDomain;
- try {
- if(d.getCommandStack() instanceof TransactionalCommandStack) {
- TransactionalCommandStack comStack = (TransactionalCommandStack)d.getCommandStack();
- comStack.execute(cmd, options);
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (RollbackException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- /**
- * @return a list of selected objects view
- */
- protected static List<IGraphicalEditPart> getIGraphicalPartSelection() {
- List<IGraphicalEditPart> viewSelected = new ArrayList<IGraphicalEditPart>();
- ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
- if(false == selection instanceof IStructuredSelection) {
- return Collections.emptyList();
- }
- for(Object object : ((IStructuredSelection)selection).toList()) {
- if(false == object instanceof IGraphicalEditPart) {
- continue;
- }
- if(object instanceof DiagramEditPart) {
- continue;
- }
- viewSelected.add((IGraphicalEditPart)object);
- }
- return viewSelected;
- }
-
- /**
- * Dialog to display to the user that egdes will be deleted
- *
- * @author arthur daussy
- *
- */
- public static class DeleteActivityEdgeDialog extends MessageDialog {
-
- /**
- * All incoming out coming edges
- */
- private Iterable<ActivityEdge> egdes;
-
- /***
- * {@link CallAction} to sync
- */
- private InvocationAction callAction;
-
- public DeleteActivityEdgeDialog(Shell parentShell, Iterable<ActivityEdge> egdes, InvocationAction callAction) {
- super(parentShell, SYNCHRONIZE_PINS_AND_PARAMETERS, getIcon(), "", WARNING, new String[]{ "Synchronize", "Cancel" }, 0);////$NON-NLS-1$////$NON-NLS-2$
- this.egdes = egdes;
- this.callAction = callAction;
- this.message = getEdgeListString();
- }
-
- private String getEdgeListString() {
- UMLItemProviderAdapterFactory t = new UMLItemProviderAdapterFactory();
- IItemLabelProvider provider = (IItemLabelProvider)t.adapt(callAction, IItemLabelProvider.class);
- StringBuilder builder = new StringBuilder("If you synchronize " + provider.getText(callAction) + " the following edges will be deleted : \n ");////$NON-NLS-1$
- for(ActivityEdge e : egdes) {
- provider = (IItemLabelProvider)t.adapt(e, IItemLabelProvider.class);
- builder.append(provider.getText(e)).append(" \n");
- }
- return builder.toString();
- }
-
- @Override
- public int open() {
- //If no edge to delete nothing to do
- if(egdes.iterator().hasNext()) {
- return super.open();
- }
- return 0;
- }
-
- public Iterable<ActivityEdge> getEgdesToDelete() {
- return egdes;
- }
- }
-}
+/***************************************************************************** + * 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 + * Olivier Mélois (Atos) : olivier.melois@atos.net - 371712 + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.activity.handlers; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.core.commands.ExecutionEvent; +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.core.runtime.IStatus; +import org.eclipse.emf.common.command.CompoundCommand; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.xmi.XMIResource; +import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain; +import org.eclipse.emf.edit.domain.EditingDomain; +import org.eclipse.emf.edit.provider.IItemLabelProvider; +import org.eclipse.emf.transaction.RollbackException; +import org.eclipse.emf.transaction.Transaction; +import org.eclipse.emf.transaction.TransactionalCommandStack; +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.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.emf.core.util.EMFCoreUtil; +import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand; +import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.papyrus.commands.DestroyElementPapyrusCommand; +import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper; +import org.eclipse.papyrus.infra.core.utils.EditorUtils; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.Type; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder; +import org.eclipse.papyrus.infra.widgets.toolbox.notification.view.PapyrusNotificationView; +import org.eclipse.papyrus.uml.diagram.activity.commands.CreatePinToParameterLinkEAnnotation; +import org.eclipse.papyrus.uml.diagram.activity.helper.IPinToParameterLinkCommand; +import org.eclipse.papyrus.uml.diagram.activity.helper.PinAndParameterSynchronizer; +import org.eclipse.papyrus.uml.diagram.activity.helper.datastructure.LinkPinToParameter; +import org.eclipse.papyrus.uml.diagram.activity.providers.UMLMarkerNavigationProvider; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.handlers.HandlerUtil; +import org.eclipse.uml2.uml.ActivityEdge; +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.Element; +import org.eclipse.uml2.uml.InputPin; +import org.eclipse.uml2.uml.InvocationAction; +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.SendSignalAction; +import org.eclipse.uml2.uml.Signal; +import org.eclipse.uml2.uml.TypedElement; +import org.eclipse.uml2.uml.edit.providers.UMLItemProviderAdapterFactory; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +/** + * Handler to synchronized the pin and parameter manually + * + * @author arthur daussy + * + */ +public class SynchronizePinsParametersHandler extends AbstractSynchronizePinsAndParameters { + + /** + * Label for the handler (use in notification and dialog) + */ + private static final String SYNCHRONIZE_PINS_AND_PARAMETERS = "Synchronize pins and parameters"; //$NON-NLS-1$ + + /** + * Constructor + */ + public SynchronizePinsParametersHandler() { + } + + /** + * Execute unprotected command + */ + public Object execute(ExecutionEvent event) throws ExecutionException { + ISelection selection = HandlerUtil.getActiveMenuSelection(event); + if(selection instanceof StructuredSelection) { + StructuredSelection structuredSelection = (StructuredSelection)selection; + 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(); + } + if(element instanceof InvocationAction) { + syncInvocationAction((InvocationAction)element); + } + } + } + return null; + } + + /** + * Synchronizes a Call Action + * + * @param callAction + */ + public static void syncInvocationAction(InvocationAction invocationAction) { + if(!isAccessible(invocationAction)) { + createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "Unable to synchronize pins on " + invocationAction.getQualifiedName() + " : the ressource is unreachable", Type.WARNING); + return; + } + //Trying to match pins of the callAction with parameters of same index/direction/type. + //The pins that can not be matched will be destroyed by the "syncCallActionWhenOutdated" method. + matchPinsAndParams(invocationAction); + if(isUpToDate(invocationAction)) { + createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "The call action " + invocationAction.getQualifiedName() + " is up to date", Type.INFO); + } else { + //Synchronization when a link between pins and params already exists but is outdated. + syncCallActionWhenOutdated(invocationAction); + } + //Renaming pins according to their associated parameters. + renamePins(invocationAction); + } + + /** + * Rename the pins according to their parameters when possible. + * + * @param invocationAction + */ + private static void renamePins(final InvocationAction invocationAction) { + //Command used as renaming the pins change the model. + AbstractTransactionalCommand renamePinsCommand = new AbstractTransactionalCommand(EditorUtils.getTransactionalEditingDomain(), "renaming pins", null) { //$NON-NLS-1$ + + @Override + protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { + Iterable<? extends Pin> allPins = Lists.newArrayList(invocationAction.getArguments()); + if(invocationAction instanceof CallAction) { + allPins = Iterables.concat(((CallAction)invocationAction).getResults(), allPins); + } + Element behaviorStructural = null; + if(invocationAction instanceof CallBehaviorAction) { + behaviorStructural = ((CallBehaviorAction)invocationAction).getBehavior(); + } else if(invocationAction instanceof CallOperationAction) { + behaviorStructural = ((CallOperationAction)invocationAction).getOperation(); + } else if(invocationAction instanceof SendSignalAction) { + behaviorStructural = ((SendSignalAction)invocationAction).getSignal(); + } else if(invocationAction instanceof BroadcastSignalAction) { + behaviorStructural = ((BroadcastSignalAction)invocationAction).getSignal(); + } + XMIResource xmiResource = PinAndParameterSynchronizer.getXMIResource(behaviorStructural); + for(Pin pin : allPins) { + TypedElement typedElement = PinAndParameterSynchronizer.getLinkedParemeter(pin, xmiResource); + if(typedElement != null) { + String paramName = typedElement.getName(); + pin.setName(paramName); + } + } + return CommandResult.newOKCommandResult(); + } + }; + executeCommand(new GMFtoEMFCommandWrapper(renamePinsCommand), invocationAction); + } + + /** + * Method used to match the pins of a call action with parameters of that same call action, + * when the pins do not have eAnnotations already linking to parameters. If no match can + * be performed, the pin is destroyed along with its edges. + * + * @param callAction + */ + private static void matchPinsAndParams(InvocationAction invocationAction) { + List<InputPin> inputPins = Lists.newArrayList(invocationAction.getArguments()); + List<OutputPin> outputPins = null; + if(outputPins instanceof CallAction) { + CallAction callAction = (CallAction)outputPins; + outputPins = callAction.getResults(); + } else { + outputPins = Collections.emptyList(); + } + //The command that is going to be executed. + CompoundCommand linkingPinsAndParamsCommand = new CompoundCommand(); + // CompositeTransactionalCommand linkingPinsAndParamsCommand = new CompositeTransactionalCommand(EditorUtils.getTransactionalEditingDomain(), "Pin synchronization");////$NON-NLS-1$ + if(invocationAction instanceof CallAction) { + CallAction callAction = (CallAction)invocationAction; + List<Parameter> callActionParams = getParametersFromCallAction(callAction); + Map<Integer, TypedElement> inputParameters = new HashMap<Integer, TypedElement>(); + Map<Integer, TypedElement> outputParameters = new HashMap<Integer, TypedElement>(); + //Splitting parameters. + PinAndParameterSynchronizer.splitParameters(callActionParams, Lists.<Parameter> newArrayList(), inputParameters, outputParameters, invocationAction); + //Matching pins and parameters. + matchPinsAndParams(inputPins, inputParameters, linkingPinsAndParamsCommand); + matchPinsAndParams(outputPins, outputParameters, linkingPinsAndParamsCommand); + } else if(invocationAction instanceof InvocationAction) { + Map<Integer, TypedElement> invocationActionProperties = getPropertyFromInvocationAction(invocationAction); + matchPinsAndParams(inputPins, invocationActionProperties, linkingPinsAndParamsCommand); + } + //Execution of the command + executeCommand(linkingPinsAndParamsCommand, invocationAction); + } + + /** + * Refinement for the matchPinsAndParams(CallAction) method. + * + * @param pins + * : the list of all input (or output) pins. The list will be filtered + * to try to just perform a matching on pins that do not have eAnnotations linking + * to parameters. + * @param parameters + * : parameters with the same direction as the pins. + * @param globalCmd + * : the command used to create the eAnnotations. + */ + private static void matchPinsAndParams(List<? extends Pin> pins, Map<Integer, ? extends TypedElement> parameters, CompoundCommand globalCmd) { + for(int pinIndex = 0; pinIndex < pins.size(); pinIndex++) { + Pin pin = pins.get(pinIndex); + //The matching is performed only on pins that do not have a pin-to-parameter link. + if(lacksPinToParameterLink(pin)) { + TypedElement paramWithSameIndex = parameters.get(pinIndex); + boolean foundMatchingParam = false; + if(paramWithSameIndex != null) { + //A parameter has been found with the same index as the pin. If both have the same type, a link is created. + if(pin.getType() == paramWithSameIndex.getType()) { + LinkPinToParameter link = new LinkPinToParameter(pin, paramWithSameIndex); + CreatePinToParameterLinkEAnnotation linkCommand = new CreatePinToParameterLinkEAnnotation(EditorUtils.getTransactionalEditingDomain(), link); + if(linkCommand != null) { + globalCmd.append(linkCommand); + foundMatchingParam = true; + } + createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "The pin " + pin.getQualifiedName() + " " + "has been linked to the parameter " + paramWithSameIndex.getQualifiedName(), Type.INFO); + } + } + if(!foundMatchingParam) { + createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "The pin " + pin.getQualifiedName() + " will be deleted, along with its edges", Type.WARNING); + } + } + } + } + + /** + * Checks whether a pin lacks the Pin-to-Parameter link + */ + private static boolean lacksPinToParameterLink(Pin pin) { + return pin.getEAnnotation(IPinToParameterLinkCommand.PIN_TO_PARAMETER_LINK) == null; + } + + /** + * @param callAction + * @return the parameters from the behavior or the operation of the call action. + */ + private static List<Parameter> getParametersFromCallAction(CallAction callAction) { + List<Parameter> result = Lists.newArrayList(); + if(callAction instanceof CallBehaviorAction) { + Behavior behavior = ((CallBehaviorAction)callAction).getBehavior(); + if(behavior != null) { + result = behavior.getOwnedParameters(); + } + } else if(callAction instanceof CallOperationAction) { + Operation operation = ((CallOperationAction)callAction).getOperation(); + if(operation != null) { + result = operation.getOwnedParameters(); + } + } + return result; + } + + /** + * @param callAction + * @return the properties from the signal of the Invocation action (if any) + */ + private static Map<Integer, TypedElement> getPropertyFromInvocationAction(InvocationAction invocationAction) { + Map<Integer, TypedElement> result = Maps.newHashMap(); + if(invocationAction instanceof SendSignalAction) { + Signal signal = ((SendSignalAction)invocationAction).getSignal(); + if(signal != null) { + EList<Property> properties = signal.getOwnedAttributes(); + for(int index = 0; index < properties.size(); index++) { + result.put(index, properties.get(index)); + } + } + } else if(invocationAction instanceof BroadcastSignalAction) { + Signal signal = ((BroadcastSignalAction)invocationAction).getSignal(); + if(signal != null) { + EList<Property> properties = signal.getOwnedAttributes(); + for(int index = 0; index < properties.size(); index++) { + result.put(index, properties.get(index)); + } + } + } + return result; + } + + /** + * Refining for the syncCallAction method. + */ + private static void syncCallActionWhenOutdated(InvocationAction invocationAction) { + //Command to reset all pins + CompoundCommand cmd = null; + if(invocationAction instanceof CallAction) { + cmd = PinAndParameterSynchronizer.getResetPinsCmd(invocationAction); + } else if(invocationAction instanceof SendSignalAction) { + cmd = PinAndParameterSynchronizer.getResetPinsCmd(invocationAction); + } else if(invocationAction instanceof BroadcastSignalAction) { + cmd = PinAndParameterSynchronizer.getResetPinsCmd(invocationAction); + } + Element behaviorStructural = null; + if(invocationAction instanceof CallBehaviorAction) { + behaviorStructural = ((CallBehaviorAction)invocationAction).getBehavior(); + } else if(invocationAction instanceof CallOperationAction) { + behaviorStructural = ((CallOperationAction)invocationAction).getOperation(); + } else if(invocationAction instanceof SendSignalAction) { + behaviorStructural = ((SendSignalAction)invocationAction).getSignal(); + } else if(invocationAction instanceof BroadcastSignalAction) { + behaviorStructural = ((BroadcastSignalAction)invocationAction).getSignal(); + } + XMIResource xmiResource = PinAndParameterSynchronizer.getXMIResource(behaviorStructural); + if(!cmd.isEmpty() && cmd.canExecute()) { + //calculate incoming and outcoming edge + Iterable<ActivityEdge> outgoing = Collections.emptyList(); + Iterable<ActivityEdge> incoming = Collections.emptyList(); + if(invocationAction instanceof CallAction) { + for(Pin p : ((CallAction)invocationAction).getResults()) { + if(!isUpToDate(p, xmiResource)) { + outgoing = Iterables.concat(outgoing, p.getOutgoings()); + } + } + } + for(Pin p : invocationAction.getArguments()) { + if(!isUpToDate(p, xmiResource)) { + incoming = Iterables.concat(incoming, p.getIncomings()); + } + } + HashSet<ActivityEdge> newHashSet = Sets.newHashSet(Iterables.concat(outgoing, incoming)); + //Notifify User that Edge will deleted + DeleteActivityEdgeDialog dialog = new DeleteActivityEdgeDialog(new Shell(), newHashSet, invocationAction); + if(dialog.open() == MessageDialog.OK) { + IFile target = invocationAction.eResource() != null ? WorkspaceSynchronizer.getFile(invocationAction.eResource()) : null; + for(ActivityEdge activityEdge : dialog.getEgdesToDelete()) { + //Create a marker for all deleted edges + if(!newHashSet.isEmpty()) { + UMLItemProviderAdapterFactory umlAdapterFactory = new UMLItemProviderAdapterFactory(); + IItemLabelProvider edgeLabelProvider = (IItemLabelProvider)umlAdapterFactory.adapt(activityEdge, IItemLabelProvider.class); + IItemLabelProvider callActionLabelProvider = (IItemLabelProvider)umlAdapterFactory.adapt(invocationAction, IItemLabelProvider.class); + UMLMarkerNavigationProvider.addMarker(target, activityEdge.eResource().getURIFragment(activityEdge), EMFCoreUtil.getQualifiedName(invocationAction, true), "The edge " + edgeLabelProvider.getText(activityEdge) + " has been deleted since " + callActionLabelProvider.getText(invocationAction) + " has been synchronized", IStatus.WARNING); + } + //Destroy all edge + EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(activityEdge); + if(editingDomain instanceof TransactionalEditingDomain) { + DestroyElementCommand detryCmd = new DestroyElementPapyrusCommand(new DestroyElementRequest(activityEdge, false)); + if(detryCmd != null && detryCmd.canExecute()) { + ((TransactionalEditingDomain)editingDomain).getCommandStack().execute(new GMFtoEMFCommandWrapper(detryCmd)); + } + } + } + //Reset all pin + executeCommand(cmd, invocationAction); + createNotification(SYNCHRONIZE_PINS_AND_PARAMETERS, "The call action " + invocationAction.getQualifiedName() + " has been synchronized", Type.INFO); + } + } + } + + public static void createNotification(String title, String text, Type type) { + try { + PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(PapyrusNotificationView.ID); + } catch (PartInitException e) { + } + new NotificationBuilder().setAsynchronous(true).setTemporary(false).setTitle(title).setMessage(text).setType(type).run(); + } + + /** + * Calculate if the call action needs to be synchronized + * + * @param invocationAction + * @return + */ + private static boolean isUpToDate(InvocationAction invocationAction) { + ArrayList<TypedElement> typedElementArgument = null; + ArrayList<InputPin> invocationActionArguments = Lists.newArrayList(invocationAction.getArguments()); + ArrayList<OutputPin> callActionResult = Lists.newArrayList(); + if(invocationAction instanceof CallAction) { + callActionResult.addAll(((CallAction)invocationAction).getResults()); + } + XMIResource xmiResource = null; + if(invocationAction instanceof CallOperationAction) { + CallOperationAction callOperationAction = (CallOperationAction)invocationAction; + Operation operation = callOperationAction.getOperation(); + if(operation != null) { + xmiResource = PinAndParameterSynchronizer.getXMIResource(operation); + typedElementArgument = Lists.newArrayList(transformeToTypedElementIterable(callOperationAction.getOperation().getOwnedParameters())); + } + } else if(invocationAction instanceof CallBehaviorAction) { + CallBehaviorAction callBehaviorAction = (CallBehaviorAction)invocationAction; + Behavior behavior = callBehaviorAction.getBehavior(); + if(behavior != null) { + xmiResource = PinAndParameterSynchronizer.getXMIResource(behavior); + typedElementArgument = Lists.newArrayList(transformeToTypedElementIterable(behavior.getOwnedParameters())); + } + } else if(invocationAction instanceof SendSignalAction) { + Signal signal = ((SendSignalAction)invocationAction).getSignal(); + if(signal != null) { + xmiResource = PinAndParameterSynchronizer.getXMIResource(signal); + typedElementArgument = Lists.newArrayList(transformeToTypedElementIterable(signal.getOwnedAttributes())); + } + } else if(invocationAction instanceof BroadcastSignalAction) { + Signal signal = ((BroadcastSignalAction)invocationAction).getSignal(); + if(signal != null) { + xmiResource = PinAndParameterSynchronizer.getXMIResource(signal); + typedElementArgument = Lists.newArrayList(transformeToTypedElementIterable(signal.getOwnedAttributes())); + } + } + if(typedElementArgument == null) { + return true; + } + //checking if each pin is up to date. + final Set<TypedElement> typedElementArgumentFound = new HashSet<TypedElement>(); + for(InputPin p : invocationActionArguments) { + if(!isUpToDate(p, xmiResource)) { + return false; + } else { + TypedElement pa = PinAndParameterSynchronizer.getLinkedParemeter(p, xmiResource); + typedElementArgumentFound.add(pa); + } + } + for(OutputPin p : callActionResult) { + if(!isUpToDate(p, xmiResource)) { + return false; + } else { + TypedElement pa = PinAndParameterSynchronizer.getLinkedParemeter(p, xmiResource); + typedElementArgumentFound.add(pa); + } + } + // Checking whether new pins should be created (meaning some parameters do not have matching pins) + Iterable<TypedElement> intersectionBetweenPinParamsAndAllParams = Iterables.filter(typedElementArgument, new Predicate<TypedElement>() { + + public boolean apply(TypedElement input) { + return !typedElementArgumentFound.contains(input); + } + }); + return Iterables.size(intersectionBetweenPinParamsAndAllParams) == 0; + } + + /** + * Transform a eObject to typed elements + * + * @param input + * @return + */ + private static Iterable<TypedElement> transformeToTypedElementIterable(Iterable<? extends EObject> input) { + Iterable<TypedElement> typedElements = Iterables.transform(input, new Function<EObject, TypedElement>() { + + public TypedElement apply(EObject from) { + if(from instanceof TypedElement) { + return (TypedElement)from; + } + return null; + } + }); + return Iterables.filter(typedElements, Predicates.notNull()); + } + + /** + * Refining of the isUpToDate method (checks whether the pin has the same + * type & direction than its associated parameter. + */ + public static boolean isUpToDate(Pin pin, XMIResource xmiResource) { + boolean result = false; + TypedElement typedElement = PinAndParameterSynchronizer.getLinkedParemeter(pin, xmiResource); + if(typedElement != null) { + if(pin.getType() != null) { + result = pin.getType().isCompatibleWith(typedElement.getType()); + } else { + result = (pin.getType() == typedElement.getType()); + } + if(typedElement instanceof Parameter) { + Parameter pa = (Parameter)typedElement; + if(pin instanceof OutputPin) { + boolean directionIsOut; + directionIsOut = (pa.getDirection().getValue() == ParameterDirectionKind.OUT); + directionIsOut |= (pa.getDirection().getValue() == ParameterDirectionKind.INOUT); + directionIsOut |= (pa.getDirection().getValue() == ParameterDirectionKind.RETURN); + result &= directionIsOut; + } else if(pin instanceof InputPin) { + boolean directionIsIn; + directionIsIn = (pa.getDirection().getValue() == ParameterDirectionKind.IN); + directionIsIn |= (pa.getDirection().getValue() == ParameterDirectionKind.INOUT); + result &= directionIsIn; + } + } + } + return result; + } + + /** + * Test if the action can be reached (return false if the CallAction is in a controled package which is not loaded). + * + * @param callAction + * @return + */ + public static boolean isAccessible(InvocationAction callAction) { + boolean result = false; + EObject targetedBehavior = null; + if(callAction instanceof CallBehaviorAction) { + CallBehaviorAction cba = (CallBehaviorAction)callAction; + targetedBehavior = cba.getBehavior(); + } else if(callAction instanceof CallOperationAction) { + targetedBehavior = ((CallOperationAction)callAction).getOperation(); + } else if(callAction instanceof SendSignalAction) { + targetedBehavior = ((SendSignalAction)callAction).getSignal(); + } else if(callAction instanceof BroadcastSignalAction) { + targetedBehavior = ((BroadcastSignalAction)callAction).getSignal(); + } + if(targetedBehavior != null) { + result = !targetedBehavior.eIsProxy(); + } + return result; + } + + /** + * Executes the supplied command inside an <code>unchecked action</code> + * + * @param cmd + * command that can be executed (i.e., cmd.canExecute() == true) + */ + protected static void executeCommand(final org.eclipse.emf.common.command.Command cmd, EObject eObject) { + if(cmd != null && cmd.canExecute()) { + Map<String, Boolean> options = null; + options = Collections.singletonMap(Transaction.OPTION_NO_VALIDATION, Boolean.TRUE); + EditingDomain editingDomain = AdapterFactoryEditingDomain.getEditingDomainFor(eObject); + if(editingDomain instanceof TransactionalEditingDomain) { + TransactionalEditingDomain d = (TransactionalEditingDomain)editingDomain; + try { + if(d.getCommandStack() instanceof TransactionalCommandStack) { + TransactionalCommandStack comStack = (TransactionalCommandStack)d.getCommandStack(); + comStack.execute(cmd, options); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } catch (RollbackException e) { + e.printStackTrace(); + } + } + } + } + + /** + * @return a list of selected objects view + */ + protected static List<IGraphicalEditPart> getIGraphicalPartSelection() { + List<IGraphicalEditPart> viewSelected = new ArrayList<IGraphicalEditPart>(); + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + ISelection selection = activeWorkbenchWindow.getSelectionService().getSelection(); + if(false == selection instanceof IStructuredSelection) { + return Collections.emptyList(); + } + for(Object object : ((IStructuredSelection)selection).toList()) { + if(false == object instanceof IGraphicalEditPart) { + continue; + } + if(object instanceof DiagramEditPart) { + continue; + } + viewSelected.add((IGraphicalEditPart)object); + } + } + return viewSelected; + } + + /** + * Dialog to display to the user that egdes will be deleted + * + * @author arthur daussy + * + */ + public static class DeleteActivityEdgeDialog extends MessageDialog { + + /** + * All incoming out coming edges + */ + private Iterable<ActivityEdge> egdes; + + /*** + * {@link CallAction} to sync + */ + private InvocationAction callAction; + + public DeleteActivityEdgeDialog(Shell parentShell, Iterable<ActivityEdge> egdes, InvocationAction callAction) { + super(parentShell, SYNCHRONIZE_PINS_AND_PARAMETERS, getIcon(), "", WARNING, new String[]{ "Synchronize", "Cancel" }, 0);//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + this.egdes = egdes; + this.callAction = callAction; + this.message = getEdgeListString(); + } + + private String getEdgeListString() { + UMLItemProviderAdapterFactory t = new UMLItemProviderAdapterFactory(); + IItemLabelProvider provider = (IItemLabelProvider)t.adapt(callAction, IItemLabelProvider.class); + StringBuilder builder = new StringBuilder("If you synchronize " + provider.getText(callAction) + " the following edges will be deleted : \n ");//$NON-NLS-1$ //$NON-NLS-2$ + for(ActivityEdge e : egdes) { + provider = (IItemLabelProvider)t.adapt(e, IItemLabelProvider.class); + builder.append(provider.getText(e)).append(" \n"); + } + return builder.toString(); + } + + @Override + public int open() { + //If no edge to delete nothing to do + if(egdes.iterator().hasNext()) { + return super.open(); + } + return 0; + } + + public Iterable<ActivityEdge> getEgdesToDelete() { + return egdes; + } + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/actions/AbstractAction.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/actions/AbstractAction.java index 0b4089c6041..f972224640b 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/actions/AbstractAction.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/actions/AbstractAction.java @@ -24,6 +24,7 @@ import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.papyrus.infra.core.editor.IMultiDiagramEditor; import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** @@ -67,22 +68,25 @@ public abstract class AbstractAction extends Action { */ protected List<View> getSelection() { List<View> viewSelected = new ArrayList<View>(); - ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); - if(false == selection instanceof IStructuredSelection) { - return Collections.emptyList(); - } - for(Object object : ((IStructuredSelection)selection).toList()) { - if(false == object instanceof IGraphicalEditPart) { - continue; - } - if(object instanceof DiagramEditPart) { - continue; - } - View view = ((IGraphicalEditPart)object).getNotationView(); - if(view.getEAnnotation("Shortcut") != null) { - continue; + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + ISelection selection = activeWorkbenchWindow.getSelectionService().getSelection(); + if(false == selection instanceof IStructuredSelection) { + return Collections.emptyList(); } - viewSelected.add(view); + for(Object object : ((IStructuredSelection)selection).toList()) { + if(false == object instanceof IGraphicalEditPart) { + continue; + } + if(object instanceof DiagramEditPart) { + continue; + } + View view = ((IGraphicalEditPart)object).getNotationView(); + if(view.getEAnnotation("Shortcut") != null) { + continue; + } + viewSelected.add(view); + } } return viewSelected; } diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/actions/handlers/AbstractShowHideHandler.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/actions/handlers/AbstractShowHideHandler.java index e6b554ad39c..0d9a523e021 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/actions/handlers/AbstractShowHideHandler.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/actions/handlers/AbstractShowHideHandler.java @@ -26,6 +26,7 @@ import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.papyrus.uml.diagram.common.actions.AbstractShowHideAction; import org.eclipse.ui.ISelectionService; +import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** @@ -93,21 +94,25 @@ abstract public class AbstractShowHideHandler extends AbstractHandler { */ protected void buildSelection() { this.selection.clear(); - ISelectionService selectionService = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService(); - ISelection selectionTmp = selectionService.getSelection(); - if((selectionTmp != null) && (!selectionTmp.isEmpty())) { - if(selectionTmp instanceof StructuredSelection) { - Iterator<?> it = ((StructuredSelection)selectionTmp).iterator(); - while(it.hasNext()) { - Object current = it.next(); - if(current instanceof IGraphicalEditPart) { - EditPolicy editpolicy = ((IGraphicalEditPart)current).getEditPolicy(this.editpolicy); - if(editpolicy != null) { - this.selection.add((IGraphicalEditPart)current); + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + ISelectionService selectionService = activeWorkbenchWindow.getSelectionService(); + ISelection selectionTmp = selectionService.getSelection(); + if((selectionTmp != null) && (!selectionTmp.isEmpty())) { + if(selectionTmp instanceof StructuredSelection) { + Iterator<?> it = ((StructuredSelection)selectionTmp).iterator(); + while(it.hasNext()) { + Object current = it.next(); + if(current instanceof IGraphicalEditPart) { + EditPolicy editpolicy = ((IGraphicalEditPart)current).getEditPolicy(this.editpolicy); + if(editpolicy != null) { + this.selection.add((IGraphicalEditPart)current); + } } } } - } + } } + } } diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/handlers/RenamedElementHandler.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/handlers/RenamedElementHandler.java index 0753da97b69..ea16ac5ab22 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/handlers/RenamedElementHandler.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.common/src/org/eclipse/papyrus/uml/diagram/common/handlers/RenamedElementHandler.java @@ -30,6 +30,7 @@ import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.papyrus.infra.emf.utils.EMFHelper; import org.eclipse.papyrus.infra.gmfdiag.common.utils.DiagramEditPartsUtil; +import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; /** @@ -81,24 +82,22 @@ public class RenamedElementHandler extends AbstractHandler { */ protected List<IGraphicalEditPart> getSelectedElements() { List<IGraphicalEditPart> editparts = new ArrayList<IGraphicalEditPart>(); - - ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); - if(selection instanceof IStructuredSelection) { - - IStructuredSelection structuredSelection = (IStructuredSelection)selection; - - Iterator<?> it = structuredSelection.iterator(); - while(it.hasNext()) { - Object object = it.next(); - if(object instanceof IGraphicalEditPart) { - editparts.add((IGraphicalEditPart)object); + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + ISelection selection = activeWorkbenchWindow.getSelectionService().getSelection(); + if(selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection)selection; + Iterator<?> it = structuredSelection.iterator(); + while(it.hasNext()) { + Object object = it.next(); + if(object instanceof IGraphicalEditPart) { + editparts.add((IGraphicalEditPart)object); + } } - } - - } else if(selection instanceof IGraphicalEditPart) { - editparts.add((IGraphicalEditPart)selection); + } else if(selection instanceof IGraphicalEditPart) { + editparts.add((IGraphicalEditPart)selection); + } } - return editparts; } } diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.component/custom-src/org/eclipse/papyrus/uml/diagram/component/custom/handler/ChangeShapeHandler.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.component/custom-src/org/eclipse/papyrus/uml/diagram/component/custom/handler/ChangeShapeHandler.java index 12d20b5dabf..b345b71b617 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.component/custom-src/org/eclipse/papyrus/uml/diagram/component/custom/handler/ChangeShapeHandler.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.component/custom-src/org/eclipse/papyrus/uml/diagram/component/custom/handler/ChangeShapeHandler.java @@ -1,124 +1,128 @@ -/*****************************************************************************
- * Copyright (c) 2012 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.component.custom.handler;
-
-import java.util.ArrayList;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.emf.edit.command.DeleteCommand;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart;
-import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.gmf.runtime.notation.Edge;
-import org.eclipse.gmf.runtime.notation.NotationPackage;
-import org.eclipse.gmf.runtime.notation.View;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper;
-import org.eclipse.papyrus.infra.gmfdiag.common.utils.ServiceUtilsForEditPart;
-import org.eclipse.papyrus.uml.diagram.common.commands.SemanticAdapter;
-import org.eclipse.papyrus.uml.diagram.component.custom.command.DeferredSetViewCommand;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISelectionService;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * This class is an abstract class in charge to transform a editpart into another editpart
- *
- */
-public abstract class ChangeShapeHandler extends AbstractHandler {
-
- protected TransactionalEditingDomain transactionalEditingDomain = null;
-
- protected org.eclipse.uml2.uml.Element selectedElement = null;
- protected String newType;
-
- /**
- *
- * Constructor.
- *
- */
- public ChangeShapeHandler() {
- super();
- }
-
- protected abstract AbstractTransactionalCommand getChangeShapeCommand(final GraphicalEditPart editPart);
-
- /**
- *
- * @return null or the selected editPart
- */
- protected GraphicalEditPart getSelectedGraphicalEditpart() {
- ISelectionService selectionService = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService();
- ISelection selection = selectionService.getSelection();
- if(selection instanceof IStructuredSelection) {
- Object selectedobject = ((IStructuredSelection)selection).getFirstElement();
- if(selectedobject instanceof GraphicalEditPart) {
- return (GraphicalEditPart)selectedobject;
- }
- }
- return null;
- }
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- final GraphicalEditPart editPart = getSelectedGraphicalEditpart();
- ServiceUtilsForEditPart util = ServiceUtilsForEditPart.getInstance();
- try {
- transactionalEditingDomain = util.getTransactionalEditingDomain(editPart);
- } catch (Exception e) {
- System.err.println("impossible to get the Transactional Editing Domain " + e);
- }
- try {
- editPart.getEditingDomain().runExclusive(new Runnable() {
-
- public void run() {
- Display.getCurrent().asyncExec(new Runnable() {
-
- public void run() {
- //get Links
- View view=(View)(editPart.getModel());
- TransactionalEditingDomain domain= editPart.getEditingDomain();
- @SuppressWarnings("unchecked")
- ArrayList<Edge>targetEdge= new ArrayList<Edge>(view.getTargetEdges());
- @SuppressWarnings("unchecked")
- ArrayList<Edge>sourceEdge= new ArrayList<Edge>(view.getSourceEdges());
-
- //create new Shape
- AbstractTransactionalCommand createCommand = getChangeShapeCommand(editPart);
- org.eclipse.emf.common.command.Command deleteCommand = DeleteCommand.create(editPart.getEditingDomain(), view);
- org.eclipse.emf.common.command.CompoundCommand compoundCommand = new org.eclipse.emf.common.command.CompoundCommand("change Shape");
- compoundCommand.append(new GMFtoEMFCommandWrapper(createCommand));
-
- //remove old Shape
- compoundCommand.append(deleteCommand);
-
- //Add links
- DeferredSetViewCommand deferredSetCommand= new DeferredSetViewCommand(domain, (SemanticAdapter)createCommand.getCommandResult().getReturnValue(), NotationPackage.eINSTANCE.getView_SourceEdges(), sourceEdge);
- compoundCommand.append(new GMFtoEMFCommandWrapper(deferredSetCommand));
- deferredSetCommand= new DeferredSetViewCommand(domain, (SemanticAdapter)createCommand.getCommandResult().getReturnValue(), NotationPackage.eINSTANCE.getView_TargetEdges(), targetEdge);
- compoundCommand.append(new GMFtoEMFCommandWrapper(deferredSetCommand));
-
- editPart.getEditingDomain().getCommandStack().execute(compoundCommand);
- }
- });
- }
- });
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2012 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.component.custom.handler; + +import java.util.ArrayList; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.emf.edit.command.DeleteCommand; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; +import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.gmf.runtime.notation.Edge; +import org.eclipse.gmf.runtime.notation.NotationPackage; +import org.eclipse.gmf.runtime.notation.View; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper; +import org.eclipse.papyrus.infra.gmfdiag.common.utils.ServiceUtilsForEditPart; +import org.eclipse.papyrus.uml.diagram.common.commands.SemanticAdapter; +import org.eclipse.papyrus.uml.diagram.component.custom.command.DeferredSetViewCommand; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.ISelectionService; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; + +/** + * This class is an abstract class in charge to transform a editpart into another editpart + * + */ +public abstract class ChangeShapeHandler extends AbstractHandler { + + protected TransactionalEditingDomain transactionalEditingDomain = null; + + protected org.eclipse.uml2.uml.Element selectedElement = null; + protected String newType; + + /** + * + * Constructor. + * + */ + public ChangeShapeHandler() { + super(); + } + + protected abstract AbstractTransactionalCommand getChangeShapeCommand(final GraphicalEditPart editPart); + + /** + * + * @return null or the selected editPart + */ + protected GraphicalEditPart getSelectedGraphicalEditpart() { + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + ISelectionService selectionService = activeWorkbenchWindow.getSelectionService(); + ISelection selection = selectionService.getSelection(); + if(selection instanceof IStructuredSelection) { + Object selectedobject = ((IStructuredSelection)selection).getFirstElement(); + if(selectedobject instanceof GraphicalEditPart) { + return (GraphicalEditPart)selectedobject; + } + } + } + return null; + } + + public Object execute(ExecutionEvent event) throws ExecutionException { + final GraphicalEditPart editPart = getSelectedGraphicalEditpart(); + ServiceUtilsForEditPart util = ServiceUtilsForEditPart.getInstance(); + try { + transactionalEditingDomain = util.getTransactionalEditingDomain(editPart); + } catch (Exception e) { + System.err.println("impossible to get the Transactional Editing Domain " + e); + } + try { + editPart.getEditingDomain().runExclusive(new Runnable() { + + public void run() { + Display.getCurrent().asyncExec(new Runnable() { + + public void run() { + //get Links + View view=(View)(editPart.getModel()); + TransactionalEditingDomain domain= editPart.getEditingDomain(); + @SuppressWarnings("unchecked") + ArrayList<Edge>targetEdge= new ArrayList<Edge>(view.getTargetEdges()); + @SuppressWarnings("unchecked") + ArrayList<Edge>sourceEdge= new ArrayList<Edge>(view.getSourceEdges()); + + //create new Shape + AbstractTransactionalCommand createCommand = getChangeShapeCommand(editPart); + org.eclipse.emf.common.command.Command deleteCommand = DeleteCommand.create(editPart.getEditingDomain(), view); + org.eclipse.emf.common.command.CompoundCommand compoundCommand = new org.eclipse.emf.common.command.CompoundCommand("change Shape"); + compoundCommand.append(new GMFtoEMFCommandWrapper(createCommand)); + + //remove old Shape + compoundCommand.append(deleteCommand); + + //Add links + DeferredSetViewCommand deferredSetCommand= new DeferredSetViewCommand(domain, (SemanticAdapter)createCommand.getCommandResult().getReturnValue(), NotationPackage.eINSTANCE.getView_SourceEdges(), sourceEdge); + compoundCommand.append(new GMFtoEMFCommandWrapper(deferredSetCommand)); + deferredSetCommand= new DeferredSetViewCommand(domain, (SemanticAdapter)createCommand.getCommandResult().getReturnValue(), NotationPackage.eINSTANCE.getView_TargetEdges(), targetEdge); + compoundCommand.append(new GMFtoEMFCommandWrapper(deferredSetCommand)); + + editPart.getEditingDomain().getCommandStack().execute(compoundCommand); + } + }); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.menu/src/org/eclipse/papyrus/uml/diagram/menu/toolbar/ZoomToolbar.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.menu/src/org/eclipse/papyrus/uml/diagram/menu/toolbar/ZoomToolbar.java index 11ab305bffa..6ef5b7a1d92 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.menu/src/org/eclipse/papyrus/uml/diagram/menu/toolbar/ZoomToolbar.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.menu/src/org/eclipse/papyrus/uml/diagram/menu/toolbar/ZoomToolbar.java @@ -1,537 +1,539 @@ -/*****************************************************************************
- * 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:
- * Vincent Lorenzo (CEA LIST) vincent.lorenzo@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.uml.diagram.menu.toolbar;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.gef.editparts.ZoomListener;
-import org.eclipse.gef.editparts.ZoomManager;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
-import org.eclipse.gmf.runtime.diagram.ui.internal.util.IUIConstants;
-import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart;
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.papyrus.infra.core.editor.CoreMultiDiagramEditor;
-import org.eclipse.papyrus.infra.core.sasheditor.editor.IPage;
-import org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer;
-import org.eclipse.papyrus.uml.diagram.common.Activator;
-import org.eclipse.papyrus.uml.diagram.menu.actions.ZoomAction;
-import org.eclipse.papyrus.uml.diagram.menu.messages.Messages;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.ui.IPartListener;
-import org.eclipse.ui.IPartService;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * This class provides a Combo box in the toolbar for the Zoom Action
- * This Combo is automatically refresh when the zoom changed
- *
- * A part of this code comes from {@link ZoomContributionItem}
- */
-@SuppressWarnings("restriction")
-public class ZoomToolbar extends ContributionItem implements ZoomListener, Listener, org.eclipse.papyrus.infra.core.sasheditor.editor.IPageChangedListener {
-
- /** the combo box */
- protected Combo combo = null;
-
- /**
- * the part service
- */
- private IPartService partService = null;
-
- /**
- * the listener for the part service
- */
-
- private IPartListener partListener = null;
-
-
- /**
- *
- * Constructor.
- *
- */
- public ZoomToolbar() {
- this(""); //$NON-NLS-1$
- }
-
- /**
- *
- * Constructor.
- *
- * @param id
- */
- public ZoomToolbar(String id) {
- super(id);
- init();
- }
-
- /**
- *
- * @see org.eclipse.jface.action.ContributionItem#dispose()
- *
- */
- @Override
- public void dispose() {
- super.dispose();
- if(this.partService != null) {
- this.partService.removePartListener(this.partListener);
- }
- }
-
- /**
- * Adds a listener on the part Service and refresh the value displayed in the Combo
- *
- */
- protected void init() {
- addPartListener();
- refreshCombo();
- }
-
- /**
- * adds the part listener
- */
- protected void addPartListener() {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow activeWorkbench = workbench.getActiveWorkbenchWindow();
- if(activeWorkbench != null) {
- partService = activeWorkbench.getPartService();
- if(partService != null) {
- this.partListener = new CustomPartListener();
- partService.addPartListener(this.partListener);
- }
- }
- }
-
- /**
- *
- * @see org.eclipse.jface.action.ContributionItem#fill(org.eclipse.swt.widgets.ToolBar, int)
- *
- * @param parent
- * @param index
- */
- @Override
- public void fill(ToolBar parent, int index) {
-
- ToolItem toolItem = new ToolItem(parent, SWT.SEPARATOR);
- Image zoomImage = Activator.getPluginIconImage("org.eclipse.papyrus.uml.diagram.menu", "/icons/zoomplus.gif"); //$NON-NLS-1$ //$NON-NLS-2$
- /*
- * TODO : the image is not set, when we use SWT.SEPARATOR.
- * It's a SWT bug.
- * This image is used in the Perspective Customization
- * That works fine with SWT.PUSH, SWT.PULL_DOWN, ..., but in this case it's the zoom which doesn't work
- */
- toolItem.setImage(zoomImage);
- //this text is used in the perspective customization
- toolItem.setToolTipText(Messages.ZoomToolbar_Zoom);
-
- combo = new Combo(parent, SWT.DROP_DOWN);
- combo.setItems(getZoomLevelsAsText(getZoomManager()));
- combo.setVisibleItemCount(IUIConstants.DEFAULT_DROP_DOWN_SIZE);
- combo.pack();
- toolItem.setWidth(combo.getSize().x);
- toolItem.setControl(combo);
- combo.addListener(SWT.Selection, this);
- combo.addListener(SWT.KeyDown, this);
-
- //the combo is created each time that we change table!
- combo.setEnabled(getDiagramEditPart() != null);
-
- refreshCombo();
- parent.pack();
- }
-
- /**
- *
- * @see org.eclipse.jface.action.ContributionItem#isDynamic()
- *
- * @return
- */
- @Override
- public boolean isDynamic() {
- return true;
- }
-
-
- /**
- * Get the zoom levels as text string array from the zoom manager.
- *
- * @return String array with zoom levels.
- *
- * @see org.eclipse.gef.editparts.ZoomManager#getZoomLevelsAsText()
- */
- public String[] getZoomLevelsAsText(ZoomManager manager) {
- int nNumericZoomLevels = 0;
- if(manager != null) {
- nNumericZoomLevels = manager.getZoomLevels().length;
- }
- String[] allZoomLevels = new String[nNumericZoomLevels + 6];
- allZoomLevels[0] = ZoomAction.ZOOM_IN;
- allZoomLevels[1] = ZoomAction.ZOOM_OUT;
- allZoomLevels[2] = ZoomAction.ZOOM_FIT;
- allZoomLevels[3] = ZoomAction.ZOOM_WIDTH;
- allZoomLevels[4] = ZoomAction.ZOOM_HEIGHT;
- allZoomLevels[5] = ZoomAction.ZOOM_SELECTION;
-
- if(manager != null) {
- String[] numericZoomLevels = manager.getZoomLevelsAsText();
- for(int i = 0; i < manager.getZoomLevels().length; i++) {
- allZoomLevels[i + 6] = numericZoomLevels[i];
- }
- }
- return allZoomLevels;
- }
-
- /**
- * Retrieves the value of the <code>workbenchPart</code> instance
- * variable.
- *
- * @return The value of the <code>workbenchPart</code> instance variable.
- */
- protected IDiagramWorkbenchPart getWorkbenchPart() {
- IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
-
- if(part instanceof IDiagramWorkbenchPart) {
- return (IDiagramWorkbenchPart)part;
- }
- return null;
- }
-
- /**
- * A utility method to return the active part if it implements the <code>IDiagramWorkbenchPart</code> interface
- *
- * @return The current part if it implements <code>IDiagramWorkbenchPart</code>; <code>null</code> otherwise
- */
- protected IDiagramWorkbenchPart getDiagramWorkbenchPart() {
- return getWorkbenchPart() instanceof IDiagramWorkbenchPart ? (IDiagramWorkbenchPart)getWorkbenchPart() : null;
- }
-
- /**
- * A utility method to return the active <code>DiagramEditPart</code> if the current part implements <code>IDiagramWorkbenchPart</code>
- *
- * @return The current diagram if the parts implements <code>IDiagramWorkbenchPart</code>; <code>null</code> otherwise
- */
- protected DiagramEditPart getDiagramEditPart() {
- IDiagramWorkbenchPart editor = getDiagramWorkbenchPart();
- return editor != null ? editor.getDiagramEditPart() : null;
- }
-
-
- /**
- * Returns the current zoom manager
- *
- * @return
- * the current zoom manager
- */
- protected ZoomManager getZoomManager() {
- if(getDiagramWorkbenchPart() != null) {
- return (ZoomManager)getDiagramWorkbenchPart().getAdapter(ZoomManager.class);
- }
- return null;
- }
-
-
- /**
- *
- * @see org.eclipse.gef.editparts.ZoomListener#zoomChanged(double)
- *
- * @param zoom
- */
- public void zoomChanged(double zoom) {
- refreshCombo();
- }
-
- /**
- * refresh the combo status
- */
- public void refreshCombo() {
- if(combo != null && !combo.isDisposed() && combo.isEnabled()) {
- ZoomManager zoomManager = getZoomManager();
- if(getZoomManager() != null) {
- combo.setItems(getZoomLevelsAsText(zoomManager));
- if(zoomManager != null) {
- String zoomText = zoomManager.getZoomAsText();
- int index = combo.indexOf(zoomText);
- if(index != -1) {
- combo.select(index);
- } else {
- combo.setText(zoomText);
- }
- }
- }
- }
- }
-
- /**
- * Sets the zoom level to the zoom string using the zoom manager. First, it
- * checks for the special cases. If it isn't one of the special cases, it
- * uses the zoom manager to do the zooming. There are six special cases,
- * zoom to fit, zoom in, zoom out, zoom to width, zoom to height, and zoom
- * to selected shapes.
- *
- * @param zoomText
- * the zoom string which we will zoom to.
- * @see org.eclipse.gef.editparts.ZoomManager#setZoomAsText(java.lang.String)
- */
- public void setZoomAsText(String zoomText) {
- String parameter = null;
- if(zoomText.equals(ZoomAction.ZOOM_IN)) {
- parameter = ZoomAction.ZOOM_IN_PARAMETER;
- } else if(zoomText.equals(ZoomAction.ZOOM_OUT)) {
- parameter = ZoomAction.ZOOM_OUT_PARAMETER;
- } else if(zoomText.equals(ZoomAction.ZOOM_100)) {
- parameter = ZoomAction.ZOOM_100_PARAMETER;
- } else if(zoomText.equals(ZoomAction.ZOOM_FIT)) {
- parameter = ZoomAction.ZOOM_FIT_PARAMETER;
- } else if(zoomText.equals(ZoomAction.ZOOM_WIDTH)) {
- parameter = ZoomAction.ZOOM_WIDTH_PARAMETER;
- } else if(zoomText.equals(ZoomAction.ZOOM_WIDTH)) {
- parameter = ZoomAction.ZOOM_HEIGHT_PARAMETER;
- } else if(zoomText.equals(ZoomAction.ZOOM_SELECTION)) {
- parameter = ZoomAction.ZOOM_SELECTION_PARAMETER;
- } else {
- parameter = zoomText;
- ZoomManager manager = getZoomManager();
- if(manager != null) {
- manager.setZoomAsText(parameter);//to set a specific value to zoom
- }
- }
-
- ZoomAction action = new ZoomAction(parameter, getSelectedElements());
- if(action.isEnabled()) {
- action.doRun(null);
- } else {
- refreshCombo();
- }
- }
-
-
-
-
- /**
- *
- * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
- *
- * @param event
- */
- public void handleEvent(Event event) {
- if(event.type == SWT.KeyDown && event.character != '\r') {
- return;
- }
- setZoomAsText(combo.getText());
-
- }
-
- /**
- * Iterate over current selection and build a list of the {@link IGraphicalEditPart} contained in
- * the selection.
- *
- * @return the currently selected {@link IGraphicalEditPart}
- */
- protected List<IGraphicalEditPart> getSelectedElements() {
- List<IGraphicalEditPart> editparts = new ArrayList<IGraphicalEditPart>();
-
- ISelection selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
- if(selection instanceof IStructuredSelection) {
-
- IStructuredSelection structuredSelection = (IStructuredSelection)selection;
-
- Iterator<?> it = structuredSelection.iterator();
- while(it.hasNext()) {
- Object object = it.next();
- if(object instanceof IGraphicalEditPart) {
- editparts.add((IGraphicalEditPart)object);
- }
- }
-
- } else if(selection instanceof IGraphicalEditPart) {
- editparts.add((IGraphicalEditPart)selection);
- }
-
- return editparts;
- }
-
-
-
- /**
- *
- * @see org.eclipse.papyrus.sasheditor.editor.IPageChangedListener#pageChanged(org.eclipse.papyrus.sasheditor.editor.IPage)
- *
- * @param newPage
- */
- public void pageChanged(IPage newPage) {
- refreshCombo();
-
- //we update the listeners
- removeListeners(partService.getActivePart());
- addListeners(partService.getActivePart());
- }
-
- /**
- * Removes the listeners on the zoom manager and on the ISashWindowsContainer
- *
- * @param part
- * the part owning the listener to remove
- */
- protected void removeListeners(IWorkbenchPart part) {
- //we remove the zoom listener
- ZoomManager manager = (ZoomManager)part.getAdapter(ZoomManager.class);
- if(manager != null) {
- manager.removeZoomListener(getInstance());
- }
-
- //we remove the page changed listener
- ISashWindowsContainer windowContainer = (ISashWindowsContainer)part.getAdapter(ISashWindowsContainer.class);
- if(windowContainer != null) {
- windowContainer.removePageChangedListener(getInstance());
- }
- refreshStatusCombo(part);
-
- }
-
- /**
- * Adds the listeners on the zoom manager and on the ISashWindowsContainer
- *
- * @param part
- * the part owning the listener to add
- */
- protected void addListeners(IWorkbenchPart part) {
- //we add listener on the zoom manager
- ZoomManager manager = (ZoomManager)part.getAdapter(ZoomManager.class);
- if(manager != null) {
- manager.addZoomListener(getInstance());
- }
-
- //we add listener on the window container
- ISashWindowsContainer windowContainer = (ISashWindowsContainer)part.getAdapter(ISashWindowsContainer.class);
- if(windowContainer != null) {
- windowContainer.addPageChangedListener(getInstance());
- }
- refreshStatusCombo(part);
- }
-
-
-
- /**
- *
- * @param part
- * refresh the state of the combo
- */
- protected void refreshStatusCombo(IWorkbenchPart part) {
- ZoomManager zoomManager = (ZoomManager)part.getAdapter(ZoomManager.class);
-
- if(combo != null && !combo.isDisposed()) {
- if(zoomManager == null) {
- combo.setEnabled(false);
- } else {
- combo.setEnabled(true && getDiagramEditPart() != null);
- refreshCombo();
- }
- }
- }
-
- /**
- * Returns the current instance of {@link ZoomToolbar} (this)
- *
- * @return
- * the current instance of {@link ZoomToolbar} (this)
- */
- protected ZoomToolbar getInstance() {
- return this;
- }
-
- /**
- *
- * This listener is used to listen the part changes
- *
- *
- */
- public class CustomPartListener implements IPartListener {
-
- /**
- *
- * @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart)
- *
- * @param part
- */
- public void partActivated(IWorkbenchPart part) {
- if(part instanceof CoreMultiDiagramEditor) {
- removeListeners(part);
- addListeners(part);
- }
- refreshStatusCombo(part);
- }
-
- /**
- *
- * @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart)
- *
- * @param part
- */
- public void partBroughtToTop(IWorkbenchPart part) {
- refreshStatusCombo(part);
- }
-
- /**
- *
- * @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart)
- *
- * @param part
- */
- public void partClosed(IWorkbenchPart part) {
- refreshStatusCombo(part);
- }
-
- /**
- *
- * @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart)
- *
- * @param part
- */
- public void partDeactivated(IWorkbenchPart part) {
- if(part instanceof CoreMultiDiagramEditor) {
-
- }
- refreshStatusCombo(part);
- }
-
- /**
- *
- * @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart)
- *
- * @param part
- */
- public void partOpened(IWorkbenchPart part) {
- if(part instanceof CoreMultiDiagramEditor) {
- removeListeners(part);
- addListeners(part);
- }
- refreshStatusCombo(part);
- }
-
- }
-}
+/***************************************************************************** + * 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: + * Vincent Lorenzo (CEA LIST) vincent.lorenzo@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.uml.diagram.menu.toolbar; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.gef.editparts.ZoomListener; +import org.eclipse.gef.editparts.ZoomManager; +import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart; +import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; +import org.eclipse.gmf.runtime.diagram.ui.internal.util.IUIConstants; +import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramWorkbenchPart; +import org.eclipse.jface.action.ContributionItem; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.papyrus.infra.core.editor.CoreMultiDiagramEditor; +import org.eclipse.papyrus.infra.core.sasheditor.editor.IPage; +import org.eclipse.papyrus.infra.core.sasheditor.editor.ISashWindowsContainer; +import org.eclipse.papyrus.uml.diagram.common.Activator; +import org.eclipse.papyrus.uml.diagram.menu.actions.ZoomAction; +import org.eclipse.papyrus.uml.diagram.menu.messages.Messages; +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.ToolBar; +import org.eclipse.swt.widgets.ToolItem; +import org.eclipse.ui.IPartListener; +import org.eclipse.ui.IPartService; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPart; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; + +/** + * This class provides a Combo box in the toolbar for the Zoom Action + * This Combo is automatically refresh when the zoom changed + * + * A part of this code comes from {@link ZoomContributionItem} + */ +@SuppressWarnings("restriction") +public class ZoomToolbar extends ContributionItem implements ZoomListener, Listener, org.eclipse.papyrus.infra.core.sasheditor.editor.IPageChangedListener { + + /** the combo box */ + protected Combo combo = null; + + /** + * the part service + */ + private IPartService partService = null; + + /** + * the listener for the part service + */ + + private IPartListener partListener = null; + + + /** + * + * Constructor. + * + */ + public ZoomToolbar() { + this(""); //$NON-NLS-1$ + } + + /** + * + * Constructor. + * + * @param id + */ + public ZoomToolbar(String id) { + super(id); + init(); + } + + /** + * + * @see org.eclipse.jface.action.ContributionItem#dispose() + * + */ + @Override + public void dispose() { + super.dispose(); + if(this.partService != null) { + this.partService.removePartListener(this.partListener); + } + } + + /** + * Adds a listener on the part Service and refresh the value displayed in the Combo + * + */ + protected void init() { + addPartListener(); + refreshCombo(); + } + + /** + * adds the part listener + */ + protected void addPartListener() { + IWorkbench workbench = PlatformUI.getWorkbench(); + IWorkbenchWindow activeWorkbench = workbench.getActiveWorkbenchWindow(); + if(activeWorkbench != null) { + partService = activeWorkbench.getPartService(); + if(partService != null) { + this.partListener = new CustomPartListener(); + partService.addPartListener(this.partListener); + } + } + } + + /** + * + * @see org.eclipse.jface.action.ContributionItem#fill(org.eclipse.swt.widgets.ToolBar, int) + * + * @param parent + * @param index + */ + @Override + public void fill(ToolBar parent, int index) { + + ToolItem toolItem = new ToolItem(parent, SWT.SEPARATOR); + Image zoomImage = Activator.getPluginIconImage("org.eclipse.papyrus.uml.diagram.menu", "/icons/zoomplus.gif"); //$NON-NLS-1$ //$NON-NLS-2$ + /* + * TODO : the image is not set, when we use SWT.SEPARATOR. + * It's a SWT bug. + * This image is used in the Perspective Customization + * That works fine with SWT.PUSH, SWT.PULL_DOWN, ..., but in this case it's the zoom which doesn't work + */ + toolItem.setImage(zoomImage); + //this text is used in the perspective customization + toolItem.setToolTipText(Messages.ZoomToolbar_Zoom); + + combo = new Combo(parent, SWT.DROP_DOWN); + combo.setItems(getZoomLevelsAsText(getZoomManager())); + combo.setVisibleItemCount(IUIConstants.DEFAULT_DROP_DOWN_SIZE); + combo.pack(); + toolItem.setWidth(combo.getSize().x); + toolItem.setControl(combo); + combo.addListener(SWT.Selection, this); + combo.addListener(SWT.KeyDown, this); + + //the combo is created each time that we change table! + combo.setEnabled(getDiagramEditPart() != null); + + refreshCombo(); + parent.pack(); + } + + /** + * + * @see org.eclipse.jface.action.ContributionItem#isDynamic() + * + * @return + */ + @Override + public boolean isDynamic() { + return true; + } + + + /** + * Get the zoom levels as text string array from the zoom manager. + * + * @return String array with zoom levels. + * + * @see org.eclipse.gef.editparts.ZoomManager#getZoomLevelsAsText() + */ + public String[] getZoomLevelsAsText(ZoomManager manager) { + int nNumericZoomLevels = 0; + if(manager != null) { + nNumericZoomLevels = manager.getZoomLevels().length; + } + String[] allZoomLevels = new String[nNumericZoomLevels + 6]; + allZoomLevels[0] = ZoomAction.ZOOM_IN; + allZoomLevels[1] = ZoomAction.ZOOM_OUT; + allZoomLevels[2] = ZoomAction.ZOOM_FIT; + allZoomLevels[3] = ZoomAction.ZOOM_WIDTH; + allZoomLevels[4] = ZoomAction.ZOOM_HEIGHT; + allZoomLevels[5] = ZoomAction.ZOOM_SELECTION; + + if(manager != null) { + String[] numericZoomLevels = manager.getZoomLevelsAsText(); + for(int i = 0; i < manager.getZoomLevels().length; i++) { + allZoomLevels[i + 6] = numericZoomLevels[i]; + } + } + return allZoomLevels; + } + + /** + * Retrieves the value of the <code>workbenchPart</code> instance + * variable. + * + * @return The value of the <code>workbenchPart</code> instance variable. + */ + protected IDiagramWorkbenchPart getWorkbenchPart() { + IWorkbenchPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); + + if(part instanceof IDiagramWorkbenchPart) { + return (IDiagramWorkbenchPart)part; + } + return null; + } + + /** + * A utility method to return the active part if it implements the <code>IDiagramWorkbenchPart</code> interface + * + * @return The current part if it implements <code>IDiagramWorkbenchPart</code>; <code>null</code> otherwise + */ + protected IDiagramWorkbenchPart getDiagramWorkbenchPart() { + return getWorkbenchPart() instanceof IDiagramWorkbenchPart ? (IDiagramWorkbenchPart)getWorkbenchPart() : null; + } + + /** + * A utility method to return the active <code>DiagramEditPart</code> if the current part implements <code>IDiagramWorkbenchPart</code> + * + * @return The current diagram if the parts implements <code>IDiagramWorkbenchPart</code>; <code>null</code> otherwise + */ + protected DiagramEditPart getDiagramEditPart() { + IDiagramWorkbenchPart editor = getDiagramWorkbenchPart(); + return editor != null ? editor.getDiagramEditPart() : null; + } + + + /** + * Returns the current zoom manager + * + * @return + * the current zoom manager + */ + protected ZoomManager getZoomManager() { + if(getDiagramWorkbenchPart() != null) { + return (ZoomManager)getDiagramWorkbenchPart().getAdapter(ZoomManager.class); + } + return null; + } + + + /** + * + * @see org.eclipse.gef.editparts.ZoomListener#zoomChanged(double) + * + * @param zoom + */ + public void zoomChanged(double zoom) { + refreshCombo(); + } + + /** + * refresh the combo status + */ + public void refreshCombo() { + if(combo != null && !combo.isDisposed() && combo.isEnabled()) { + ZoomManager zoomManager = getZoomManager(); + if(getZoomManager() != null) { + combo.setItems(getZoomLevelsAsText(zoomManager)); + if(zoomManager != null) { + String zoomText = zoomManager.getZoomAsText(); + int index = combo.indexOf(zoomText); + if(index != -1) { + combo.select(index); + } else { + combo.setText(zoomText); + } + } + } + } + } + + /** + * Sets the zoom level to the zoom string using the zoom manager. First, it + * checks for the special cases. If it isn't one of the special cases, it + * uses the zoom manager to do the zooming. There are six special cases, + * zoom to fit, zoom in, zoom out, zoom to width, zoom to height, and zoom + * to selected shapes. + * + * @param zoomText + * the zoom string which we will zoom to. + * @see org.eclipse.gef.editparts.ZoomManager#setZoomAsText(java.lang.String) + */ + public void setZoomAsText(String zoomText) { + String parameter = null; + if(zoomText.equals(ZoomAction.ZOOM_IN)) { + parameter = ZoomAction.ZOOM_IN_PARAMETER; + } else if(zoomText.equals(ZoomAction.ZOOM_OUT)) { + parameter = ZoomAction.ZOOM_OUT_PARAMETER; + } else if(zoomText.equals(ZoomAction.ZOOM_100)) { + parameter = ZoomAction.ZOOM_100_PARAMETER; + } else if(zoomText.equals(ZoomAction.ZOOM_FIT)) { + parameter = ZoomAction.ZOOM_FIT_PARAMETER; + } else if(zoomText.equals(ZoomAction.ZOOM_WIDTH)) { + parameter = ZoomAction.ZOOM_WIDTH_PARAMETER; + } else if(zoomText.equals(ZoomAction.ZOOM_WIDTH)) { + parameter = ZoomAction.ZOOM_HEIGHT_PARAMETER; + } else if(zoomText.equals(ZoomAction.ZOOM_SELECTION)) { + parameter = ZoomAction.ZOOM_SELECTION_PARAMETER; + } else { + parameter = zoomText; + ZoomManager manager = getZoomManager(); + if(manager != null) { + manager.setZoomAsText(parameter);//to set a specific value to zoom + } + } + + ZoomAction action = new ZoomAction(parameter, getSelectedElements()); + if(action.isEnabled()) { + action.doRun(null); + } else { + refreshCombo(); + } + } + + + + + /** + * + * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event) + * + * @param event + */ + public void handleEvent(Event event) { + if(event.type == SWT.KeyDown && event.character != '\r') { + return; + } + setZoomAsText(combo.getText()); + + } + + /** + * Iterate over current selection and build a list of the {@link IGraphicalEditPart} contained in + * the selection. + * + * @return the currently selected {@link IGraphicalEditPart} + */ + protected List<IGraphicalEditPart> getSelectedElements() { + List<IGraphicalEditPart> editparts = new ArrayList<IGraphicalEditPart>(); + + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + ISelection selection = activeWorkbenchWindow.getSelectionService().getSelection(); + if(selection instanceof IStructuredSelection) { + + IStructuredSelection structuredSelection = (IStructuredSelection)selection; + + Iterator<?> it = structuredSelection.iterator(); + while(it.hasNext()) { + Object object = it.next(); + if(object instanceof IGraphicalEditPart) { + editparts.add((IGraphicalEditPart)object); + } + } + + } else if(selection instanceof IGraphicalEditPart) { + editparts.add((IGraphicalEditPart)selection); + } + } + return editparts; + } + + + + /** + * + * @see org.eclipse.papyrus.sasheditor.editor.IPageChangedListener#pageChanged(org.eclipse.papyrus.sasheditor.editor.IPage) + * + * @param newPage + */ + public void pageChanged(IPage newPage) { + refreshCombo(); + + //we update the listeners + removeListeners(partService.getActivePart()); + addListeners(partService.getActivePart()); + } + + /** + * Removes the listeners on the zoom manager and on the ISashWindowsContainer + * + * @param part + * the part owning the listener to remove + */ + protected void removeListeners(IWorkbenchPart part) { + //we remove the zoom listener + ZoomManager manager = (ZoomManager)part.getAdapter(ZoomManager.class); + if(manager != null) { + manager.removeZoomListener(getInstance()); + } + + //we remove the page changed listener + ISashWindowsContainer windowContainer = (ISashWindowsContainer)part.getAdapter(ISashWindowsContainer.class); + if(windowContainer != null) { + windowContainer.removePageChangedListener(getInstance()); + } + refreshStatusCombo(part); + + } + + /** + * Adds the listeners on the zoom manager and on the ISashWindowsContainer + * + * @param part + * the part owning the listener to add + */ + protected void addListeners(IWorkbenchPart part) { + //we add listener on the zoom manager + ZoomManager manager = (ZoomManager)part.getAdapter(ZoomManager.class); + if(manager != null) { + manager.addZoomListener(getInstance()); + } + + //we add listener on the window container + ISashWindowsContainer windowContainer = (ISashWindowsContainer)part.getAdapter(ISashWindowsContainer.class); + if(windowContainer != null) { + windowContainer.addPageChangedListener(getInstance()); + } + refreshStatusCombo(part); + } + + + + /** + * + * @param part + * refresh the state of the combo + */ + protected void refreshStatusCombo(IWorkbenchPart part) { + ZoomManager zoomManager = (ZoomManager)part.getAdapter(ZoomManager.class); + + if(combo != null && !combo.isDisposed()) { + if(zoomManager == null) { + combo.setEnabled(false); + } else { + combo.setEnabled(true && getDiagramEditPart() != null); + refreshCombo(); + } + } + } + + /** + * Returns the current instance of {@link ZoomToolbar} (this) + * + * @return + * the current instance of {@link ZoomToolbar} (this) + */ + protected ZoomToolbar getInstance() { + return this; + } + + /** + * + * This listener is used to listen the part changes + * + * + */ + public class CustomPartListener implements IPartListener { + + /** + * + * @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart) + * + * @param part + */ + public void partActivated(IWorkbenchPart part) { + if(part instanceof CoreMultiDiagramEditor) { + removeListeners(part); + addListeners(part); + } + refreshStatusCombo(part); + } + + /** + * + * @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart) + * + * @param part + */ + public void partBroughtToTop(IWorkbenchPart part) { + refreshStatusCombo(part); + } + + /** + * + * @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart) + * + * @param part + */ + public void partClosed(IWorkbenchPart part) { + refreshStatusCombo(part); + } + + /** + * + * @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart) + * + * @param part + */ + public void partDeactivated(IWorkbenchPart part) { + if(part instanceof CoreMultiDiagramEditor) { + + } + refreshStatusCombo(part); + } + + /** + * + * @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart) + * + * @param part + */ + public void partOpened(IWorkbenchPart part) { + if(part instanceof CoreMultiDiagramEditor) { + removeListeners(part); + addListeners(part); + } + refreshStatusCombo(part); + } + + } +} diff --git a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.usecase/custom-src/org/eclipse/papyrus/uml/diagram/usecase/handler/ChangeShapeHandler.java b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.usecase/custom-src/org/eclipse/papyrus/uml/diagram/usecase/handler/ChangeShapeHandler.java index be5c8f8e0da..853c0ed138a 100644 --- a/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.usecase/custom-src/org/eclipse/papyrus/uml/diagram/usecase/handler/ChangeShapeHandler.java +++ b/plugins/uml/diagram/org.eclipse.papyrus.uml.diagram.usecase/custom-src/org/eclipse/papyrus/uml/diagram/usecase/handler/ChangeShapeHandler.java @@ -1,98 +1,102 @@ -/*****************************************************************************
- * Copyright (c) 2012 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.usecase.handler;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-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.emf.commands.core.command.AbstractTransactionalCommand;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper;
-import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper;
-import org.eclipse.papyrus.infra.gmfdiag.common.utils.ServiceUtilsForEditPart;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISelectionService;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * This class is an abstract class in charge to transform a editpart into another editpart
- *
- */
-public abstract class ChangeShapeHandler extends AbstractHandler {
-
- protected TransactionalEditingDomain transactionalEditingDomain = null;
-
- protected org.eclipse.uml2.uml.Element selectedElement = null;
-
- public ChangeShapeHandler() {
- super();
- }
-
- protected abstract AbstractTransactionalCommand getChangeShapeCommand(final GraphicalEditPart editPart);
-
- /**
- *
- * @return null or the selected editPart
- */
- protected GraphicalEditPart getSelectedGraphicalEditpart() {
- ISelectionService selectionService = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService();
- ISelection selection = selectionService.getSelection();
- if(selection instanceof IStructuredSelection) {
- Object selectedobject = ((IStructuredSelection)selection).getFirstElement();
- if(selectedobject instanceof GraphicalEditPart) {
- return (GraphicalEditPart)selectedobject;
- }
- }
- return null;
- }
-
- public Object execute(ExecutionEvent event) throws ExecutionException {
- final GraphicalEditPart editPart = getSelectedGraphicalEditpart();
- ServiceUtilsForEditPart util = ServiceUtilsForEditPart.getInstance();
- try {
- transactionalEditingDomain = util.getTransactionalEditingDomain(editPart);
- } catch (Exception e) {
- System.err.println("impossible to get the Transactional Editing Domain " + e);
- }
- try {
- editPart.getEditingDomain().runExclusive(new Runnable() {
-
- public void run() {
- Display.getCurrent().asyncExec(new Runnable() {
-
- public void run() {
- AbstractTransactionalCommand command = getChangeShapeCommand(editPart);
- Request deleteViewRequest = new GroupRequest(RequestConstants.REQ_DELETE);
- Command deleteCommand = editPart.getCommand(deleteViewRequest);
- org.eclipse.emf.common.command.CompoundCommand compoundCommand = new org.eclipse.emf.common.command.CompoundCommand("change Shape");
- compoundCommand.append(new GMFtoEMFCommandWrapper(command));
- compoundCommand.append(new GEFtoEMFCommandWrapper(deleteCommand));
- editPart.getEditingDomain().getCommandStack().execute(compoundCommand);
- }
- });
- }
- });
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return null;
- }
-}
+/***************************************************************************** + * Copyright (c) 2012 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.usecase.handler; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +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.emf.commands.core.command.AbstractTransactionalCommand; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.papyrus.commands.wrappers.GEFtoEMFCommandWrapper; +import org.eclipse.papyrus.commands.wrappers.GMFtoEMFCommandWrapper; +import org.eclipse.papyrus.infra.gmfdiag.common.utils.ServiceUtilsForEditPart; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.ISelectionService; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; + +/** + * This class is an abstract class in charge to transform a editpart into another editpart + * + */ +public abstract class ChangeShapeHandler extends AbstractHandler { + + protected TransactionalEditingDomain transactionalEditingDomain = null; + + protected org.eclipse.uml2.uml.Element selectedElement = null; + + public ChangeShapeHandler() { + super(); + } + + protected abstract AbstractTransactionalCommand getChangeShapeCommand(final GraphicalEditPart editPart); + + /** + * + * @return null or the selected editPart + */ + protected GraphicalEditPart getSelectedGraphicalEditpart() { + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + ISelectionService selectionService = activeWorkbenchWindow.getSelectionService(); + ISelection selection = selectionService.getSelection(); + if(selection instanceof IStructuredSelection) { + Object selectedobject = ((IStructuredSelection)selection).getFirstElement(); + if(selectedobject instanceof GraphicalEditPart) { + return (GraphicalEditPart)selectedobject; + } + } + } + return null; + } + + public Object execute(ExecutionEvent event) throws ExecutionException { + final GraphicalEditPart editPart = getSelectedGraphicalEditpart(); + ServiceUtilsForEditPart util = ServiceUtilsForEditPart.getInstance(); + try { + transactionalEditingDomain = util.getTransactionalEditingDomain(editPart); + } catch (Exception e) { + System.err.println("impossible to get the Transactional Editing Domain " + e); + } + try { + editPart.getEditingDomain().runExclusive(new Runnable() { + + public void run() { + Display.getCurrent().asyncExec(new Runnable() { + + public void run() { + AbstractTransactionalCommand command = getChangeShapeCommand(editPart); + Request deleteViewRequest = new GroupRequest(RequestConstants.REQ_DELETE); + Command deleteCommand = editPart.getCommand(deleteViewRequest); + org.eclipse.emf.common.command.CompoundCommand compoundCommand = new org.eclipse.emf.common.command.CompoundCommand("change Shape"); //$NON-NLS-1$ + compoundCommand.append(new GMFtoEMFCommandWrapper(command)); + compoundCommand.append(new GEFtoEMFCommandWrapper(deleteCommand)); + editPart.getEditingDomain().getCommandStack().execute(compoundCommand); + } + }); + } + }); + } catch (InterruptedException e) { + e.printStackTrace(); + } + return null; + } +} diff --git a/plugins/uml/org.eclipse.papyrus.uml.commands/src/org/eclipse/papyrus/uml/commands/handler/AbstractEMFCommandHandler.java b/plugins/uml/org.eclipse.papyrus.uml.commands/src/org/eclipse/papyrus/uml/commands/handler/AbstractEMFCommandHandler.java index 8139cd23f09..dd885fdd9f2 100644 --- a/plugins/uml/org.eclipse.papyrus.uml.commands/src/org/eclipse/papyrus/uml/commands/handler/AbstractEMFCommandHandler.java +++ b/plugins/uml/org.eclipse.papyrus.uml.commands/src/org/eclipse/papyrus/uml/commands/handler/AbstractEMFCommandHandler.java @@ -1,225 +1,233 @@ -/*****************************************************************************
- * 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.commands.handler;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.emf.common.command.Command;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.transaction.RunnableWithResult;
-import org.eclipse.emf.transaction.TransactionalEditingDomain;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.papyrus.infra.core.services.ServiceException;
-import org.eclipse.papyrus.infra.core.services.ServicesRegistry;
-import org.eclipse.papyrus.infra.core.utils.ServiceUtils;
-import org.eclipse.papyrus.infra.emf.utils.BusinessModelResolver;
-import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
-import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForEObject;
-import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForHandlers;
-import org.eclipse.papyrus.uml.commands.Activator;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * <pre>
- *
- * This abstract command handler manages:
- * - current selection in order to build a list of the selected {@link EObject}
- * - execute the command (returned by children) in Papyrus {@link TransactionalEditingDomain}
- * - calculate the command enablement and visibility regarding the command executability
- * (the command is now shown in menu if not executable).
- *
- * </pre>
- */
+/***************************************************************************** + * 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.commands.handler; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.emf.common.command.Command; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.transaction.RunnableWithResult; +import org.eclipse.emf.transaction.TransactionalEditingDomain; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.papyrus.infra.core.services.ServiceException; +import org.eclipse.papyrus.infra.core.services.ServicesRegistry; +import org.eclipse.papyrus.infra.core.utils.ServiceUtils; +import org.eclipse.papyrus.infra.emf.utils.BusinessModelResolver; +import org.eclipse.papyrus.infra.emf.utils.EMFHelper; +import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForEObject; +import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForHandlers; +import org.eclipse.papyrus.uml.commands.Activator; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; + +/** + * <pre> + * + * This abstract command handler manages: + * - current selection in order to build a list of the selected {@link EObject} + * - execute the command (returned by children) in Papyrus {@link TransactionalEditingDomain} + * - calculate the command enablement and visibility regarding the command executability + * (the command is now shown in menu if not executable). + * + * </pre> + */ @Deprecated // use org.eclipse.papyrus.infra.gmfdiag.modelexplorer.handlers.AbstractEMFCommandHandler -public abstract class AbstractEMFCommandHandler extends AbstractHandler {
-
- /**
- * Returns the current editing domain
- *
- * @return
- * the current editing domain
- */
- protected TransactionalEditingDomain getEditingDomain() {
- TransactionalEditingDomain editingDomain = null;
- try {
- editingDomain = org.eclipse.papyrus.infra.core.utils.ServiceUtilsForActionHandlers.getInstance().getTransactionalEditingDomain();
- } catch (ServiceException e) {
- //we are closing the editor, so the model explorer has nothing to display
- // e.printStackTrace();
- }
- return editingDomain;
- }
-
- /**
- * <pre>
- *
- * Returns the command to execute (to be implemented
- * in children implementing this class)
- *
- * @return the command to execute
- *
- * </pre>
- */
- protected abstract Command getCommand(ServicesRegistry registry);
-
- /**
- * <pre>
- * Get the selected element, the first selected element if several are selected or null
- * if no selection or the selection is not an {@link EObject}.
- *
- * @return selected {@link EObject} or null
- * </pre>
- *
- */
- protected EObject getSelectedElement() {
- EObject eObject = null;
- Object selection = null;
-
- // Get current selection
- selection = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
-
- // Get first element if the selection is an IStructuredSelection
- if(selection instanceof IStructuredSelection) {
- IStructuredSelection structuredSelection = (IStructuredSelection)selection;
- selection = structuredSelection.getFirstElement();
- }
-
- // Treat non-null selected object (try to adapt and return EObject)
- if(selection != null) {
-
- eObject=EMFHelper.getEObject(selection);
- }
- return eObject;
- }
-
- /**
- * <pre>
- * Parse current selection and extract the list of {@link EObject} from
- * this selection.
- *
- * This also tries to adapt selected element into {@link EObject}
- * (for example to get the {@link EObject} from a selection in the ModelExplorer).
- *
- * @return a list of currently selected {@link EObject}
- * </pre>
- *
- */
- protected List<EObject> getSelectedElements() {
-
- List<EObject> selectedEObjects = new ArrayList<EObject>();
-
- //FIXME: This method should always be called from the UI Thread.
- //TODO: Fix the tests and remove the syncExec call
- // Parse current selection
- RunnableWithResult<ISelection> runnable;
- Display.getDefault().syncExec(runnable = new RunnableWithResult.Impl<ISelection>() {
-
- public void run() {
- setResult(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection());
- }
- });
-
- ISelection selection = runnable.getResult();
- if(selection instanceof IStructuredSelection) {
- IStructuredSelection structuredSelection = (IStructuredSelection)selection;
- for(Object current : structuredSelection.toArray()) {
- // Adapt current selection to EObject
- EObject eobject=EMFHelper.getEObject(current);
- if(eobject != null) {
- selectedEObjects.add(eobject);
- }
-
- }
- } else { // Not a IStructuredSelection
- if(selection != null) {
- // Adapt current selection to EObject
- EObject eobject=EMFHelper.getEObject(selection);
- if(eobject != null) {
- selectedEObjects.add(eobject);
- }
- }
- }
-
- return selectedEObjects;
- }
-
- /**
- *
- * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
- *
- * @param event
- * @return null
- * @throws ExecutionException
- */
- public Object execute(ExecutionEvent event) throws ExecutionException {
-
- try {
- ServicesRegistry registry = ServiceUtilsForHandlers.getInstance().getServiceRegistry(event);
- Command emfCommand = getCommand(registry);
-
- ServiceUtils.getInstance().getTransactionalEditingDomain(registry).getCommandStack().execute(emfCommand);
-
- return emfCommand.getResult();
-
- } catch (ServiceException e) {
-
- Activator.log.error("Unexpected error while executing command.", e);
-
- }
-
- return null;
- }
-
- /**
- *
- * @see org.eclipse.core.commands.AbstractHandler#isEnabled()
- *
- * @return true (enabled) when the command can be executed.
- */
- @Override
- public boolean isEnabled() {
- return getCommand(getServicesRegistryFromSelection()).canExecute();
- }
-
- protected ServicesRegistry getServicesRegistryFromSelection() {
- for(EObject selectedElement : getSelectedElements()) {
- try {
- ServicesRegistry registry = ServiceUtilsForEObject.getInstance().getServiceRegistry(selectedElement);
- if(registry != null) {
- return registry;
- }
- } catch (ServiceException ex) {
- //Ignore it and keep searching for a ServicesRegistry
- }
- }
-
- return null;
- }
-
- /**
- *
- * @return true (visible) when the command can be executed.
- */
- public boolean isVisible() {
- return getCommand(getServicesRegistryFromSelection()).canExecute();
- }
-}
+public abstract class AbstractEMFCommandHandler extends AbstractHandler { + + /** + * Returns the current editing domain + * + * @return + * the current editing domain + */ + protected TransactionalEditingDomain getEditingDomain() { + TransactionalEditingDomain editingDomain = null; + try { + editingDomain = org.eclipse.papyrus.infra.core.utils.ServiceUtilsForActionHandlers.getInstance().getTransactionalEditingDomain(); + } catch (ServiceException e) { + //we are closing the editor, so the model explorer has nothing to display + // e.printStackTrace(); + } + return editingDomain; + } + + /** + * <pre> + * + * Returns the command to execute (to be implemented + * in children implementing this class) + * + * @return the command to execute + * + * </pre> + */ + protected abstract Command getCommand(ServicesRegistry registry); + + /** + * <pre> + * Get the selected element, the first selected element if several are selected or null + * if no selection or the selection is not an {@link EObject}. + * + * @return selected {@link EObject} or null + * </pre> + * + */ + protected EObject getSelectedElement() { + EObject eObject = null; + Object selection = null; + + // Get current selection + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + selection = activeWorkbenchWindow.getSelectionService().getSelection(); + + // Get first element if the selection is an IStructuredSelection + if(selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection)selection; + selection = structuredSelection.getFirstElement(); + } + + // Treat non-null selected object (try to adapt and return EObject) + if(selection != null) { + + eObject=EMFHelper.getEObject(selection); + } + } + + return eObject; + } + + /** + * <pre> + * Parse current selection and extract the list of {@link EObject} from + * this selection. + * + * This also tries to adapt selected element into {@link EObject} + * (for example to get the {@link EObject} from a selection in the ModelExplorer). + * + * @return a list of currently selected {@link EObject} + * </pre> + * + */ + protected List<EObject> getSelectedElements() { + + List<EObject> selectedEObjects = new ArrayList<EObject>(); + + //FIXME: This method should always be called from the UI Thread. + //TODO: Fix the tests and remove the syncExec call + // Parse current selection + RunnableWithResult<ISelection> runnable; + Display.getDefault().syncExec(runnable = new RunnableWithResult.Impl<ISelection>() { + + public void run() { + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + setResult(activeWorkbenchWindow.getSelectionService().getSelection()); + } + } + }); + + ISelection selection = runnable.getResult(); + if(selection instanceof IStructuredSelection) { + IStructuredSelection structuredSelection = (IStructuredSelection)selection; + for(Object current : structuredSelection.toArray()) { + // Adapt current selection to EObject + EObject eobject=EMFHelper.getEObject(current); + if(eobject != null) { + selectedEObjects.add(eobject); + } + + } + } else { // Not a IStructuredSelection + if(selection != null) { + // Adapt current selection to EObject + EObject eobject=EMFHelper.getEObject(selection); + if(eobject != null) { + selectedEObjects.add(eobject); + } + } + } + + return selectedEObjects; + } + + /** + * + * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent) + * + * @param event + * @return null + * @throws ExecutionException + */ + public Object execute(ExecutionEvent event) throws ExecutionException { + + try { + ServicesRegistry registry = ServiceUtilsForHandlers.getInstance().getServiceRegistry(event); + Command emfCommand = getCommand(registry); + + ServiceUtils.getInstance().getTransactionalEditingDomain(registry).getCommandStack().execute(emfCommand); + + return emfCommand.getResult(); + + } catch (ServiceException e) { + + Activator.log.error("Unexpected error while executing command.", e); + + } + + return null; + } + + /** + * + * @see org.eclipse.core.commands.AbstractHandler#isEnabled() + * + * @return true (enabled) when the command can be executed. + */ + @Override + public boolean isEnabled() { + return getCommand(getServicesRegistryFromSelection()).canExecute(); + } + + protected ServicesRegistry getServicesRegistryFromSelection() { + for(EObject selectedElement : getSelectedElements()) { + try { + ServicesRegistry registry = ServiceUtilsForEObject.getInstance().getServiceRegistry(selectedElement); + if(registry != null) { + return registry; + } + } catch (ServiceException ex) { + //Ignore it and keep searching for a ServicesRegistry + } + } + + return null; + } + + /** + * + * @return true (visible) when the command can be executed. + */ + public boolean isVisible() { + return getCommand(getServicesRegistryFromSelection()).canExecute(); + } +} diff --git a/tests/junit/plugins/junit/org.eclipse.papyrus.junit.utils/src/org/eclipse/papyrus/junit/utils/ModelExplorerUtils.java b/tests/junit/plugins/junit/org.eclipse.papyrus.junit.utils/src/org/eclipse/papyrus/junit/utils/ModelExplorerUtils.java index ad3541dd4e7..d9d8bf6a5f7 100644 --- a/tests/junit/plugins/junit/org.eclipse.papyrus.junit.utils/src/org/eclipse/papyrus/junit/utils/ModelExplorerUtils.java +++ b/tests/junit/plugins/junit/org.eclipse.papyrus.junit.utils/src/org/eclipse/papyrus/junit/utils/ModelExplorerUtils.java @@ -1,211 +1,214 @@ -/*****************************************************************************
- * Copyright (c) 2012, 2014 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:
- * Vincent Lorenzo (CEA LIST) Vincent.Lorenzo@cea.fr - Initial API and implementation
- * Christian W. Damus (CEA) - bug 386118
- *
- *****************************************************************************/
-package org.eclipse.papyrus.junit.utils;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.core.commands.IHandler;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.emf.ecore.EObject;
-import org.eclipse.emf.transaction.RunnableWithResult;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.papyrus.infra.core.editor.IMultiDiagramEditor;
-import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
-import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPage;
-import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPageBookView;
-import org.eclipse.papyrus.views.modelexplorer.ModelExplorerView;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.part.IPage;
-import org.junit.Assert;
-
-/**
- * Useful methods for the ModelExplorer view
- */
-public class ModelExplorerUtils {
-
- /**
- * the ID of the ModelExplorerView
- */
- private static final String ModelExplorerViewId = "org.eclipse.papyrus.views.modelexplorer.modelexplorer"; //$NON-NLS-1$
-
- private ModelExplorerUtils() {
- // to prevent instanciation
- }
-
- /**
- *
- * @return
- * the opened modelexplorer. Warning, it should be better that Papyrus was opened yet
- * @throws PartInitException
- */
- public static ModelExplorerView openModelExplorerView() throws PartInitException {
- IViewPart modelexplorer = null;
- modelexplorer = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ModelExplorerViewId);
- final ModelExplorerPageBookView view = (ModelExplorerPageBookView)modelexplorer;
- final IPage currentPage = view.getCurrentPage();
- final ModelExplorerPage page = (ModelExplorerPage)currentPage;
- final IViewPart viewer = page.getViewer();
- Assert.assertNotNull(viewer);
- viewer.setFocus();
- return (ModelExplorerView)viewer;
- }
-
- /**
- *
- * @param view
- * the modelexplorer to manipulate
- * @param elements
- * the elements to select
- */
- public static void setSelectionInTheModelexplorer(final ModelExplorerView view, List<?> elements) {
- view.revealSemanticElement(elements);
- final List<?> currentSelection = getCurrentSelectionInTheModelExplorer();
- Assert.assertTrue("The current selection is not the wanted selection", elements.containsAll(currentSelection));
- Assert.assertTrue("The current selection is not the wanted selection", currentSelection.containsAll(elements));
- }
-
- /**
- *
- * @return
- * the object selected in the ModelExplorer
- * //TODO : should be moved in the ModelExplorer
- */
- public static List<?> getCurrentSelectionInTheModelExplorer() {
- final IStructuredSelection currentSelection = (IStructuredSelection)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(ModelExplorerViewId);
- final List<Object> selection = new ArrayList<Object>();
- final Iterator<?> iter = currentSelection.iterator();
- while(iter.hasNext()) {
- final Object current = iter.next();
- EObject eObject = EMFHelper.getEObject(current);
- if(eObject != null) {
- selection.add(eObject);
- } else {
- selection.add(current);
- }
-
- }
- return selection;
- }
-
- /**
- *
- * @param view
- * the ModelExplorerView
- * @return
- * the root of the Model
- * //TODO : should be moved in the ModelExplorer
- */
- public static final EObject getRootInModelExplorer(final ModelExplorerView view) {
- view.getCommonViewer().expandToLevel(2);
-
- // store the root of the model
- final Object[] visibleElement = view.getCommonViewer().getVisibleExpandedElements();
- EObject modelRoot = null;
- if(visibleElement.length > 0) {
- modelRoot = EMFHelper.getEObject(visibleElement[0]);
- }
- Assert.assertNotNull(modelRoot);
- while(modelRoot.eContainer() != null) {
- modelRoot = modelRoot.eContainer();
- }
- return modelRoot;
- }
-
- /**
- *
- * @param actionContext
- * the creation context
- * @param wantedResult
- * the wanted result
- */
- public static final void testHandlerStatusInModelExplorer(final ModelExplorerView view, final String commandToTest, final EObject actionContext, boolean wantedResult) {
- setSelectionInTheModelexplorer(view, Collections.singletonList(actionContext));
- ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class);
- Command cmd = commandService.getCommand(commandToTest);
- IHandler handler = cmd.getHandler();
- if(handler instanceof AbstractHandler) {
- ((AbstractHandler)handler).setEnabled(commandToTest);
- }
- boolean res = handler.isEnabled();
- Assert.assertEquals(wantedResult, res);
- }
-
- /**
- * Execute an editor command creation and returns the current papyrus nested editor (you must verify that it is the correct editor to be sure of
- * the command execution)
- *
- * @param currentPapyrusEditor
- * the current PapyrusEditor
- * @param view
- * the model explorer view
- * @param commandToExecute
- * the command to execute
- * @param actionContext
- * the context used for the commadn (the selected elements)
- * @param bundelID
- * the bundle id
- *
- * @return
- * the current papyrus nested editor (you must verify that it is the correct editor to be sure of
- * the command execution)
- */
- public static final Object executeCreateNestedEditorHandlerInModelExplorer(final IMultiDiagramEditor currentPapyrusEditor, final ModelExplorerView view, final String commandToExecute, final EObject actionContext, final String bundelID) {
- setSelectionInTheModelexplorer(view, Collections.singletonList(actionContext));
- ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class);
- final Command cmd = commandService.getCommand(commandToExecute);
- final IHandler handler = cmd.getHandler();
- if(handler instanceof AbstractHandler) {
- ((AbstractHandler)handler).setEnabled(commandToExecute);
- }
- final RunnableWithResult<?> runnableWithResult = new RunnableWithResult.Impl<Object>() {
-
- public void run() {
- try {
- handler.execute(new ExecutionEvent(cmd, Collections.emptyMap(), null, null));
- } catch (ExecutionException e) {
- setStatus(new Status(IStatus.ERROR, bundelID, e.getMessage()));
- }
-
- IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- IEditorPart activeEditor = activePage.getActiveEditor();
- if(currentPapyrusEditor != activeEditor) {
- setStatus(new Status(IStatus.ERROR, bundelID, "The current active editor is not the wanted Papyrus Editor"));
- }
-
- setResult(currentPapyrusEditor.getActiveEditor());
- setStatus(Status.OK_STATUS);
- }
- };
- Display.getDefault().syncExec(runnableWithResult);
- Assert.assertEquals(runnableWithResult.getStatus().getMessage(), IStatus.OK, runnableWithResult.getStatus().getSeverity());
- Object result = runnableWithResult.getResult();
- Assert.assertNotNull(result);
- return result;
- }
-}
+/***************************************************************************** + * Copyright (c) 2012, 2014 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: + * Vincent Lorenzo (CEA LIST) Vincent.Lorenzo@cea.fr - Initial API and implementation + * Christian W. Damus (CEA) - bug 386118 + * + *****************************************************************************/ +package org.eclipse.papyrus.junit.utils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.Command; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.core.commands.IHandler; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.transaction.RunnableWithResult; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.papyrus.infra.core.editor.IMultiDiagramEditor; +import org.eclipse.papyrus.infra.emf.utils.EMFHelper; +import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPage; +import org.eclipse.papyrus.views.modelexplorer.ModelExplorerPageBookView; +import org.eclipse.papyrus.views.modelexplorer.ModelExplorerView; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.commands.ICommandService; +import org.eclipse.ui.part.IPage; +import org.junit.Assert; + +/** + * Useful methods for the ModelExplorer view + */ +public class ModelExplorerUtils { + + /** + * the ID of the ModelExplorerView + */ + private static final String ModelExplorerViewId = "org.eclipse.papyrus.views.modelexplorer.modelexplorer"; //$NON-NLS-1$ + + private ModelExplorerUtils() { + // to prevent instanciation + } + + /** + * + * @return + * the opened modelexplorer. Warning, it should be better that Papyrus was opened yet + * @throws PartInitException + */ + public static ModelExplorerView openModelExplorerView() throws PartInitException { + IViewPart modelexplorer = null; + modelexplorer = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ModelExplorerViewId); + final ModelExplorerPageBookView view = (ModelExplorerPageBookView)modelexplorer; + final IPage currentPage = view.getCurrentPage(); + final ModelExplorerPage page = (ModelExplorerPage)currentPage; + final IViewPart viewer = page.getViewer(); + Assert.assertNotNull(viewer); + viewer.setFocus(); + return (ModelExplorerView)viewer; + } + + /** + * + * @param view + * the modelexplorer to manipulate + * @param elements + * the elements to select + */ + public static void setSelectionInTheModelexplorer(final ModelExplorerView view, List<?> elements) { + view.revealSemanticElement(elements); + final List<?> currentSelection = getCurrentSelectionInTheModelExplorer(); + Assert.assertTrue("The current selection is not the wanted selection", elements.containsAll(currentSelection)); //$NON-NLS-1$ + Assert.assertTrue("The current selection is not the wanted selection", currentSelection.containsAll(elements)); //$NON-NLS-1$ + } + + /** + * + * @return + * the object selected in the ModelExplorer + * //TODO : should be moved in the ModelExplorer + */ + public static List<?> getCurrentSelectionInTheModelExplorer() { + final List<Object> selection = new ArrayList<Object>(); + IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + if (activeWorkbenchWindow!=null){ + final IStructuredSelection currentSelection = (IStructuredSelection)activeWorkbenchWindow.getSelectionService().getSelection(ModelExplorerViewId); + final Iterator<?> iter = currentSelection.iterator(); + while(iter.hasNext()) { + final Object current = iter.next(); + EObject eObject = EMFHelper.getEObject(current); + if(eObject != null) { + selection.add(eObject); + } else { + selection.add(current); + } + } + } + return selection; + } + + /** + * + * @param view + * the ModelExplorerView + * @return + * the root of the Model + * //TODO : should be moved in the ModelExplorer + */ + public static final EObject getRootInModelExplorer(final ModelExplorerView view) { + view.getCommonViewer().expandToLevel(2); + + // store the root of the model + final Object[] visibleElement = view.getCommonViewer().getVisibleExpandedElements(); + EObject modelRoot = null; + if(visibleElement.length > 0) { + modelRoot = EMFHelper.getEObject(visibleElement[0]); + } + Assert.assertNotNull(modelRoot); + while(modelRoot.eContainer() != null) { + modelRoot = modelRoot.eContainer(); + } + return modelRoot; + } + + /** + * + * @param actionContext + * the creation context + * @param wantedResult + * the wanted result + */ + public static final void testHandlerStatusInModelExplorer(final ModelExplorerView view, final String commandToTest, final EObject actionContext, boolean wantedResult) { + setSelectionInTheModelexplorer(view, Collections.singletonList(actionContext)); + ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class); + Command cmd = commandService.getCommand(commandToTest); + IHandler handler = cmd.getHandler(); + if(handler instanceof AbstractHandler) { + ((AbstractHandler)handler).setEnabled(commandToTest); + } + boolean res = handler.isEnabled(); + Assert.assertEquals(wantedResult, res); + } + + /** + * Execute an editor command creation and returns the current papyrus nested editor (you must verify that it is the correct editor to be sure of + * the command execution) + * + * @param currentPapyrusEditor + * the current PapyrusEditor + * @param view + * the model explorer view + * @param commandToExecute + * the command to execute + * @param actionContext + * the context used for the commadn (the selected elements) + * @param bundelID + * the bundle id + * + * @return + * the current papyrus nested editor (you must verify that it is the correct editor to be sure of + * the command execution) + */ + public static final Object executeCreateNestedEditorHandlerInModelExplorer(final IMultiDiagramEditor currentPapyrusEditor, final ModelExplorerView view, final String commandToExecute, final EObject actionContext, final String bundelID) { + setSelectionInTheModelexplorer(view, Collections.singletonList(actionContext)); + ICommandService commandService = (ICommandService)PlatformUI.getWorkbench().getService(ICommandService.class); + final Command cmd = commandService.getCommand(commandToExecute); + final IHandler handler = cmd.getHandler(); + if(handler instanceof AbstractHandler) { + ((AbstractHandler)handler).setEnabled(commandToExecute); + } + final RunnableWithResult<?> runnableWithResult = new RunnableWithResult.Impl<Object>() { + + public void run() { + try { + handler.execute(new ExecutionEvent(cmd, Collections.emptyMap(), null, null)); + } catch (ExecutionException e) { + setStatus(new Status(IStatus.ERROR, bundelID, e.getMessage())); + } + + IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); + IEditorPart activeEditor = activePage.getActiveEditor(); + if(currentPapyrusEditor != activeEditor) { + setStatus(new Status(IStatus.ERROR, bundelID, "The current active editor is not the wanted Papyrus Editor")); //$NON-NLS-1$ + } + + setResult(currentPapyrusEditor.getActiveEditor()); + setStatus(Status.OK_STATUS); + } + }; + Display.getDefault().syncExec(runnableWithResult); + Assert.assertEquals(runnableWithResult.getStatus().getMessage(), IStatus.OK, runnableWithResult.getStatus().getSeverity()); + Object result = runnableWithResult.getResult(); + Assert.assertNotNull(result); + return result; + } +} diff --git a/tests/junit/plugins/junit/org.eclipse.papyrus.junit.utils/src/org/eclipse/papyrus/junit/utils/PackageExplorerUtils.java b/tests/junit/plugins/junit/org.eclipse.papyrus.junit.utils/src/org/eclipse/papyrus/junit/utils/PackageExplorerUtils.java index d6ef585d17e..cb3e3f1b8c6 100644 --- a/tests/junit/plugins/junit/org.eclipse.papyrus.junit.utils/src/org/eclipse/papyrus/junit/utils/PackageExplorerUtils.java +++ b/tests/junit/plugins/junit/org.eclipse.papyrus.junit.utils/src/org/eclipse/papyrus/junit/utils/PackageExplorerUtils.java @@ -1,91 +1,91 @@ -/*****************************************************************************
- * Copyright (c) 2012 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:
- * Vincent Lorenzo (CEA LIST) Vincent.Lorenzo@cea.fr - Initial API and implementation
- *
- *****************************************************************************/
-package org.eclipse.papyrus.junit.utils;
-
-import java.util.List;
-
-import org.eclipse.jdt.ui.IPackagesViewPart;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.junit.Assert;
-
-/**
- *
- * Utils Methods for the Package Explorer
- *
- */
-public class PackageExplorerUtils {
-
- /** ID of the Package Explorer View */
- private static final String PACKAGE_EXPLORER_VIEW_ID = "org.eclipse.jdt.ui.PackageExplorer";
-
- /**
- * This methods opens the PackageExplorerView, and give it the focus
- *
- * @throws PartInitException
- */
- public static final IPackagesViewPart openPackageExplorerView() throws PartInitException {
- final IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- IPackagesViewPart pack = null;
- IViewPart packageExplorer = activeWorkbenchWindow.getActivePage().showView(PACKAGE_EXPLORER_VIEW_ID);
- pack = (IPackagesViewPart)packageExplorer;
- Assert.assertNotNull(pack);
- pack.setFocus();
- return pack;
-
- }
-
- /**
- * Set the selection in the PackageExplorer
- *
- * @param packageExplorer
- * the package explorer
- * @param newSelection
- * the new selection
- */
- public static final void setSelectionInPackageExplorerView(final IPackagesViewPart packageExplorer, final IStructuredSelection newSelection) {
- packageExplorer.getTreeViewer().expandAll();
- packageExplorer.getTreeViewer().setSelection(newSelection);
- //we verify that the current selection is correct in the PackageExplorer
- IStructuredSelection currentSelection = (IStructuredSelection)packageExplorer.getTreeViewer().getSelection();
- Assert.assertEquals("Package Explorer: The current selection is not the same as the wanted selection", currentSelection.toList(), newSelection.toList());
-
- //we verify that the current selection is correct using the selection service
- currentSelection = getCurrentSelectionInPackageExplorerView();
- Assert.assertEquals("Package Explorer: The SelectionService doesn't return the wanted selection", currentSelection.toList(), newSelection.toList());
- }
-
- /**
- *
- * @return
- * the current selection in the PackageExplorer
- */
- public static final IStructuredSelection getCurrentSelectionInPackageExplorerView() {
- return (IStructuredSelection)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(PACKAGE_EXPLORER_VIEW_ID);
- }
-
- /**
- *
- * @return
- * the current selection in the PackageExplorer as List
- */
- public static final List<?> getCurrentSelectionAsListInPackageExplorerView() {
- final IStructuredSelection selection = (IStructuredSelection)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(PACKAGE_EXPLORER_VIEW_ID);
- final List<?> list = selection.toList();
- return list;
- }
-}
+/***************************************************************************** + * Copyright (c) 2012 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: + * Vincent Lorenzo (CEA LIST) Vincent.Lorenzo@cea.fr - Initial API and implementation + * + *****************************************************************************/ +package org.eclipse.papyrus.junit.utils; + +import java.util.List; + +import org.eclipse.jdt.ui.IPackagesViewPart; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.ui.IViewPart; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.junit.Assert; + +/** + * + * Utils Methods for the Package Explorer + * + */ +public class PackageExplorerUtils { + + /** ID of the Package Explorer View */ + private static final String PACKAGE_EXPLORER_VIEW_ID = "org.eclipse.jdt.ui.PackageExplorer"; //$NON-NLS-1$ + + /** + * This methods opens the PackageExplorerView, and give it the focus + * + * @throws PartInitException + */ + public static final IPackagesViewPart openPackageExplorerView() throws PartInitException { + final IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); + IPackagesViewPart pack = null; + IViewPart packageExplorer = activeWorkbenchWindow.getActivePage().showView(PACKAGE_EXPLORER_VIEW_ID); + pack = (IPackagesViewPart)packageExplorer; + Assert.assertNotNull(pack); + pack.setFocus(); + return pack; + + } + + /** + * Set the selection in the PackageExplorer + * + * @param packageExplorer + * the package explorer + * @param newSelection + * the new selection + */ + public static final void setSelectionInPackageExplorerView(final IPackagesViewPart packageExplorer, final IStructuredSelection newSelection) { + packageExplorer.getTreeViewer().expandAll(); + packageExplorer.getTreeViewer().setSelection(newSelection); + //we verify that the current selection is correct in the PackageExplorer + IStructuredSelection currentSelection = (IStructuredSelection)packageExplorer.getTreeViewer().getSelection(); + Assert.assertEquals("Package Explorer: The current selection is not the same as the wanted selection", currentSelection.toList(), newSelection.toList()); //$NON-NLS-1$ + + //we verify that the current selection is correct using the selection service + currentSelection = getCurrentSelectionInPackageExplorerView(); + Assert.assertEquals("Package Explorer: The SelectionService doesn't return the wanted selection", currentSelection.toList(), newSelection.toList()); //$NON-NLS-1$ + } + + /** + * + * @return + * the current selection in the PackageExplorer + */ + public static final IStructuredSelection getCurrentSelectionInPackageExplorerView() { + return (IStructuredSelection)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(PACKAGE_EXPLORER_VIEW_ID); + } + + /** + * + * @return + * the current selection in the PackageExplorer as List + */ + public static final List<?> getCurrentSelectionAsListInPackageExplorerView() { + final IStructuredSelection selection = (IStructuredSelection)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(PACKAGE_EXPLORER_VIEW_ID); + final List<?> list = selection.toList(); + return list; + } +} |