Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 853ada99096813bb0a08bea1f656a41a3f1d95f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*****************************************************************************
 * Copyright (c) 2013, 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:
 *  Remi Schnekenburger (CEA LIST) - Initial API and implementation
 *  Christian W. Damus (CEA) - bug 431109
 *
 *****************************************************************************/
package org.eclipse.papyrus.infra.gmfdiag.common.commands;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.IUndoableOperation;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.UnexecutableCommand;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.edit.command.CommandParameter;
import org.eclipse.emf.edit.command.CreateChildCommand;
import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.CompositeEMFOperation;
import org.eclipse.gmf.runtime.common.core.command.CommandResult;
import org.eclipse.gmf.runtime.common.core.command.ICommand;
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
import org.eclipse.gmf.runtime.emf.type.core.commands.CreateElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.papyrus.infra.core.services.ServiceException;
import org.eclipse.papyrus.infra.core.services.ServicesRegistry;
import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
import org.eclipse.papyrus.infra.emf.utils.ServiceUtilsForResource;
import org.eclipse.papyrus.infra.gmfdiag.common.Activator;
import org.eclipse.papyrus.infra.services.labelprovider.service.LabelProviderService;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;

/**
 * Creation command based on the metamodel.edit framework instead of relying on
 * the defaut GMF creation mechanism.
 * <P>
 * So the creation of elements is similar to the creation customized in the metamodel itself, which can be interesting for metamodels like UML. This can avoid specific code for example for Activity.createNode() list of commands.
 * </P>
 * <P>
 * The implementation relies on a composite command that delegates first the basic creation of the element to the metamodel.edit service.<BR/>
 * A second operation computes during execution the list of additional commands to configure the newly created element. For example, the name of the new element can be set in configure commands. Note: the configure command needs the newly created command, so
 * the list of operations to perform is unknown until the composite operation is executed. The executability of the 2nd set of commands can be hard to test.
 * </P>
 */
public class CreateEditBasedElementCommand extends CreateElementCommand {

	protected final class CreateEditBasedElementTransactionalCommand extends AbstractTransactionalCommand {
		private Collection<Command> possibleCommands;
		private Command commandDone;

		protected CreateEditBasedElementTransactionalCommand(TransactionalEditingDomain domain, String label, List<?> affectedFiles) {
			super(domain, label, affectedFiles);
		}

		@Override
		public boolean canExecute() {
			// Optimistically enable if the request would have to create
			// the container, because
			// we can't do that in a read-only context (when not
			// actually executing)
			return canCreateChild() && (!hasElementToEdit() || !(getPossibleCommands().isEmpty()));
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
			Command command = prepareCommand();
			if (command.canExecute()) {
				// create an IUndoableOperation => undo is relying on
				// the execution of this command
				command.execute();
				return CommandResult.newOKCommandResult(newElement);
			}
			return CommandResult.newErrorCommandResult("Impossible to create Element");
		}

		protected Collection<Command> getPossibleCommands() {
			if (possibleCommands == null) {
				possibleCommands = new HashSet<Command>();
				EClass eClass = getElementType().getEClass();
				List<EClass> eClassesToCreateCommandsFor = new ArrayList<EClass>();
				if (eClass.isAbstract()) {
					// If we didn't receive a hint on the eClass to create
					if (eClassHint == null) {
						eClassesToCreateCommandsFor.addAll(EMFHelper.getSubclassesOf(eClass, true));
					} else {
						eClassesToCreateCommandsFor.add(eClassHint);
					}
				} else {
					eClassesToCreateCommandsFor.add(eClass);
				}
				if (eClassesToCreateCommandsFor.isEmpty()) {
					possibleCommands.add(UnexecutableCommand.INSTANCE);
				}
				EObject element = getElementToEdit();
				if (element != null) {
					// Do the default element creation
					EReference containment = getContainmentFeature();
					if (containment != null) {
						IEditingDomainItemProvider editingDomainItemProvider = AdapterFactoryEditingDomain.getEditingDomainItemProviderFor(element);
						for (EClass eClassToCreateCommandsFor : eClassesToCreateCommandsFor) {

							EObject newElement = eClassToCreateCommandsFor.getEPackage().getEFactoryInstance().create(eClassToCreateCommandsFor);
							Command possibleCommand = editingDomainItemProvider.createCommand(element, getEditingDomain(), CreateChildCommand.class, new CommandParameter(element, containment, new CommandParameter(null, containment, newElement)));
							if (possibleCommand == null) {
								possibleCommands.add(UnexecutableCommand.INSTANCE);
							} else {
								if (possibleCommand.canExecute()) {
									possibleCommands.add(possibleCommand);
								}
							}
						}
					}
				}
			}
			return possibleCommands;
		}

		/**
		 * Prepares the EMF command to which we delegate execution, if
		 * it has not already been created. This is not safe to do in a
		 * read-only context if our request does not {@link CreateEditBasedElementCommand#hasElementToEdit() have
		 * a container}, because this would attempt to create that
		 * container.
		 *
		 * @see CreateEditBasedElementCommand#hasElementToEdit()
		 */
		protected Command prepareCommand() {
			if (commandDone == null) {
				// Do the default element creation
				EReference containment = getContainmentFeature();
				EClass eClass = getElementType().getEClass();
				if (eClass.isAbstract()) {
					if (eClassHint == null) {
						// If we didn't receive a hint on the eClass to create
						// Propose to select appropriate concrete sub-metaclass
						try {
							ServicesRegistry registry = ServiceUtilsForResource.getInstance().getServiceRegistry(getElementToEdit().eResource());
							if (registry != null) {
								LabelProviderService labelProviderService = registry.getService(LabelProviderService.class);
								if (labelProviderService != null) {
									ElementListSelectionDialog dialog = new ElementListSelectionDialog(Display.getCurrent().getActiveShell(), labelProviderService.getLabelProvider());
									dialog.setTitle("Metaclass selection");
									dialog.setMessage("Select the a concrete sub-metaclass of " + eClass.getName());
									dialog.setElements(EMFHelper.getSubclassesOf(eClass, true).toArray());
									dialog.setMultipleSelection(false);
									dialog.open();
									Object[] results = dialog.getResult();
									if (results != null) {
										if (results.length > 0) {
											if (results[0] instanceof EClass) {
												eClass = (EClass) results[0];
											}
										}
									}
								} else {
									Activator.log.error(new NullPointerException());
									commandDone = UnexecutableCommand.INSTANCE;
								}
							} else {
								Activator.log.error(new NullPointerException());
								commandDone = UnexecutableCommand.INSTANCE;
							}
						} catch (ServiceException e) {
							Activator.log.error(e);
							commandDone = UnexecutableCommand.INSTANCE;
						}
					} else {
						eClass = eClassHint;
					}
				}
				if (containment != null) {
					EObject element = getElementToEdit();
					if (element != null) {
						newElement = eClass.getEPackage().getEFactoryInstance().create(eClass);
						IEditingDomainItemProvider editingDomainItemProvider = AdapterFactoryEditingDomain.getEditingDomainItemProviderFor(element);
						commandDone = editingDomainItemProvider.createCommand(element, getEditingDomain(), CreateChildCommand.class, new CommandParameter(element, containment, new CommandParameter(null, containment, newElement)));
					}
				}
				if (commandDone == null) {
					// Couldn't create a useful command
					commandDone = UnexecutableCommand.INSTANCE;
				}
			}
			return commandDone;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		public boolean canUndo() {
			return commandDone.canUndo();
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
			commandDone.undo();
			return Status.OK_STATUS;
		}

		/**
		 * {@inheritDoc}
		 */
		@Override
		protected IStatus doRedo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
			commandDone.redo();
			return Status.OK_STATUS;
		}
	}

	/** Shadow the base class's element-to-edit because we need direct access. */
	private EObject elementToEdit;

	/** newly created element */
	protected EObject newElement;

	/**
	 * composite operation in charge of listing and executing all performed
	 * operations
	 */
	protected CompositeEMFOperation compositeEMFOperation;

	public static final String ECLASS_HINT = "ECLASS_HINT";

	protected EClass eClassHint = null;

	/**
	 * Constructor.
	 *
	 * @param request
	 *            create element request creating this command
	 */
	public CreateEditBasedElementCommand(CreateElementRequest request) {
		super(request);
		Object eClassHintParamValue = request.getParameter(ECLASS_HINT);
		if (eClassHintParamValue instanceof EClass) {
			eClassHint = (EClass) eClassHintParamValue;
		}
		EObject container = request.getContainer();
		if ((container != null) && container.eClass().getEAllContainments().contains(request.getContainmentFeature())) {
			setElementToEdit(container);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
		if (compositeEMFOperation != null && compositeEMFOperation.canUndo()) {
			return compositeEMFOperation.undo(monitor, info);
		}
		return new Status(IStatus.ERROR, Activator.ID, "imposible to undo the command");
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected IStatus doRedo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
		if (compositeEMFOperation != null && compositeEMFOperation.canRedo()) {
			return compositeEMFOperation.redo(monitor, info);
		}
		return new Status(IStatus.ERROR, Activator.ID, "imposible to redo the command");
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean canExecute() {
		// The superclass implementation can short-circuit the effort of
		// preparing the operation
		return super.canExecute() && prepareOperation().canExecute();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
		IUndoableOperation operation = prepareOperation();
		IStatus compositeStatus = operation.execute(monitor, info);
		return (compositeStatus == null) ? CommandResult.newOKCommandResult(newElement) : new CommandResult(compositeStatus, newElement);
	}

	protected IUndoableOperation prepareOperation() {
		if (compositeEMFOperation == null) {
			compositeEMFOperation = new CompositeEMFOperation(getEditingDomain(), "Create Element");
			// creates the basic element
			AbstractTransactionalCommand createTransactionalCommand = new CreateEditBasedElementTransactionalCommand(getEditingDomain(), "Create basic element", getAffectedFiles());
			compositeEMFOperation.add(createTransactionalCommand);
			AbstractTransactionalCommand configureTransactionalCommand = new AbstractTransactionalCommand(getEditingDomain(), "Configure element", getAffectedFiles()) {

				/**
				 * {@inheritDoc}ondre
				 */
				@Override
				protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
					// Configure the new element
					ConfigureRequest configureRequest = createConfigureRequest();
					ICommand configureCommand = getElementType().getEditCommand(configureRequest);
					IStatus configureStatus = null;
					if (configureCommand != null && configureCommand.canExecute()) {
						configureStatus = configureCommand.execute(monitor, info);
					}
					// Put the newly created element in the request so that the
					// 'after' commands have access to it.
					getCreateRequest().setNewElement(newElement);
					return (configureStatus == null) ? CommandResult.newOKCommandResult(newElement) : new CommandResult(configureStatus, newElement);
				}
			};
			// executes the command and then adds it to the list
			compositeEMFOperation.add(configureTransactionalCommand); // add
																		// before
																		// execution
		}
		return compositeEMFOperation;
	}

	protected boolean isPrepared() {
		return compositeEMFOperation != null;
	}

	/**
	 * Creates the request to configure the new element.
	 *
	 * @return the request
	 */
	@Override
	protected ConfigureRequest createConfigureRequest() {
		ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, getElementType());
		// pass along the client context
		configureRequest.setClientContext(getCreateRequest().getClientContext());
		configureRequest.addParameters(getRequest().getParameters());
		return configureRequest;
	}

	/**
	 * Queries whether I know my element to edit, yet.
	 *
	 * @return whether I have an element to edit
	 */
	protected boolean hasElementToEdit() {
		return elementToEdit != null;
	}

	@Override
	protected void setElementToEdit(EObject element) {
		this.elementToEdit = element;
		super.setElementToEdit(element);
	}

	/**
	 * An enablement filter heuristically determining whether we think we will
	 * be able to create the child element.
	 *
	 * @return whether we can create the new child element
	 */
	protected boolean canCreateChild() {
		// Assume we can unless we think we can't
		boolean result = true;
		// This is an additional constraint in the EMF CreateChildCommand that
		// we use, that the GMF CreateElementCommand doesn't apply
		Object context = getRequest().getEditHelperContext();
		if (context instanceof EObject) {
			EObject owner = (EObject) context;
			EReference reference = getContainmentFeature();
			// The context may not have this reference if some intermediate
			// container is to be created by the edit-helper.
			// But, then, we can only optimistically report that we can create
			// the child
			if ((reference != null) && !reference.isMany() && (owner.eClass().getEAllReferences().contains(reference))) {
				// Don't replace an existing value
				result = ((EObject) context).eGet(reference) == null;
			}
		}
		return result;
	}

	@Override
	public void dispose() {
		if (isPrepared()) {
			compositeEMFOperation.dispose();
			compositeEMFOperation = null;
		}
		super.dispose();
	}
}

Back to the top