]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.modeling.ui/src/org/simantics/modeling/ui/diagramEditor/e4/PopulateElementDropParticipant.java
Externalize strings
[simantics/platform.git] / bundles / org.simantics.modeling.ui / src / org / simantics / modeling / ui / diagramEditor / e4 / PopulateElementDropParticipant.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 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.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;
86
87 /**
88  * This participant populates Elements from ElementClass-resources drops
89  */
90 public class PopulateElementDropParticipant extends AbstractDiagramParticipant implements IDropTargetParticipant {
91
92     @Dependency PickContext pickContext;
93     @Dependency TransformUtil transformUtil;
94         
95     protected GraphToDiagramSynchronizer synchronizer;
96     protected MPart part;
97
98     public PopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer) {
99         this(synchronizer, null);
100     }
101
102     public PopulateElementDropParticipant(GraphToDiagramSynchronizer synchronizer, MPart part) {
103         this.synchronizer = synchronizer;
104         this.part = part;
105     }
106
107     @Override
108     public void dragEnter(DropTargetDragEvent dtde, IDnDContext dp) {
109         if (diagram == null)
110             return;
111
112         Transferable tr = dtde.getTransferable();
113         if (tr.isDataFlavorSupported(LocalObjectTransferable.FLAVOR)) {
114             // System.out.println("joo");
115             Object obj = null;
116
117             // This must be done to have SWT transfer set the source data
118             try {
119                 obj = tr.getTransferData(LocalObjectTransferable.FLAVOR);
120                 // System.out.println("GOT FROM AWT: " + obj);
121             } catch (UnsupportedFlavorException e) {
122                 // TODO Auto-generated catch block
123                 e.printStackTrace();
124             } catch (IOException e) {
125                 // TODO Auto-generated catch block
126                 e.printStackTrace();
127             }
128
129             // Check SWT
130             if (!(obj instanceof IStructuredSelection)) {
131                 obj = LocalObjectTransfer.getTransfer().getObject();
132                 // System.out.println("GOT FROM SWT: " + obj);
133             }
134
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);
141                             if (ec != null) {
142                                 dp.add(new ElementClassDragItem(ec));
143                             } else {
144                                 Resource r = (Resource) ((IAdaptable) elm).getAdapter(Resource.class);
145                                 if (r != null) {
146                                     if (elm instanceof ISymbolItem) {
147                                         /* FIXME fix this check 
148                                         ISymbolItem symbol = (ISymbolItem) elm;
149                                         Resource dia = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
150                                         try {
151                                             if (!DiagramTypeUtils.symbolAllowedOnDiagram(synchronizer.getSession(), symbol, dia)) {
152                                                 // Deny dragging of this symbol
153                                                 continue;
154                                             }
155                                         } catch (DatabaseException e) {
156                                             e.printStackTrace();
157                                             continue;
158                                         }*/
159                                     }
160
161                                     try {
162                                         String valid = validateDrop(synchronizer.getSession(), r,
163                                                 diagram.<Resource> getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE));
164                                         if (valid == null) {
165                                             ElementClassDragItem item = new ElementClassDragItem(synchronizer.getNodeClass(r));
166                                             item.getHintContext().setHint(ElementHints.KEY_TRANSFORM, AffineTransform.getScaleInstance(1, 1));
167                                             dp.add(item);
168                                         }
169                                     } catch (DatabaseException e) {
170                                         // Ignore node-class retrieval failures.
171                                         //System.out.println("error: " + e.getMessage());
172                                     }
173                                 }
174                             }
175                         }
176                     }
177
178                     // Let the default logic handle out how many columns to use.
179                     dp.getHints().removeHint(DnDHints.KEY_DND_GRID_COLUMNS);
180                 }
181             }
182
183             return;
184         }
185
186         if (tr.isDataFlavorSupported(ElementClassTransferable.FLAVOR)) {
187             ResourceElementClassTransferData dada;
188             try {
189                 dada = (ResourceElementClassTransferData) tr.getTransferData(ElementClassTransferable.FLAVOR);
190             } catch (UnsupportedFlavorException e) {
191                 throw new Error(e);
192             } catch (IOException e) {
193                 throw new Error(e);
194             }
195             Session s = synchronizer.getSession();
196             try {
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)));
201                 }
202             } catch (DatabaseException e) {
203                 throw new RuntimeException(e);
204             }
205
206             return;
207         }
208     }
209
210     private String validateDrop(RequestProcessor processor, final Resource draggedResource, final Resource dropTarget) throws DatabaseException {
211         return processor.syncRequest(new UniqueRead<String>() {
212             @Override
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);
220
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) });
230                 }
231
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;
241                     }
242                 }
243
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;
252                         }
253                     }
254                 }
255
256                 return null;
257             }
258         });
259     }
260
261     @Override
262     public void dragExit(DropTargetEvent dte, IDnDContext dp) {
263         // System.out.println("exit");
264     }
265
266     @Override
267     public void dragOver(DropTargetDragEvent dtde, IDnDContext dp) {
268         // System.out.println("over");
269     }
270
271     private IElement tryPick(Point p) {
272
273         Point2D canvas = transformUtil.controlToCanvas(p, null);
274         
275         assertDependencies();
276
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);
281
282         if(picks.size() == 1) return picks.iterator().next();
283         
284         return null;
285         
286     }
287
288     @Override
289     public void drop(DropTargetDropEvent dtde, final IDnDContext dp) {
290         TimeLogger.resetTimeAndLog(getClass(), "drop"); //$NON-NLS-1$
291
292         final IDiagram d = getHint(DiagramHints.KEY_DIAGRAM);
293         if (d == null)
294             return;
295
296         IElement pick = tryPick(dtde.getLocation()); 
297         if(pick != null) {
298                 
299                         final List<WorkbenchSelectionElement> wses = new ArrayList<WorkbenchSelectionElement>();
300                         
301                         for(IDragItem i : dp.toArray())
302                                 if(i instanceof WSEDragItem)
303                                         wses.add(((WSEDragItem)i).getObject());
304
305                 final Resource element = (Resource)ElementUtils.getData(d, pick);
306                 if(element != null && !wses.isEmpty()) {
307                 
308                 try {
309                         
310                                         Simantics.getSession().syncRequest(new WriteRequest() {
311
312                                                 @Override
313                                                 public void perform(WriteGraph graph) throws DatabaseException {
314                                                         
315                                                         DiagramResource DIA = DiagramResource.getInstance(graph);
316                                                         
317                                                 Simantics.invokeSCLWrite(graph, element, DIA.symbolDropHandler, wses);
318                                                 
319                                                 }
320                                                 
321                                         });
322                                         
323                                 } catch (DatabaseException e) {
324                                         Logger.defaultLogError(e);
325                                 }
326                 
327                 return;
328                 
329                 }
330                 
331
332         }
333         
334         Runnable creator = () -> {
335             DiagramUtils.mutateDiagram(d, m -> {
336                 IDragItem items[] = dp.toArray();
337
338                 for (IDragItem i : items) {
339                     if (!(i instanceof ElementClassDragItem))
340                         continue;
341
342                     ElementClassDragItem res = (ElementClassDragItem) i;
343                     ElementClass ec = res.getElementClass();
344
345                     Point2D pos = dp.getItemPosition(i);
346                     // System.out.println(pos);
347                     assert (pos != null);
348
349                     IElement element = m.newElement(ec);
350                     element.setHints(res.getHintContext().getHints());
351
352                     setupDroppedElement(element, pos);
353
354                     // Remove only the drag items we've processed.
355                     dp.remove(i);
356                 }
357             });
358         };
359
360         selectNewDiagramContentAfter(d, part, creator);
361
362         getContext().getContentContext().setDirty();
363     }
364
365     protected void selectNewDiagramContentAfter(IDiagram d, MPart activatePart, Runnable diagramModifier) {
366         try {
367             Resource diagramResource = d.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
368             final DiagramContentTracker tracker = diagramResource == null ? null
369                     : DiagramContentTracker.start(getContext(), Simantics.getSession(), diagramResource);
370
371             diagramModifier.run();
372
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)
380                     .setOneshot(true)
381                     .track();
382                     if (activatePart != null)
383                         E4WorkbenchUtils.activatePart(activatePart);
384                 }
385             }
386         } catch (DatabaseException e) {
387             Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.PopulateElementDropParticipant_ActivatorDiagramContentTrackingFailed, e));
388         }
389     }
390
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);
396
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);
402         } else {
403             ElementUtils.setPos(element, dropPos);
404         }
405     }
406
407     @Override
408     public void dropActionChanged(DropTargetDragEvent dtde, IDnDContext dp) {
409         dtde.acceptDrag(DnDConstants.ACTION_COPY);
410     }
411
412     @Override
413     public int getAllowedOps() {
414         return DnDConstants.ACTION_COPY;
415     }
416     
417     @Override
418     public double getPriority() {
419         return 10.0;
420     }
421
422 }