Removed unnecessary dependencies on org.apache.log4j
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / diagramEditor / e4 / PopulateElementDropParticipant.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2020 Association for Decentralized Information Management
3  * in Industry THTH ry.
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
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.modeling.ui.diagramEditor.e4;
13
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;
26 import java.util.Set;
27
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.adapter.GraphToDiagramSynchronizer;
49 import org.simantics.diagram.content.Change;
50 import org.simantics.diagram.content.DiagramContentChanges;
51 import org.simantics.diagram.content.DiagramContentTracker;
52 import org.simantics.diagram.stubs.DiagramResource;
53 import org.simantics.diagram.symbollibrary.ISymbolItem;
54 import org.simantics.diagram.synchronization.runtime.DiagramSelectionUpdater;
55 import org.simantics.diagram.ui.DiagramModelHints;
56 import org.simantics.diagram.ui.ElementClassTransferable;
57 import org.simantics.diagram.ui.ElementClassTransferable.ResourceElementClassTransferData;
58 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
59 import org.simantics.g2d.diagram.DiagramHints;
60 import org.simantics.g2d.diagram.DiagramUtils;
61 import org.simantics.g2d.diagram.IDiagram;
62 import org.simantics.g2d.diagram.handler.PickContext;
63 import org.simantics.g2d.diagram.handler.PickRequest;
64 import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
65 import org.simantics.g2d.dnd.DnDHints;
66 import org.simantics.g2d.dnd.ElementClassDragItem;
67 import org.simantics.g2d.dnd.IDnDContext;
68 import org.simantics.g2d.dnd.IDragItem;
69 import org.simantics.g2d.dnd.IDropTargetParticipant;
70 import org.simantics.g2d.element.ElementClass;
71 import org.simantics.g2d.element.ElementHints;
72 import org.simantics.g2d.element.ElementUtils;
73 import org.simantics.g2d.element.IElement;
74 import org.simantics.g2d.participant.TransformUtil;
75 import org.simantics.modeling.ModelingResources;
76 import org.simantics.modeling.ui.Activator;
77 import org.simantics.modeling.ui.diagramEditor.WSEDragItem;
78 import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;
79 import org.simantics.structural.stubs.StructuralResource2;
80 import org.simantics.ui.dnd.LocalObjectTransfer;
81 import org.simantics.ui.dnd.LocalObjectTransferable;
82 import org.simantics.ui.selection.WorkbenchSelectionElement;
83 import org.simantics.ui.workbench.e4.E4WorkbenchUtils;
84 import org.simantics.utils.logging.TimeLogger;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87
88 /**
89  * This participant populates Elements from ElementClass-resources drops
90  */
91 public class PopulateElementDropParticipant extends AbstractDiagramParticipant implements IDropTargetParticipant {
92
93     private static final Logger LOGGER = LoggerFactory.getLogger(PopulateElementDropParticipant.class);
94
95     @Dependency PickContext pickContext;
96     @Dependency TransformUtil transformUtil;
97         
98     protected GraphToDiagramSynchronizer synchronizer;
99     protected MPart part;
100
101     public PopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer) {
102         this(synchronizer, null);
103     }
104
105     public PopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer, MPart part) {
106         this.synchronizer = synchronizer;
107         this.part = part;
108     }
109
110     @Override
111     public void dragEnter(DropTargetDragEvent dtde, IDnDContext dp) {
112         if (diagram == null)
113             return;
114
115         Transferable tr = dtde.getTransferable();
116         if (tr.isDataFlavorSupported(LocalObjectTransferable.FLAVOR)) {
117             // System.out.println("joo");
118             Object obj = null;
119
120             // This must be done to have SWT transfer set the source data
121             try {
122                 obj = tr.getTransferData(LocalObjectTransferable.FLAVOR);
123                 // System.out.println("GOT FROM AWT: " + obj);
124             } catch (UnsupportedFlavorException e) {
125                 // TODO Auto-generated catch block
126                 e.printStackTrace();
127             } catch (IOException e) {
128                 // TODO Auto-generated catch block
129                 e.printStackTrace();
130             }
131
132             // Check SWT
133             if (!(obj instanceof IStructuredSelection)) {
134                 obj = LocalObjectTransfer.getTransfer().getObject();
135                 // System.out.println("GOT FROM SWT: " + obj);
136             }
137
138             if (obj instanceof IStructuredSelection) {
139                 IStructuredSelection sel = (IStructuredSelection) obj;
140                 if (!sel.isEmpty()) {
141                     for (Object elm : sel.toList()) {
142                         if (elm instanceof IAdaptable) {
143                             ElementClass ec = (ElementClass) ((IAdaptable) elm).getAdapter(ElementClass.class);
144                             if (ec != null) {
145                                 dp.add(new ElementClassDragItem(ec));
146                             } else {
147                                 Resource r = (Resource) ((IAdaptable) elm).getAdapter(Resource.class);
148                                 if (r != null) {
149                                     if (elm instanceof ISymbolItem) {
150                                         /* FIXME fix this check 
151                                         ISymbolItem symbol = (ISymbolItem) elm;
152                                         Resource dia = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
153                                         try {
154                                             if (!DiagramTypeUtils.symbolAllowedOnDiagram(synchronizer.getSession(), symbol, dia)) {
155                                                 // Deny dragging of this symbol
156                                                 continue;
157                                             }
158                                         } catch (DatabaseException e) {
159                                             e.printStackTrace();
160                                             continue;
161                                         }*/
162                                     }
163
164                                     try {
165                                         String valid = validateDrop(synchronizer.getSession(), r,
166                                                 diagram.<Resource> getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE));
167                                         if (valid == null) {
168                                             ElementClassDragItem item = new ElementClassDragItem(synchronizer.getNodeClass(r));
169                                             item.getHintContext().setHint(ElementHints.KEY_TRANSFORM, AffineTransform.getScaleInstance(1, 1));
170                                             dp.add(item);
171                                         }
172                                     } catch (DatabaseException e) {
173                                         // Ignore node-class retrieval failures.
174                                         //System.out.println("error: " + e.getMessage());
175                                     }
176                                 }
177                             }
178                         }
179                     }
180
181                     // Let the default logic handle out how many columns to use.
182                     dp.getHints().removeHint(DnDHints.KEY_DND_GRID_COLUMNS);
183                 }
184             }
185
186             return;
187         }
188
189         if (tr.isDataFlavorSupported(ElementClassTransferable.FLAVOR)) {
190             ResourceElementClassTransferData dada;
191             try {
192                 dada = (ResourceElementClassTransferData) tr.getTransferData(ElementClassTransferable.FLAVOR);
193             } catch (UnsupportedFlavorException e) {
194                 throw new Error(e);
195             } catch (IOException e) {
196                 throw new Error(e);
197             }
198             Session s = synchronizer.getSession();
199             try {
200                 for (String rid : dada.elementClassResourceRandomAccessReference) {
201                     SerialisationSupport support = s.getService(SerialisationSupport.class);
202                     Resource r = support.getResource(Long.parseLong(rid));
203                     dp.add(new ElementClassDragItem(synchronizer.getNodeClass(r)));
204                 }
205             } catch (DatabaseException e) {
206                 throw new RuntimeException(e);
207             }
208
209             return;
210         }
211     }
212
213     private String validateDrop(RequestProcessor processor, final Resource draggedResource, final Resource dropTarget) throws DatabaseException {
214         return processor.syncRequest(new UniqueRead<String>() {
215             @Override
216             public String perform(ReadGraph graph) throws DatabaseException {
217                 // System.out.println("dragged resource: " + draggedResource);
218                 // System.out.println("drop target resource: " + dropTarget);
219                 Resource sourceModel = graph.syncRequest(new PossibleIndexRoot(draggedResource));
220                 Resource targetModel = graph.syncRequest(new PossibleIndexRoot(dropTarget));
221                 // System.out.println("source model: " + sourceModel);
222                 // System.out.println("target model: " + targetModel);
223
224                 // Prevent dragging data from one source model to another.
225                 // If source is not part of any model, everything is okay.
226                 if (sourceModel != null && !graph.syncRequest(new IsLinkedTo(targetModel, sourceModel))) {
227                     // Prevent a symbol instantiating within its own configuration.
228                     // NOTE: this doesn't handle transitive cycles.
229                     return NLS.bind(Messages.PopulateElementDropParticipant_CannotInstantiate,
230                             new Object[] { NameUtils.getSafeName(graph, draggedResource),
231                                     NameUtils.getURIOrSafeNameInternal(graph, targetModel),
232                                     NameUtils.getURIOrSafeNameInternal(graph, sourceModel) });
233                 }
234
235                 // Prevent dragging to published components
236                 ModelingResources MOD = ModelingResources.getInstance(graph);
237                 StructuralResource2 STR = StructuralResource2.getInstance(graph);
238                 Resource configuration = graph.getPossibleObject(dropTarget, MOD.DiagramToComposite);
239                 if (configuration != null) {
240                     Resource componentTypeFromDiagram = graph.getPossibleObject(configuration, STR.Defines);
241                     if (componentTypeFromDiagram != null) {
242                         if (Layer0Utils.isPublished(graph, componentTypeFromDiagram))
243                             return Messages.PopulateElementDropParticipant_CannotCreateElementIntoDiagram;
244                     }
245                 }
246
247                 // Prevent dragging a symbol of component type into its own configuration.
248                 Resource componentTypeFromSymbol = graph.getPossibleObject(draggedResource, MOD.SymbolToComponentType);
249                 if (componentTypeFromSymbol != null) {
250                     if (configuration != null) {
251                         Resource componentTypeFromDiagram = graph.getPossibleObject(configuration, STR.Defines);
252                         if (componentTypeFromDiagram != null
253                                 && componentTypeFromSymbol.equals(componentTypeFromDiagram)) {
254                             return Messages.PopulateElementDropParticipant_CannotInstantiateUserComponent;
255                         }
256                     }
257                 }
258
259                 return null;
260             }
261         });
262     }
263
264     @Override
265     public void dragExit(DropTargetEvent dte, IDnDContext dp) {
266         // System.out.println("exit");
267     }
268
269     @Override
270     public void dragOver(DropTargetDragEvent dtde, IDnDContext dp) {
271         // System.out.println("over");
272     }
273
274     private IElement tryPick(Point p) {
275
276         Point2D canvas = transformUtil.controlToCanvas(p, null);
277         
278         assertDependencies();
279
280         PickRequest     req                     = new PickRequest(canvas);
281         req.pickPolicy = PickRequest.PickPolicy.PICK_INTERSECTING_OBJECTS;
282         List<IElement>  picks                   = new ArrayList<IElement>();
283         pickContext.pick(diagram, req, picks);
284
285         if(picks.size() == 1) return picks.iterator().next();
286         
287         return null;
288         
289     }
290
291     @Override
292     public void drop(DropTargetDropEvent dtde, final IDnDContext dp) {
293         TimeLogger.resetTimeAndLog(getClass(), "drop"); //$NON-NLS-1$
294
295         final IDiagram d = getHint(DiagramHints.KEY_DIAGRAM);
296         if (d == null)
297             return;
298
299         IElement pick = tryPick(dtde.getLocation()); 
300         if(pick != null) {
301                 
302                         final List<WorkbenchSelectionElement> wses = new ArrayList<WorkbenchSelectionElement>();
303                         
304                         for(IDragItem i : dp.toArray())
305                                 if(i instanceof WSEDragItem)
306                                         wses.add(((WSEDragItem)i).getObject());
307
308                 final Resource element = (Resource)ElementUtils.getData(d, pick);
309                 if(element != null && !wses.isEmpty()) {
310                 
311                 try {
312                         
313                                         Simantics.getSession().syncRequest(new WriteRequest() {
314
315                                                 @Override
316                                                 public void perform(WriteGraph graph) throws DatabaseException {
317                                                         
318                                                         DiagramResource DIA = DiagramResource.getInstance(graph);
319                                                         
320                                                 Simantics.invokeSCLWrite(graph, element, DIA.symbolDropHandler, wses);
321                                                 
322                                                 }
323                                                 
324                                         });
325                                         
326                                 } catch (DatabaseException e) {
327                                         LOGGER.error("symbolDropHandler invocation failed", e);
328                                 }
329                 
330                 return;
331                 
332                 }
333                 
334
335         }
336         
337         Runnable creator = () -> {
338             DiagramUtils.mutateDiagram(d, m -> {
339                 IDragItem items[] = dp.toArray();
340
341                 for (IDragItem i : items) {
342                     if (!(i instanceof ElementClassDragItem))
343                         continue;
344
345                     ElementClassDragItem res = (ElementClassDragItem) i;
346                     ElementClass ec = res.getElementClass();
347
348                     Point2D pos = dp.getItemPosition(i);
349                     // System.out.println(pos);
350                     assert (pos != null);
351
352                     IElement element = m.newElement(ec);
353                     element.setHints(res.getHintContext().getHints());
354
355                     setupDroppedElement(element, pos);
356
357                     // Remove only the drag items we've processed.
358                     dp.remove(i);
359                 }
360             });
361         };
362
363         selectNewDiagramContentAfter(d, part, creator);
364
365         getContext().getContentContext().setDirty();
366     }
367
368     protected void selectNewDiagramContentAfter(IDiagram d, MPart activatePart, Runnable diagramModifier) {
369         try {
370             Resource diagramResource = d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
371             final DiagramContentTracker tracker = diagramResource == null ? null
372                     : DiagramContentTracker.start(getContext(), Simantics.getSession(), diagramResource);
373
374             diagramModifier.run();
375
376             if (tracker != null) {
377                 // Get difference of diagram contents to find out what was added.
378                 DiagramContentChanges changes = tracker.update();
379                 Set<Resource> addedElements = changes.pick(changes.elements, Change.ADDED);
380                 if (!addedElements.isEmpty()) {
381                     new DiagramSelectionUpdater(getContext())
382                     .setNewSelection(0, addedElements)
383                     .setOneshot(true)
384                     .track();
385                     if (activatePart != null)
386                         E4WorkbenchUtils.activatePart(activatePart);
387                 }
388             }
389         } catch (DatabaseException e) {
390             Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.PopulateElementDropParticipant_ActivatorDiagramContentTrackingFailed, e));
391         }
392     }
393
394     protected void setupDroppedElement(IElement element, Point2D dropPos) {
395         // This works only for elements without parents.
396         ISnapAdvisor snapAdvisor = getContext().getHintStack().getHint(DiagramHints.SNAP_ADVISOR);
397         if(snapAdvisor != null)
398             snapAdvisor.snap(dropPos);
399
400         IElement parent = element.getHint(ElementHints.KEY_PARENT_ELEMENT);
401         if (parent != null) {
402             Point2D parentPos = ElementUtils.getPos(parent);
403             Point2D pos = new Point2D.Double(dropPos.getX() - parentPos.getX(), dropPos.getY() - parentPos.getY());
404             ElementUtils.setPos(element, pos);
405         } else {
406             ElementUtils.setPos(element, dropPos);
407         }
408     }
409
410     @Override
411     public void dropActionChanged(DropTargetDragEvent dtde, IDnDContext dp) {
412         dtde.acceptDrag(DnDConstants.ACTION_COPY);
413     }
414
415     @Override
416     public int getAllowedOps() {
417         return DnDConstants.ACTION_COPY;
418     }
419     
420     @Override
421     public double getPriority() {
422         return 10.0;
423     }
424
425 }