1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.modeling.ui.diagramEditor.e4;
14 import java.awt.Point;
15 import java.awt.datatransfer.Transferable;
16 import java.awt.datatransfer.UnsupportedFlavorException;
17 import java.awt.dnd.DnDConstants;
18 import java.awt.dnd.DropTargetDragEvent;
19 import java.awt.dnd.DropTargetDropEvent;
20 import java.awt.dnd.DropTargetEvent;
21 import java.awt.geom.AffineTransform;
22 import java.awt.geom.Point2D;
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.List;
28 import org.eclipse.core.runtime.IAdaptable;
29 import org.eclipse.core.runtime.IStatus;
30 import org.eclipse.core.runtime.Status;
31 import org.eclipse.e4.ui.model.application.ui.basic.MPart;
32 import org.eclipse.jface.viewers.IStructuredSelection;
33 import org.eclipse.osgi.util.NLS;
34 import org.simantics.Simantics;
35 import org.simantics.db.ReadGraph;
36 import org.simantics.db.RequestProcessor;
37 import org.simantics.db.Resource;
38 import org.simantics.db.Session;
39 import org.simantics.db.WriteGraph;
40 import org.simantics.db.common.request.PossibleIndexRoot;
41 import org.simantics.db.common.request.UniqueRead;
42 import org.simantics.db.common.request.WriteRequest;
43 import org.simantics.db.common.utils.NameUtils;
44 import org.simantics.db.exception.DatabaseException;
45 import org.simantics.db.layer0.request.IsLinkedTo;
46 import org.simantics.db.layer0.util.Layer0Utils;
47 import org.simantics.db.service.SerialisationSupport;
48 import org.simantics.diagram.Logger;
49 import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;
50 import org.simantics.diagram.content.Change;
51 import org.simantics.diagram.content.DiagramContentChanges;
52 import org.simantics.diagram.content.DiagramContentTracker;
53 import org.simantics.diagram.stubs.DiagramResource;
54 import org.simantics.diagram.symbollibrary.ISymbolItem;
55 import org.simantics.diagram.synchronization.runtime.DiagramSelectionUpdater;
56 import org.simantics.diagram.ui.DiagramModelHints;
57 import org.simantics.diagram.ui.ElementClassTransferable;
58 import org.simantics.diagram.ui.ElementClassTransferable.ResourceElementClassTransferData;
59 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
60 import org.simantics.g2d.diagram.DiagramHints;
61 import org.simantics.g2d.diagram.DiagramUtils;
62 import org.simantics.g2d.diagram.IDiagram;
63 import org.simantics.g2d.diagram.handler.PickContext;
64 import org.simantics.g2d.diagram.handler.PickRequest;
65 import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
66 import org.simantics.g2d.dnd.DnDHints;
67 import org.simantics.g2d.dnd.ElementClassDragItem;
68 import org.simantics.g2d.dnd.IDnDContext;
69 import org.simantics.g2d.dnd.IDragItem;
70 import org.simantics.g2d.dnd.IDropTargetParticipant;
71 import org.simantics.g2d.element.ElementClass;
72 import org.simantics.g2d.element.ElementHints;
73 import org.simantics.g2d.element.ElementUtils;
74 import org.simantics.g2d.element.IElement;
75 import org.simantics.g2d.participant.TransformUtil;
76 import org.simantics.modeling.ModelingResources;
77 import org.simantics.modeling.ui.Activator;
78 import org.simantics.modeling.ui.diagramEditor.WSEDragItem;
79 import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;
80 import org.simantics.structural.stubs.StructuralResource2;
81 import org.simantics.ui.dnd.LocalObjectTransfer;
82 import org.simantics.ui.dnd.LocalObjectTransferable;
83 import org.simantics.ui.selection.WorkbenchSelectionElement;
84 import org.simantics.ui.workbench.e4.E4WorkbenchUtils;
85 import org.simantics.utils.logging.TimeLogger;
88 * This participant populates Elements from ElementClass-resources drops
90 public class PopulateElementDropParticipant extends AbstractDiagramParticipant implements IDropTargetParticipant {
92 @Dependency PickContext pickContext;
93 @Dependency TransformUtil transformUtil;
95 protected GraphToDiagramSynchronizer synchronizer;
98 public PopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer) {
99 this(synchronizer, null);
102 public PopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer, MPart part) {
103 this.synchronizer = synchronizer;
108 public void dragEnter(DropTargetDragEvent dtde, IDnDContext dp) {
112 Transferable tr = dtde.getTransferable();
113 if (tr.isDataFlavorSupported(LocalObjectTransferable.FLAVOR)) {
114 // System.out.println("joo");
117 // This must be done to have SWT transfer set the source data
119 obj = tr.getTransferData(LocalObjectTransferable.FLAVOR);
120 // System.out.println("GOT FROM AWT: " + obj);
121 } catch (UnsupportedFlavorException e) {
122 // TODO Auto-generated catch block
124 } catch (IOException e) {
125 // TODO Auto-generated catch block
130 if (!(obj instanceof IStructuredSelection)) {
131 obj = LocalObjectTransfer.getTransfer().getObject();
132 // System.out.println("GOT FROM SWT: " + obj);
135 if (obj instanceof IStructuredSelection) {
136 IStructuredSelection sel = (IStructuredSelection) obj;
137 if (!sel.isEmpty()) {
138 for (Object elm : sel.toList()) {
139 if (elm instanceof IAdaptable) {
140 ElementClass ec = (ElementClass) ((IAdaptable) elm).getAdapter(ElementClass.class);
142 dp.add(new ElementClassDragItem(ec));
144 Resource r = (Resource) ((IAdaptable) elm).getAdapter(Resource.class);
146 if (elm instanceof ISymbolItem) {
147 /* FIXME fix this check
148 ISymbolItem symbol = (ISymbolItem) elm;
149 Resource dia = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
151 if (!DiagramTypeUtils.symbolAllowedOnDiagram(synchronizer.getSession(), symbol, dia)) {
152 // Deny dragging of this symbol
155 } catch (DatabaseException e) {
162 String valid = validateDrop(synchronizer.getSession(), r,
163 diagram.<Resource> getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE));
165 ElementClassDragItem item = new ElementClassDragItem(synchronizer.getNodeClass(r));
166 item.getHintContext().setHint(ElementHints.KEY_TRANSFORM, AffineTransform.getScaleInstance(1, 1));
169 } catch (DatabaseException e) {
170 // Ignore node-class retrieval failures.
171 //System.out.println("error: " + e.getMessage());
178 // Let the default logic handle out how many columns to use.
179 dp.getHints().removeHint(DnDHints.KEY_DND_GRID_COLUMNS);
186 if (tr.isDataFlavorSupported(ElementClassTransferable.FLAVOR)) {
187 ResourceElementClassTransferData dada;
189 dada = (ResourceElementClassTransferData) tr.getTransferData(ElementClassTransferable.FLAVOR);
190 } catch (UnsupportedFlavorException e) {
192 } catch (IOException e) {
195 Session s = synchronizer.getSession();
197 for (String rid : dada.elementClassResourceRandomAccessReference) {
198 SerialisationSupport support = s.getService(SerialisationSupport.class);
199 Resource r = support.getResource(Long.parseLong(rid));
200 dp.add(new ElementClassDragItem(synchronizer.getNodeClass(r)));
202 } catch (DatabaseException e) {
203 throw new RuntimeException(e);
210 private String validateDrop(RequestProcessor processor, final Resource draggedResource, final Resource dropTarget) throws DatabaseException {
211 return processor.syncRequest(new UniqueRead<String>() {
213 public String perform(ReadGraph graph) throws DatabaseException {
214 // System.out.println("dragged resource: " + draggedResource);
215 // System.out.println("drop target resource: " + dropTarget);
216 Resource sourceModel = graph.syncRequest(new PossibleIndexRoot(draggedResource));
217 Resource targetModel = graph.syncRequest(new PossibleIndexRoot(dropTarget));
218 // System.out.println("source model: " + sourceModel);
219 // System.out.println("target model: " + targetModel);
221 // Prevent dragging data from one source model to another.
222 // If source is not part of any model, everything is okay.
223 if (sourceModel != null && !graph.syncRequest(new IsLinkedTo(targetModel, sourceModel))) {
224 // Prevent a symbol instantiating within its own configuration.
225 // NOTE: this doesn't handle transitive cycles.
226 return NLS.bind(Messages.PopulateElementDropParticipant_CannotInstantiate,
227 new Object[] { NameUtils.getSafeName(graph, draggedResource),
228 NameUtils.getURIOrSafeNameInternal(graph, targetModel),
229 NameUtils.getURIOrSafeNameInternal(graph, sourceModel) });
232 // Prevent dragging to published components
233 ModelingResources MOD = ModelingResources.getInstance(graph);
234 StructuralResource2 STR = StructuralResource2.getInstance(graph);
235 Resource configuration = graph.getPossibleObject(dropTarget, MOD.DiagramToComposite);
236 if (configuration != null) {
237 Resource componentTypeFromDiagram = graph.getPossibleObject(configuration, STR.Defines);
238 if (componentTypeFromDiagram != null) {
239 if (Layer0Utils.isPublished(graph, componentTypeFromDiagram))
240 return Messages.PopulateElementDropParticipant_CannotCreateElementIntoDiagram;
244 // Prevent dragging a symbol of component type into its own configuration.
245 Resource componentTypeFromSymbol = graph.getPossibleObject(draggedResource, MOD.SymbolToComponentType);
246 if (componentTypeFromSymbol != null) {
247 if (configuration != null) {
248 Resource componentTypeFromDiagram = graph.getPossibleObject(configuration, STR.Defines);
249 if (componentTypeFromDiagram != null
250 && componentTypeFromSymbol.equals(componentTypeFromDiagram)) {
251 return Messages.PopulateElementDropParticipant_CannotInstantiateUserComponent;
262 public void dragExit(DropTargetEvent dte, IDnDContext dp) {
263 // System.out.println("exit");
267 public void dragOver(DropTargetDragEvent dtde, IDnDContext dp) {
268 // System.out.println("over");
271 private IElement tryPick(Point p) {
273 Point2D canvas = transformUtil.controlToCanvas(p, null);
275 assertDependencies();
277 PickRequest req = new PickRequest(canvas);
278 req.pickPolicy = PickRequest.PickPolicy.PICK_INTERSECTING_OBJECTS;
279 List<IElement> picks = new ArrayList<IElement>();
280 pickContext.pick(diagram, req, picks);
282 if(picks.size() == 1) return picks.iterator().next();
289 public void drop(DropTargetDropEvent dtde, final IDnDContext dp) {
290 TimeLogger.resetTimeAndLog(getClass(), "drop"); //$NON-NLS-1$
292 final IDiagram d = getHint(DiagramHints.KEY_DIAGRAM);
296 IElement pick = tryPick(dtde.getLocation());
299 final List<WorkbenchSelectionElement> wses = new ArrayList<WorkbenchSelectionElement>();
301 for(IDragItem i : dp.toArray())
302 if(i instanceof WSEDragItem)
303 wses.add(((WSEDragItem)i).getObject());
305 final Resource element = (Resource)ElementUtils.getData(d, pick);
306 if(element != null && !wses.isEmpty()) {
310 Simantics.getSession().syncRequest(new WriteRequest() {
313 public void perform(WriteGraph graph) throws DatabaseException {
315 DiagramResource DIA = DiagramResource.getInstance(graph);
317 Simantics.invokeSCLWrite(graph, element, DIA.symbolDropHandler, wses);
323 } catch (DatabaseException e) {
324 Logger.defaultLogError(e);
334 Runnable creator = () -> {
335 DiagramUtils.mutateDiagram(d, m -> {
336 IDragItem items[] = dp.toArray();
338 for (IDragItem i : items) {
339 if (!(i instanceof ElementClassDragItem))
342 ElementClassDragItem res = (ElementClassDragItem) i;
343 ElementClass ec = res.getElementClass();
345 Point2D pos = dp.getItemPosition(i);
346 // System.out.println(pos);
347 assert (pos != null);
349 IElement element = m.newElement(ec);
350 element.setHints(res.getHintContext().getHints());
352 setupDroppedElement(element, pos);
354 // Remove only the drag items we've processed.
360 selectNewDiagramContentAfter(d, part, creator);
362 getContext().getContentContext().setDirty();
365 protected void selectNewDiagramContentAfter(IDiagram d, MPart activatePart, Runnable diagramModifier) {
367 Resource diagramResource = d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
368 final DiagramContentTracker tracker = diagramResource == null ? null
369 : DiagramContentTracker.start(getContext(), Simantics.getSession(), diagramResource);
371 diagramModifier.run();
373 if (tracker != null) {
374 // Get difference of diagram contents to find out what was added.
375 DiagramContentChanges changes = tracker.update();
376 Set<Resource> addedElements = changes.pick(changes.elements, Change.ADDED);
377 if (!addedElements.isEmpty()) {
378 new DiagramSelectionUpdater(getContext())
379 .setNewSelection(0, addedElements)
382 if (activatePart != null)
383 E4WorkbenchUtils.activatePart(activatePart);
386 } catch (DatabaseException e) {
387 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.PopulateElementDropParticipant_ActivatorDiagramContentTrackingFailed, e));
391 protected void setupDroppedElement(IElement element, Point2D dropPos) {
392 // This works only for elements without parents.
393 ISnapAdvisor snapAdvisor = getContext().getHintStack().getHint(DiagramHints.SNAP_ADVISOR);
394 if(snapAdvisor != null)
395 snapAdvisor.snap(dropPos);
397 IElement parent = element.getHint(ElementHints.KEY_PARENT_ELEMENT);
398 if (parent != null) {
399 Point2D parentPos = ElementUtils.getPos(parent);
400 Point2D pos = new Point2D.Double(dropPos.getX() - parentPos.getX(), dropPos.getY() - parentPos.getY());
401 ElementUtils.setPos(element, pos);
403 ElementUtils.setPos(element, dropPos);
408 public void dropActionChanged(DropTargetDragEvent dtde, IDnDContext dp) {
409 dtde.acceptDrag(DnDConstants.ACTION_COPY);
413 public int getAllowedOps() {
414 return DnDConstants.ACTION_COPY;
418 public double getPriority() {