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;
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.jface.viewers.IStructuredSelection;
32 import org.eclipse.ui.IWorkbenchPartSite;
33 import org.simantics.Simantics;
34 import org.simantics.db.ReadGraph;
35 import org.simantics.db.RequestProcessor;
36 import org.simantics.db.Resource;
37 import org.simantics.db.Session;
38 import org.simantics.db.WriteGraph;
39 import org.simantics.db.common.request.PossibleIndexRoot;
40 import org.simantics.db.common.request.ResourceRead2;
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.layer0.variable.Variable;
48 import org.simantics.db.layer0.variable.Variables;
49 import org.simantics.db.service.SerialisationSupport;
50 import org.simantics.diagram.adapter.GraphToDiagramSynchronizer;
51 import org.simantics.diagram.content.Change;
52 import org.simantics.diagram.content.DiagramContentChanges;
53 import org.simantics.diagram.content.DiagramContentTracker;
54 import org.simantics.diagram.stubs.DiagramResource;
55 import org.simantics.diagram.symbollibrary.ISymbolItem;
56 import org.simantics.diagram.synchronization.runtime.DiagramSelectionUpdater;
57 import org.simantics.diagram.ui.DiagramModelHints;
58 import org.simantics.diagram.ui.ElementClassTransferable;
59 import org.simantics.diagram.ui.ElementClassTransferable.ResourceElementClassTransferData;
60 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
61 import org.simantics.g2d.diagram.DiagramHints;
62 import org.simantics.g2d.diagram.DiagramUtils;
63 import org.simantics.g2d.diagram.IDiagram;
64 import org.simantics.g2d.diagram.handler.PickContext;
65 import org.simantics.g2d.diagram.handler.PickRequest;
66 import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
67 import org.simantics.g2d.dnd.DnDHints;
68 import org.simantics.g2d.dnd.ElementClassDragItem;
69 import org.simantics.g2d.dnd.IDnDContext;
70 import org.simantics.g2d.dnd.IDragItem;
71 import org.simantics.g2d.dnd.IDropTargetParticipant;
72 import org.simantics.g2d.element.ElementClass;
73 import org.simantics.g2d.element.ElementHints;
74 import org.simantics.g2d.element.ElementUtils;
75 import org.simantics.g2d.element.IElement;
76 import org.simantics.g2d.participant.TransformUtil;
77 import org.simantics.modeling.ModelingResources;
78 import org.simantics.modeling.ui.Activator;
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.utils.logging.TimeLogger;
85 import org.simantics.utils.ui.workbench.WorkbenchUtils;
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;
96 protected IWorkbenchPartSite partSite;
98 public PopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer) {
99 this(synchronizer, null);
102 public PopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer, IWorkbenchPartSite partSite) {
103 this.synchronizer = synchronizer;
104 this.partSite = partSite;
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 "Cannot instantiate " + NameUtils.getSafeName(graph, draggedResource) + " into model "
227 + NameUtils.getURIOrSafeNameInternal(graph, targetModel) + ". The source namespace ("
228 + NameUtils.getURIOrSafeNameInternal(graph, sourceModel) + ") is not linked to the target model.";
231 // Prevent dragging to published components
232 ModelingResources MOD = ModelingResources.getInstance(graph);
233 StructuralResource2 STR = StructuralResource2.getInstance(graph);
234 Resource configuration = graph.getPossibleObject(dropTarget, MOD.DiagramToComposite);
235 if (configuration != null) {
236 Resource componentTypeFromDiagram = graph.getPossibleObject(configuration, STR.Defines);
237 if(componentTypeFromDiagram != null) {
238 if(Layer0Utils.isPublished(graph, componentTypeFromDiagram))
239 return "Cannot create elements into a diagram that belongs to a published user component.";
243 // Prevent dragging a symbol of component type into its own configuration.
244 Resource componentTypeFromSymbol = graph.getPossibleObject(draggedResource, MOD.SymbolToComponentType);
245 if (componentTypeFromSymbol != null) {
246 if (configuration != null) {
247 Resource componentTypeFromDiagram = graph.getPossibleObject(configuration, STR.Defines);
248 if (componentTypeFromDiagram != null && componentTypeFromSymbol.equals(componentTypeFromDiagram)) {
249 return "Cannot instantiate user component within its own configuration.";
260 public void dragExit(DropTargetEvent dte, IDnDContext dp) {
261 // System.out.println("exit");
265 public void dragOver(DropTargetDragEvent dtde, IDnDContext dp) {
266 // System.out.println("over");
269 private IElement tryPick(Point p) {
271 Point2D canvas = transformUtil.controlToCanvas(p, null);
273 assertDependencies();
275 PickRequest req = new PickRequest(canvas);
276 req.pickPolicy = PickRequest.PickPolicy.PICK_INTERSECTING_OBJECTS;
277 List<IElement> picks = new ArrayList<IElement>();
278 pickContext.pick(diagram, req, picks);
280 if(picks.size() == 1) return picks.iterator().next();
287 public void drop(DropTargetDropEvent dtde, final IDnDContext dp) {
288 TimeLogger.resetTimeAndLog(getClass(), "drop");
290 final IDiagram d = getHint(DiagramHints.KEY_DIAGRAM);
294 IElement pick = tryPick(dtde.getLocation());
297 final List<WorkbenchSelectionElement> wses = new ArrayList<WorkbenchSelectionElement>();
299 for(IDragItem i : dp.toArray())
300 if(i instanceof WSEDragItem)
301 wses.add(((WSEDragItem)i).getObject());
303 final Resource element = (Resource)ElementUtils.getData(d, pick);
304 if(element != null && !wses.isEmpty()) {
307 Session db = Simantics.getSession();
308 DiagramResource DIA = DiagramResource.getInstance(db);
309 Variable function = db.syncRequest(new PossibleVariableProperty(element, DIA.symbolDropHandler));
310 if (function != null) {
311 db.syncRequest(new WriteRequest() {
313 public void perform(WriteGraph graph) throws DatabaseException {
314 Simantics.invokeSCLWrite(graph, function, wses);
319 } catch (DatabaseException e) {
320 Activator.getDefault().getLog()
321 .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
322 "Invocation to custom symbolDropHandler for element "
323 + element + " failed.",
333 Runnable creator = new Runnable() {
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.
361 selectNewDiagramContentAfter(d, partSite, creator);
363 getContext().getContentContext().setDirty();
366 private static class PossibleVariableProperty extends ResourceRead2<Variable> {
368 public PossibleVariableProperty(Resource entity, Resource property) {
369 super(entity, property);
373 public Variable perform(ReadGraph graph) throws DatabaseException {
374 return Variables.tryGetProperty(graph, resource, resource2);
379 protected void selectNewDiagramContentAfter(IDiagram d, IWorkbenchPartSite activateSite, Runnable diagramModifier) {
381 Resource diagramResource = d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
382 final DiagramContentTracker tracker = diagramResource == null ? null
383 : DiagramContentTracker.start(getContext(), Simantics.getSession(), diagramResource);
385 diagramModifier.run();
387 if (tracker != null) {
388 // Get difference of diagram contents to find out what was added.
389 DiagramContentChanges changes = tracker.update();
390 Set<Resource> addedElements = changes.pick(changes.elements, Change.ADDED);
391 if (!addedElements.isEmpty()) {
392 new DiagramSelectionUpdater(getContext())
393 .setNewSelection(0, addedElements)
396 if (activateSite != null)
397 WorkbenchUtils.activatePart(activateSite);
400 } catch (DatabaseException e) {
401 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Diagram content change tracking failed.", e));
405 protected void setupDroppedElement(IElement element, Point2D dropPos) {
406 // This works only for elements without parents.
407 ISnapAdvisor snapAdvisor = getContext().getHintStack().getHint(DiagramHints.SNAP_ADVISOR);
408 if(snapAdvisor != null)
409 snapAdvisor.snap(dropPos);
411 IElement parent = element.getHint(ElementHints.KEY_PARENT_ELEMENT);
412 if (parent != null) {
413 Point2D parentPos = ElementUtils.getPos(parent);
414 Point2D pos = new Point2D.Double(dropPos.getX() - parentPos.getX(), dropPos.getY() - parentPos.getY());
415 ElementUtils.setPos(element, pos);
417 ElementUtils.setPos(element, dropPos);
422 public void dropActionChanged(DropTargetDragEvent dtde, IDnDContext dp) {
423 dtde.acceptDrag(DnDConstants.ACTION_COPY);
427 public int getAllowedOps() {
428 return DnDConstants.ACTION_COPY;
432 public double getPriority() {