]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.diagram/src/org/simantics/diagram/handler/CopyPasteHandler.java
Merge branch 'feature/funcwrite'
[simantics/platform.git] / bundles / org.simantics.diagram / src / org / simantics / diagram / handler / CopyPasteHandler.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.diagram.handler;
13
14 import java.awt.Color;
15 import java.awt.event.KeyEvent;
16 import java.awt.geom.AffineTransform;
17 import java.awt.geom.Point2D;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Set;
23
24 import org.eclipse.core.runtime.IStatus;
25 import org.eclipse.core.runtime.Status;
26 import org.eclipse.jface.action.IStatusLineManager;
27 import org.eclipse.swt.widgets.Display;
28 import org.eclipse.ui.IPartListener;
29 import org.eclipse.ui.IWorkbenchPart;
30 import org.eclipse.ui.IWorkbenchPartSite;
31 import org.eclipse.ui.PlatformUI;
32 import org.simantics.Simantics;
33 import org.simantics.databoard.Bindings;
34 import org.simantics.db.ReadGraph;
35 import org.simantics.db.Resource;
36 import org.simantics.db.WriteGraph;
37 import org.simantics.db.common.request.WriteRequest;
38 import org.simantics.db.common.utils.OrderedSetUtils;
39 import org.simantics.db.exception.DatabaseException;
40 import org.simantics.db.layer0.util.ClipboardUtils;
41 import org.simantics.db.layer0.util.SimanticsClipboard;
42 import org.simantics.db.layer0.util.SimanticsClipboard.Representation;
43 import org.simantics.db.layer0.util.SimanticsKeys;
44 import org.simantics.db.layer0.variable.Variable;
45 import org.simantics.db.layer0.variable.Variables;
46 import org.simantics.db.request.Read;
47 import org.simantics.diagram.Logger;
48 import org.simantics.diagram.content.Change;
49 import org.simantics.diagram.content.ConnectionUtil;
50 import org.simantics.diagram.content.DiagramContentChanges;
51 import org.simantics.diagram.content.DiagramContentTracker;
52 import org.simantics.diagram.internal.Activator;
53 import org.simantics.diagram.stubs.DiagramResource;
54 import org.simantics.diagram.stubs.G2DResource;
55 import org.simantics.diagram.synchronization.graph.DiagramGraphUtil;
56 import org.simantics.diagram.synchronization.runtime.DiagramSelectionUpdater;
57 import org.simantics.diagram.ui.DiagramModelHints;
58 import org.simantics.g2d.canvas.ICanvasContext;
59 import org.simantics.g2d.canvas.impl.AbstractCanvasParticipant;
60 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
61 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGCleanup;
62 import org.simantics.g2d.canvas.impl.SGNodeReflection.SGInit;
63 import org.simantics.g2d.connection.ConnectionEntity;
64 import org.simantics.g2d.connection.handler.ConnectionHandler;
65 import org.simantics.g2d.diagram.IDiagram;
66 import org.simantics.g2d.diagram.handler.Topology;
67 import org.simantics.g2d.diagram.handler.Topology.Connection;
68 import org.simantics.g2d.diagram.handler.Topology.Terminal;
69 import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
70 import org.simantics.g2d.diagram.participant.Selection;
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.element.handler.BendsHandler;
76 import org.simantics.g2d.element.handler.EdgeVisuals.EdgeEnd;
77 import org.simantics.g2d.element.handler.Move;
78 import org.simantics.g2d.element.handler.TerminalTopology;
79 import org.simantics.g2d.element.handler.Transform;
80 import org.simantics.g2d.elementclass.FlagHandler;
81 import org.simantics.g2d.participant.GridPainter;
82 import org.simantics.g2d.participant.MouseUtil;
83 import org.simantics.g2d.participant.MouseUtil.MouseInfo;
84 import org.simantics.layer0.Layer0;
85 import org.simantics.modeling.ModelingResources;
86 import org.simantics.operation.Layer0X;
87 import org.simantics.project.IProject;
88 import org.simantics.scenegraph.INode;
89 import org.simantics.scenegraph.ParentNode;
90 import org.simantics.scenegraph.g2d.G2DParentNode;
91 import org.simantics.scenegraph.g2d.IG2DNode;
92 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
93 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;
94 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyReleasedEvent;
95 import org.simantics.scenegraph.g2d.events.MouseEvent;
96 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseEnterEvent;
97 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseExitEvent;
98 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseMovedEvent;
99 import org.simantics.scenegraph.g2d.events.command.Command;
100 import org.simantics.scenegraph.g2d.events.command.CommandEvent;
101 import org.simantics.scenegraph.g2d.events.command.Commands;
102 import org.simantics.scenegraph.g2d.nodes.LinkNode;
103 import org.simantics.scenegraph.g2d.nodes.LocalDelegateNode;
104 import org.simantics.scenegraph.g2d.nodes.SingleElementNode;
105 import org.simantics.scenegraph.utils.NodeMapper;
106 import org.simantics.utils.datastructures.collections.CollectionUtils;
107 import org.simantics.utils.datastructures.hints.HintListenerAdapter;
108 import org.simantics.utils.datastructures.hints.IHintContext.Key;
109 import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;
110 import org.simantics.utils.datastructures.hints.IHintListener;
111 import org.simantics.utils.datastructures.hints.IHintObservable;
112 import org.simantics.utils.logging.TimeLogger;
113 import org.simantics.utils.threads.SWTThread;
114 import org.simantics.utils.threads.ThreadUtils;
115 import org.simantics.utils.ui.ErrorLogger;
116 import org.simantics.utils.ui.SWTUtils;
117
118 /**
119  * CopyPasteHandler is a canvas handler for Commands.CUT, Commands.COPY and
120  * Commands.PASTE commands for an IDiagram.
121  * 
122  * <p>
123  * The handler attempts to copy/paste the current selection for pointer 0,
124  * meaning {@link Selection#SELECTION0}.
125  * </p>
126  * 
127  * <p>
128  * The handler logic follows the specifications at <a
129  * href="http://www.simantics.org/wiki/index.php/UC:Copy_Item" >UC:Copy Item</a>
130  * and <a href="http://www.simantics.org/wiki/index.php/UC:Cut_Item" >UC:Cut
131  * Item</a>.
132  * </p>
133  * 
134  * @see Selection current diagram selection source
135  * 
136  * @author Tuukka Lehtonen
137  * 
138  *         FIXME: translucent ghosting makes rendering REALLY sluggish, add a
139  *         timer that makes the ghost opaque when the user is interacting and
140  *         translucent only when still for a while.
141  */
142 public class CopyPasteHandler extends AbstractDiagramParticipant {
143
144     public static final Key KEY_CUT_SELECTION_FRAME_COLOR      = new KeyOf(Color.class, "CUT_SELECTION_FRAME_COLOR");
145     public static final Key KEY_CUT_SELECTION_CONTENT_COLOR    = new KeyOf(Color.class, "CUT_SELECTION_CONTENT_COLOR");
146     public static final Key KEY_COPIED_SELECTION_FRAME_COLOR   = new KeyOf(Color.class, "COPY_SELECTION_FRAME_COLOR");
147     public static final Key KEY_COPIED_SELECTION_CONTENT_COLOR = new KeyOf(Color.class, "COPY_SELECTION_CONTENT_COLOR");
148
149     /**
150      * A key for storing the current selection within the currently active
151      * project for copy/paste implementation.
152      */
153     private static final Key              KEY_DIAGRAM_SELECTION              = DiagramSelectionRepresentation.KEY_DIAGRAM_SELECTION;
154
155     private static final boolean          DEBUG                              = false;
156     private static final boolean          DEBUG_SELECTION_UPDATE             = false;
157
158     public static final int               COPY_GHOSTING_PAINT_PRIORITY       = 600;
159
160     protected static final int            HIGHLIGHT_PAINT_PRIORITY           = 500;
161
162     @Dependency
163     protected Selection                   sel;
164     @Dependency
165     protected MouseUtil                   mouseUtil;
166
167     protected final IStatusLineManager    statusLine;
168     protected final CopyPasteStrategy     strategy;
169     protected IWorkbenchPartSite          site;
170     protected IWorkbenchPartSite          listenedSite;
171
172     /**
173      * Workbench part listener for {@link #listenedSite} to keep proper track of
174      * whether this part is focused or not.
175      */
176     IPartListener partListener = new IPartListener() {
177         @Override
178         public void partOpened(IWorkbenchPart part) {
179         }
180         @Override
181         public void partDeactivated(IWorkbenchPart part) {
182             if (part == site.getPart())
183                 hasFocus = false;
184         }
185         @Override
186         public void partClosed(IWorkbenchPart part) {
187             // Make sure this listener is removed properly in any case.
188             if (listenedSite != null) {
189                 listenedSite.getPage().removePartListener(partListener);
190                 listenedSite = null;
191             }
192         }
193         @Override
194         public void partBroughtToTop(IWorkbenchPart part) {
195         }
196         @Override
197         public void partActivated(IWorkbenchPart part) {
198             if (part == site.getPart())
199                 hasFocus = true;
200         }
201     };
202
203     /**
204      * Indicates whether CopyPasteHandler thinks that {@link #site} has focus. 
205      */
206     protected boolean                     hasFocus                           = false;
207
208     protected AbstractCanvasParticipant   highlightMode                      = null;
209     private IProject                      observedProject                    = null;
210
211     /**
212      * A counter for how many times pasting has been performed without mouse and
213      * ghosting or how many times paste has been performed without moving the
214      * mouse on the diagram. This is used to offset the paste position
215      * accordingly so that copied elements don't wind up directly on top of each
216      * other.
217      */
218     private int                           pasteWithoutMovingGhostCounter     = 0;
219
220     /**
221      * An offset used when pasting without mouse/ghosting. It forces keyboard
222      * pastes to stack up on top of the latest paste performed with
223      * mouse/ghosting.
224      */
225     private final Point2D                 pasteOffset                        = new Point2D.Double(0, 0);
226
227     /**
228      * Stores the last MouseInfo for mouse 0 from the time of the previous
229      * received mouse event. Used for deciding the paste position.
230      * 
231      * @see #getPastePos(DiagramSelection)
232      */
233     private MouseInfo                     mouseInfo;
234
235     /**
236      * Scale to use for pasted diagram monitors from variables.
237      */
238     private double                        monitorScale = 0.2;
239
240     /**
241      * For updating the diagram selection after graph changes.
242      */
243     private DiagramSelectionUpdater       selectionUpdater                   = null;
244
245     public CopyPasteHandler() {
246         this(new DefaultCopyPasteStrategy());
247     }
248
249     public CopyPasteHandler(CopyPasteStrategy strategy) {
250         this(strategy, null);
251     }
252
253     public CopyPasteHandler(IStatusLineManager statusLine) {
254         this(new DefaultCopyPasteStrategy(), statusLine);
255     }
256
257     public CopyPasteHandler(CopyPasteStrategy strategy, IStatusLineManager statusLine) {
258         this.strategy = strategy != null ? strategy : new DefaultCopyPasteStrategy();
259         this.statusLine = statusLine;
260     }
261
262     public CopyPasteHandler(CopyPasteStrategy strategy, IStatusLineManager statusLine, double monitorScale) {
263         this.strategy = strategy != null ? strategy : new DefaultCopyPasteStrategy();
264         this.statusLine = statusLine;
265         setMonitorScale(monitorScale);
266     }
267
268     public CopyPasteHandler setMonitorScale(double scale) {
269         this.monitorScale = scale;
270         return this;
271     }
272
273     public CopyPasteHandler setWorkbenchSite(IWorkbenchPartSite site) {
274         this.site = site;
275         return this;
276     }
277
278     protected boolean isPasteAllowed() {
279         return listenedSite == null || hasFocus;
280     }
281
282     @Override
283     public void addedToContext(ICanvasContext ctx) {
284         super.addedToContext(ctx);
285         addProjectListener(peekProject());
286
287         listenedSite = site;
288         if (listenedSite != null) {
289             listenedSite.getPage().addPartListener(partListener);
290         }
291     }
292
293     @Override
294     public void removedFromContext(ICanvasContext ctx) {
295         // Remove project selection if its ours to prevent leaking memory.
296         DiagramSelection ds = getProjectSelection();
297         if (ds.getSourceCanvas() == ctx) {
298             removeProjectSelection();
299         }
300
301         if (listenedSite != null) {
302             listenedSite.getPage().removePartListener(partListener);
303             listenedSite = null;
304         }
305
306         removeProjectListener();
307         super.removedFromContext(ctx);
308     }
309
310     @Override
311     protected void onDiagramSet(IDiagram newDiagram, IDiagram oldDiagram) {
312         if (oldDiagram != null) {
313             if (selectionUpdater != null) {
314                 selectionUpdater.untrack();
315                 selectionUpdater = null;
316             }
317         }
318         if (newDiagram != null) {
319             selectionUpdater = new DiagramSelectionUpdater(getContext(), newDiagram).track();
320         }
321     }
322
323     IHintListener projectDiagramSelectionListener = new HintListenerAdapter() {
324         @Override
325         public void hintChanged(IHintObservable sender, Key key, Object oldValue, final Object newValue) {
326             //System.out.println(this + ": " + sender + ": " + newValue);
327             ICanvasContext ctx = getContext();
328             if (ctx != null && hasHighlight()) {
329                 //System.out.println(this + " HAS HIGHLIGHT");
330                 if (newValue == null || ((DiagramSelection) newValue).getSourceCanvas() != ctx) {
331                     //System.out.println(this + " REMOVING HIGHLIGHT");
332                     ctx.getThreadAccess().asyncExec(new Runnable() {
333                         @Override
334                         public void run() {
335                             removeHighlight();
336                         }
337                     });
338                 }
339             }
340         }
341     };
342
343     private void addProjectListener(IProject observable) {
344         if (observable != null) {
345             observable.addKeyHintListener(KEY_DIAGRAM_SELECTION, projectDiagramSelectionListener);
346             observedProject = observable;
347         }
348     }
349
350     private void removeProjectListener() {
351         if (observedProject != null) {
352             observedProject.removeKeyHintListener(KEY_DIAGRAM_SELECTION, projectDiagramSelectionListener);
353             observedProject = null;
354         }
355     }
356
357     IProject getProject() {
358         return Simantics.getProject();
359     }
360
361     IProject peekProject() {
362         return Simantics.peekProject();
363     }
364
365     public DiagramSelection getClipboardDiagramSelection() {
366         for (Set<Representation> content : Simantics.getClipboard().getContents()) {
367             try {
368                 DiagramSelection sel = ClipboardUtils.accept(content, DiagramSelectionRepresentation.KEY_DIAGRAM_SELECTION);
369                 if (sel != null)
370                     return sel;
371             } catch (DatabaseException e) {
372                 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to retrieve clipboard content.", e));
373             }
374         }
375         return DiagramSelection.EMPTY;
376     }
377
378     protected DiagramSelection getProjectSelection() {
379         IProject p = peekProject();
380         if (p == null)
381             return DiagramSelection.EMPTY;
382         DiagramSelection ds = p.getHint(KEY_DIAGRAM_SELECTION);
383         return ds != null ? ds : DiagramSelection.EMPTY;
384     }
385
386     protected void setDiagramSelection(DiagramSelection selection) {
387         setProjectSelection(selection);
388         strategy.copyToClipboard(selection);
389     }
390
391     protected void setProjectSelection(DiagramSelection selection) {
392         assert selection != null;
393         IProject p = getProject();
394         if (p == null)
395             throw new IllegalStateException("no active project for selection");
396         clearSG();
397         pasteWithoutMovingGhostCounter = 0;
398         pasteOffset.setLocation(0, 0);
399         p.setHint(KEY_DIAGRAM_SELECTION, selection);
400     }
401
402     protected void removeProjectSelection() {
403         setProjectSelection(DiagramSelection.EMPTY);
404         removeHighlight();
405         clearSG();
406         setDirty();
407     }
408
409     /**
410      * This DELETE command handler is required to remove any diagram selections
411      * when modules are deleted. This will prevent extra highlight painting from
412      * being left over in case a module marked for copying is deleted.
413      */
414     @EventHandler(priority = 100)
415     public boolean handleDelete(CommandEvent e) {
416         if (e.command.equals( Commands.DELETE) ) {
417             if (highlightMode != null) {
418                 message(null);
419                 removeProjectSelection();
420                 return false;
421             }
422         }
423         return false;
424     }
425
426     @EventHandler(priority = 0)
427     public boolean handleKey(org.simantics.scenegraph.g2d.events.KeyEvent e) {
428         if (e.keyCode == KeyEvent.VK_CONTROL) {
429             DiagramSelection ds = getProjectSelection();
430             if (!ds.isEmpty()) {
431                 if (e instanceof KeyPressedEvent) {
432                     if (ds.isCut())
433                         message("Move selection");
434                     else
435                         message("Paste selection");
436                     updateSG(ds);
437                 } else if (e instanceof KeyReleasedEvent) {
438                     selectedMessage(ds);
439                     hideSG(ds);
440                 }
441                 setDirty();
442             }
443         }
444         return false;
445     }
446
447     @EventHandler(priority = 0)
448     public boolean handleCommand(CommandEvent e) {
449         if (e.command.equals( Commands.CANCEL) ) {
450             DiagramSelection s = getProjectSelection();
451             if (highlightMode != null || !s.isEmpty()) {
452                 message(null);
453                 removeProjectSelection();
454                 return true;
455             }
456             return false;
457         }
458         if (e.command.equals( Commands.CUT ) || e.command.equals( Commands.COPY )) {
459             boolean ret = initiateCopy( e.command.equals( Commands.CUT ) );
460             if (!ret)
461                 removeProjectSelection();
462             return ret;
463         }
464         // Must have focus in order to paste! If mouse has left the editor, no
465         // pastes should be performed.
466         if (isPasteAllowed() && e.command.equals( Commands.PASTE )) {
467             DiagramSelection ds = getClipboardDiagramSelection();
468             if (ds.isEmpty()) {
469                 return tryPasteMonitors();
470             }
471             return paste(e.command, ds);
472         }
473         return false;
474     }
475
476     protected boolean initiateCopy(boolean cut) {
477         //System.out.println("INITIATING COPY");
478         int selectionId = 0;
479
480         Set<IElement> ss = sel.getSelection(selectionId);
481         Point2D copyPos = getCopyStartPos(ss);
482         if (ss.isEmpty() || copyPos == null) {
483             message("Nothing to " + (cut ? "cut" : "copy"));
484             return false;
485         }
486
487         // Validate selection, don't initiate copy if selection is invalid.
488         ElementAssortment ea = new ElementAssortment(ss);
489         String error = fixAssortment(ea, cut);
490
491         if (error != null) {
492             message(error);
493             return false;
494         }
495
496         pruneAssortment(ea, cut);
497         if (ea.isEmpty()) {
498             message("Nothing to " + (cut ? "cut" : "copy"));
499             return false;
500         }
501
502         // Allow the possible CopyStrategy to filter the copied element
503         // assortment also.
504         if (strategy instanceof CopyStrategy) {
505             if (DEBUG)
506                 System.out.println("Commencing CopyStrategy filtering with " + ea);
507             IStatus status = ((CopyStrategy) strategy).copy(new CopyOperation(getContext(), ea, cut));
508             if (!status.isOK()) {
509                 switch (status.getSeverity()) {
510                 case IStatus.CANCEL:
511                 case IStatus.WARNING:
512                     message(status.getMessage());
513                     break;
514                 case IStatus.ERROR:
515                     error(status.getMessage());
516                     break;
517                 }
518                 return false;
519             }
520         }
521
522         if (DEBUG)
523             System.out.println("Start copy with " + ea);
524
525         // Treat OTHER type elements as disconnected floating graphical elements
526         // that are always copied.
527
528         // Anything with connection parts cannot be copied
529         if (!cut && ea.containsAny(CopyPasteUtil.CONNECTION_PARTS)) {
530             error("Cannot copy connection segments nor branch points.");
531             return false;
532         }
533 //        if (ea.contains(CopyPasteUtil.MONITORS)) {
534 //            // TODO: allow copying of monitors, means fixing the component reference relations
535 //            error("Monitor " + (cut ? "cut" : "copy") + " not supported yet.");
536 //            return false;
537 //        }
538
539         // Pre-validate flag selection cases
540         if (ea.contains(CopyPasteUtil.FLAGS)) {
541             if (cut) {
542                 // Allow cutting of single flags or cutting of any amount of
543                 // flags within a single diagram.
544             } else {
545 //                // Deny flag copy if other kinds of elements are selected.
546 //                if (ea.containsAny(NOT_FLAGS)) {
547 //                    return false;
548 //                }
549                 // Only copy flags without correspondence for now.
550                 if (CopyPasteUtil.isFlagsOnlySelection(ea)) {
551                     if (!CopyPasteUtil.checkFlagsCorrespondences(ea.flags, false)) {
552                         error("Cannot copy flag that already has a correspondence.");
553                         return false;
554                     }
555                 }
556             }
557         }
558
559         // Selection is valid, go ahead and initiate a copy operation.
560         Resource sourceDiagram = diagram.<Resource>getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
561         DiagramSelection ds = new DiagramSelection(getContext(), sourceDiagram, ea.getAll(), cut, copyPos);
562         setDiagramSelection(ds);
563
564         removeHighlight();
565         highlightMode = new HighlightMode(ds, selectionId, HIGHLIGHT_PAINT_PRIORITY);
566         getContext().add(highlightMode);
567
568         selectedMessage(ds);
569
570 //        System.out.println("INITIATED COPY: " + ds);
571         return true;
572     }
573
574     public boolean paste(Command command, DiagramSelection ds) {
575         if (ds.isEmpty()) {
576             message(null);
577             return false;
578         }
579
580         TimeLogger.resetTimeAndLog(getClass(), "paste");
581
582         ElementObjectAssortment ea = ds.getAssortment();
583
584         if (DEBUG)
585             System.out.println("Initiate paste with " + ea);
586
587         try {
588             if (CopyPasteUtil.isFlagsOnlySelection(ea)) {
589                 // Do not copy if any of the flags already have a correspondence.
590                 if (!CopyPasteUtil.onlyFlagsWithoutCorrespondence(Simantics.getSession(), ea))
591                     return true;
592
593                 if (ds.isCut()) {
594                     normalPaste(command, ds, ea, true);
595                     removeHighlight();
596                     setDiagramSelection(DiagramSelection.EMPTY);
597                     resetSourceSelection(ds);
598                 } else {
599                     normalPaste(command, ds, ea, false);
600                     // There is no point in leaving the old copy selection hanging
601                     // around after copying a flag since it is a one shot operation.
602                     removeHighlight();
603                     setDiagramSelection(DiagramSelection.EMPTY);
604                 }
605             } else {
606                 if (ds.isCut()) {
607                     normalPaste(command, ds, ea, true);
608                     removeHighlight();
609                     setDiagramSelection(DiagramSelection.EMPTY);
610                     resetSourceSelection(ds);
611                 } else {
612                     normalPaste(command, ds, ea, false);
613
614 //                // This is necessary to keep the ghost diagram properly up-to-date
615 //                // after paste operations.
616 //                setProjectSelection(ds.remutate());
617                 }
618             }
619
620             message(null);
621
622         } catch (PasteException e) {
623             error( e.getLocalizedMessage() );
624             ErrorLogger.defaultLog( new Status(IStatus.INFO, Activator.PLUGIN_ID, "Problem in diagram paste operation, see exception for details.", e) );
625         } catch (DatabaseException e) {
626             error( e.getLocalizedMessage() );
627             ErrorLogger.defaultLog( new Status(IStatus.INFO, Activator.PLUGIN_ID, "Problem in diagram paste operation, see exception for details.", e) );
628         }
629
630         // Clear ghosting
631         clearSG();
632         setDirty();
633
634         return true;
635     }
636
637     /**
638      * In cut/paste cases, the source selection should reset (removed) after the
639      * paste operation has been performed. This method will reset the source
640      * selection of the specified DiagramSelection from the source canvas
641      * context. This will work regardless of which diagram/editor the selection
642      * originates from.
643      * 
644      * @param ds the source selection to reset
645      */
646     void resetSourceSelection(DiagramSelection ds) {
647         ICanvasContext cc = ds.getSourceCanvas();
648         boolean sameDiagram = diagram == ds.getSourceDiagram();
649         if (!sameDiagram && cc != null && !cc.isDisposed()) {
650             for (Selection sourceSelection : cc.getItemsByClass(Selection.class)) {
651                 Collection<IElement> empty = Collections.emptySet();
652                 sourceSelection.setSelection(0, empty);
653             }
654         }
655     }
656
657     private void normalPaste(Command command, DiagramSelection ds, ElementObjectAssortment ea, boolean cut) throws PasteException {
658         final Point2D copyPos = ds.getCopyPos();
659         final Point2D pastePos = getPastePos(ds);
660
661         double dx = pastePos.getX() - copyPos.getX();
662         double dy = pastePos.getY() - copyPos.getY();
663         final Point2D pasteOffset = new Point2D.Double(dx, dy);
664
665         try {
666             // Get diagram contents before the paste operation
667             Resource diagramResource = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
668             final DiagramContentTracker tracker =
669                 diagramResource == null ?
670                         null
671                         : DiagramContentTracker.start(getContext(), Simantics.getSession(), diagramResource);
672
673             strategy.paste(new PasteOperation(command, getContext(), ds.getSourceDiagram(), diagramResource, diagram, ea, cut, pasteOffset));
674
675             if (tracker != null) {
676                 // Get difference of diagram contents to find out what was added.
677                 DiagramContentChanges changes = tracker.update();
678                 selectionUpdater.setNewSelection(0, changes.pick(changes.elements, Change.ADDED));
679                 if (DEBUG_SELECTION_UPDATE)
680                     System.out.println("stored diagram changes @" + System.currentTimeMillis() + ": " + selectionUpdater.getNewSelection());
681             }
682
683         } catch (DatabaseException e) {
684             ErrorLogger.defaultLogError(e);
685         }
686     }
687
688     protected String fixAssortment(ElementAssortment ea, boolean cut) {
689         Topology diagramTopology = diagram.getDiagramClass().getAtMostOneItemOfClass(Topology.class);
690         List<Connection> conns = new ArrayList<Connection>();
691
692         // Include flags whether they are selected or not
693         for (IElement edge : ea.edges) {
694             Connection bc = diagramTopology.getConnection(edge, EdgeEnd.Begin);
695             if (bc != null && bc.node != null) {
696                 if (bc.node.getElementClass().getAtMostOneItemOfClass(FlagHandler.class) != null)
697                     ea.add(ElementType.Flag, bc.node);
698             }
699             Connection ec = diagramTopology.getConnection(edge, EdgeEnd.End);
700             if (ec != null && ec.node != null) {
701                 if (ec.node.getElementClass().getAtMostOneItemOfClass(FlagHandler.class) != null)
702                     ea.add(ElementType.Flag, ec.node);
703             }
704         }
705
706         // Include connections for selected flags if we're not potentially
707         // making flag continuations.
708         if (!CopyPasteUtil.isFlagsOnlySelection(ea)) {
709             for (IElement flag : ea.flags) {
710                 conns.clear();
711                 diagramTopology.getConnections(flag, ElementUtils.getSingleTerminal(flag), conns);
712                 for (Connection conn : conns) {
713                     IElement edge = conn.edge;
714                     ConnectionEntity ce = edge.getHint(ElementHints.KEY_CONNECTION_ENTITY);
715                     ea.add(ElementType.Connection, ce.getConnection());
716                 }
717             }
718         }
719
720         // For each selected connection, make sure that all connected elements
721         // are in the selection, otherwise don't copy the connection.
722         List<IElement> connectionsToRemove = new ArrayList<IElement>(ea.connections.size());
723         for (IElement connection : ea.connections) {
724             ConnectionHandler ch = connection.getElementClass().getSingleItem(ConnectionHandler.class);
725             Collection<Connection> connectors = ch.getTerminalConnections(connection, null);
726             boolean allConnectorsSelected = true;
727             for (Connection c : connectors) {
728                 if (!(ea.nodes.contains(c.node) || ea.flags.contains(c.node) || ea.references.contains(c.node))) {
729                     allConnectorsSelected = false;
730                     break;
731                 }
732             }
733             if (!allConnectorsSelected)
734                 connectionsToRemove.add(connection);
735         }
736         ea.removeAll(ElementType.Connection, connectionsToRemove);
737
738         // Remove external flags whose connection(s) are not included
739         List<IElement> flagsToRemove = new ArrayList<IElement>(ea.flags.size());
740         for (IElement flag : ea.flags) {
741             if (CopyPasteUtil.flagIsExternal(flag)) {
742                 conns.clear();
743                 diagramTopology.getConnections(flag, ElementUtils.getSingleTerminal(flag), conns);
744                 for (Connection conn : conns) {
745                     IElement edge = conn.edge;
746                     ConnectionEntity ce = edge.getHint(ElementHints.KEY_CONNECTION_ENTITY);
747                     IElement connection = ce.getConnection();
748                     if (!ea.connections.contains(connection)) {
749                         flagsToRemove.add(flag);
750                     }
751                 }
752             }
753         }
754         ea.removeAll(ElementType.Flag, flagsToRemove);
755
756         if (cut) {
757             // Issue #1874: Prevent cut/paste for connected components
758             // https://www.simulationsite.net/redmine/issues/1874
759             // Fail if any of the included nodes has connections to it that are not
760             // included in the operation.
761             Collection<Connection> connections = new ArrayList<Connection>();
762             for (IElement node : CollectionUtils.join(ea.nodes, ea.flags)) {
763                 connections.clear();
764                 for (Connection connection : getAllConnections(node, connections)) {
765                     ConnectionEntity ce = connection.edge.getHint(ElementHints.KEY_CONNECTION_ENTITY);
766                     IElement conn = ce.getConnection();
767                     if (ea.connections.contains(conn))
768                         continue;
769
770                     return "Cannot cut a node without all its connections.";
771                 }
772             }
773         }
774
775         // Remove all reference elements from the assortment whose parent elements are not in it.
776         if (!cut) {
777             Collection<IElement> referenceElementsToRemove = new ArrayList<IElement>();
778             for (IElement ref : ea.references) {
779                 IElement parent = ref.getHint(ElementHints.KEY_PARENT_ELEMENT);
780                 if (parent != null) {
781                     if (!ea.all.contains(parent)) {
782                         // Cannot copy reference element whose parent is not copied also.
783                         referenceElementsToRemove.add(ref);
784                     }
785                 } else {
786                     // OK, reference element has no parent. Free to copy/cut in any way.
787                 }
788             }
789             if (!referenceElementsToRemove.isEmpty()) {
790                 ea.removeAll(ElementType.Reference, referenceElementsToRemove);
791                 if (ea.isEmpty()) {
792                     return "Cannot copy reference elements whose parent is not copied.";
793                 }
794             }
795         }
796
797         return null;
798     }
799
800     private Collection<Terminal> getTerminals(IElement node) {
801         ArrayList<Terminal> result = new ArrayList<Terminal>();
802         for (TerminalTopology tt : node.getElementClass().getItemsByClass(TerminalTopology.class))
803             tt.getTerminals(node, result);
804         return result;
805     }
806
807     private Collection<Connection> getAllConnections(IElement node, Collection<Connection> result) {
808         IDiagram diagram = node.getDiagram();
809         Topology topology = diagram.getDiagramClass().getAtMostOneItemOfClass(Topology.class);
810         if (topology == null)
811             return result;
812         for (Terminal t : getTerminals(node))
813             topology.getConnections(node, t, result);
814         return result;
815     }
816
817     /**
818      * Classifies the specified diagram selection elements into categories
819      * appointed by the <code>ElementType</code> enumeration and prunes any
820      * edges from the selection returned assortment whose both ends are not
821      * connected to nodes within the selection.
822      *
823      * @param ea
824      * @return
825      */
826     protected void pruneAssortment(ElementAssortment ea, boolean cut) {
827         // Edges and branch points are never copied as such.
828         // They are always included as parts of copied connections.
829         // Edges can never be transformed or modified in any way as such,
830         // therefore it is safe to do this.
831         ea.clear(ElementType.Edge);
832
833         if (!cut)
834             ea.clear(ElementType.BranchPoint);
835     }
836
837     private Point2D getPastePos(DiagramSelection ds) {
838         MouseInfo mi = mouseUtil.getMouseInfo(0);
839         if (mi == null)
840             mi = mouseInfo;
841
842         if (mi != null) {
843             double xoff = mi.canvasPosition.getX() - ds.getCopyPos().getX();
844             double yoff = mi.canvasPosition.getY() - ds.getCopyPos().getY();
845             if (xoff == pasteOffset.getX() && yoff == pasteOffset.getY()) {
846                 // The mouse has not moved since last paste so let's offset the
847                 // paste down and right.
848                 double counterOffset = getOffsetGridSize() * (++pasteWithoutMovingGhostCounter);
849                 return new Point2D.Double(
850                         mi.canvasPosition.getX() + counterOffset,
851                         mi.canvasPosition.getY() + counterOffset);
852             }
853             pasteWithoutMovingGhostCounter = 0;
854             pasteOffset.setLocation(xoff, yoff);
855             return mi.canvasPosition;
856         } else {
857             //return ds.getCopyPos();
858             Point2D p = ds.getCopyPos();
859             double counterOffset = getOffsetGridSize() * (++pasteWithoutMovingGhostCounter);
860             return new Point2D.Double(
861                     p.getX() + pasteOffset.getX() + counterOffset,
862                     p.getY() + pasteOffset.getY() + counterOffset);
863         }
864     }
865
866     private double getOffsetGridSize() {
867         Double grid = getHint(GridPainter.KEY_GRID_SIZE);
868         return (grid == null || grid == 0) ? 1.0 : grid;
869     }
870
871     /**
872      * @param e
873      * @return
874      */
875     protected static boolean isConnectionOrEdge(IElement e) {
876         ElementClass ec = e.getElementClass();
877         return ec.containsClass(ConnectionHandler.class)|| ec.containsClass(BendsHandler.class);
878     }
879
880     /**
881      * @param e
882      * @return
883      */
884     protected static boolean isMoveable(IElement e) {
885         ElementClass ec = e.getElementClass();
886         return ec.containsClass(Move.class) && ec.containsClass(Transform.class);
887     }
888
889     /**
890      * @param ss
891      * @return <code>null</code> if a point of reference cannot be determined
892      *         for the specified selection.
893      */
894     protected Point2D getCopyStartPos(Set<IElement> ss) {
895 //        MouseInfo mi = mouseUtil.getMouseInfo(0);
896 //        if (mi != null) {
897 //            return (Point2D) mi.canvasPosition.clone();
898 //        }
899
900         // Find bounding rectangle top left corner
901         double mx = Double.MAX_VALUE;
902         double my = Double.MAX_VALUE;
903         for (IElement e : ss) {
904             if (isConnectionOrEdge(e) || !isMoveable(e))
905                 continue;
906
907             //Point2D pos = ElementUtils.getPos(e);
908             Point2D pos = ElementUtils.getAbsolutePos(e);
909             if (pos.getX() < mx)
910                 mx = pos.getX();
911             if (pos.getY() < my)
912                 my = pos.getY();
913         }
914
915         // Find element nearest to the top left corner
916         Point2D nearest = null;
917         double dist = Double.MAX_VALUE;
918         for (IElement e : ss) {
919             if (isConnectionOrEdge(e) || !isMoveable(e))
920                 continue;
921
922             Point2D pos = ElementUtils.getAbsolutePos(e);
923             double dx = pos.getX() - mx;
924             double dy = pos.getY() - my;
925             double d = dx*dx + dy*dy;
926             if (d < dist) {
927                 dist = d;
928                 nearest = pos;
929             }
930         }
931
932         return nearest;
933     }
934
935     private void moveGhostElements(DiagramSelection ds, Point2D pastePos) {
936         Point2D copyPos = ds.getCopyPos();
937         double dx = (pastePos.getX() - copyPos.getX());
938         double dy = (pastePos.getY() - copyPos.getY());
939
940         // Snap delta
941         Point2D snap = CopyPasteUtil.snap(getContext(), new Point2D.Double(dx, dy));
942
943         ghostNode.setTransform(AffineTransform.getTranslateInstance(snap.getX(), snap.getY()));
944         //System.out.println("ghost node: " + ghostNode);
945     }
946
947     protected SingleElementNode ghostNode = null;
948     protected NodeMapper ghostNodeMapper = new NodeMapper();
949
950     @SGInit
951     public void initSG(G2DParentNode parent) {
952         ghostNode = parent.addNode("cut/copy ghost", SingleElementNode.class);
953         ghostNode.setZIndex(COPY_GHOSTING_PAINT_PRIORITY);
954         //ghostNode.setComposite(AlphaComposite.SrcOver.derive(0.40f));
955         ghostNode.setVisible(Boolean.FALSE);
956     }
957
958     @SGCleanup
959     public void cleanupSG() {
960         ghostNode.remove();
961     }
962
963     void clearSG() {
964         ghostNode.removeNodes();
965         ghostNode.setVisible(Boolean.FALSE);
966         ghostNodeMapper.clear();
967     }
968
969     /**
970      * @param selection
971      * @return <code>true</code> if the ghost nodes were hidden and a refresh is
972      *         needed
973      */
974     boolean hideSG(DiagramSelection selection) {
975         if (ghostNode.isVisible()) {
976             // Make sure there's no leftover graphics.
977             ghostNode.removeNodes();
978             ghostNode.setVisible(Boolean.FALSE);
979             return true;
980         }
981         return false;
982     }
983
984     protected void scheduleActivateOwnerPart() {
985         if (site == null)
986             return;
987         SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), new Runnable() {
988             @Override
989             public void run() {
990                 hasFocus = true;
991                 site.getPage().activate(site.getPart());
992             }
993         });
994     }
995
996     @EventHandler(priority = 0)
997     public boolean handleMouse(MouseExitEvent e) {
998         DiagramSelection ds = getProjectSelection();
999         if (!ds.isEmpty()) {
1000             if (hideSG(ds))
1001                 setDirty();
1002         }
1003
1004         // The part might no longer have focus.
1005         // [Tuukka] commented out to fix Apros #3678
1006         //hasFocus = false;
1007
1008         return false;
1009     }
1010
1011     @EventHandler(priority = 0)
1012     public boolean handleMouse(MouseEnterEvent e) {
1013         DiagramSelection ds = getProjectSelection();
1014         if (!ds.isEmpty()) {
1015             if (site != null) {
1016                 if (inPasteMode(e)) {
1017                     scheduleActivateOwnerPart();
1018                 }
1019             }
1020         }
1021         return false;
1022     }
1023
1024     @EventHandler(priority = 0)
1025     public boolean handleMouse(MouseMovedEvent e) {
1026         DiagramSelection ds = getProjectSelection();
1027         if (!ds.isEmpty()) {
1028             MouseInfo mi = mouseUtil.getMouseInfo(0);
1029             //System.out.println("LAST MOUSE INFO: " + mi);
1030             if (mi != null)
1031                 mouseInfo = mi;
1032
1033             if (inPasteMode(e)) {
1034                 // Make sure that this owner part is active now.
1035                 if (!hasFocus)
1036                     scheduleActivateOwnerPart();
1037
1038                 updateSG(ds);
1039                 setDirty();
1040             } else {
1041                 if (hideSG(ds))
1042                     setDirty();
1043             }
1044         }
1045         return false;
1046     }
1047
1048     void updateSG(DiagramSelection selection) {
1049         MouseInfo mi = mouseUtil.getMouseInfo(0);
1050         if (mi == null)
1051             return;
1052
1053         //ghostNode.setComposite(AlphaComposite.SrcAtop.derive(0.40f));
1054         //ghostNode.setComposite(null);
1055
1056         moveGhostElements(selection, mi.canvasPosition);
1057         if (selection.getSourceCanvas() != getContext()) {
1058             for (IElement e : selection.getOriginalElements()) {
1059                 INode node = e.getHint(ElementHints.KEY_SG_NODE);
1060                 //System.out.println("ghost element: " + e + ", node=" + node);
1061                 if (node instanceof IG2DNode) {
1062                     LocalDelegateNode delegate = getOrCreateNode(ghostNode, ElementUtils.generateNodeId(e),
1063                             LocalDelegateNode.class);
1064                     delegate.setDelegate( (IG2DNode) node );
1065                 }
1066             }
1067         } else {
1068             for (IElement e : selection.getOriginalElements()) {
1069                 //System.out.println("ghost element: " + e);
1070                 INode node = e.getHint(ElementHints.KEY_SG_NODE);
1071                 if (node != null) {
1072                     //System.out.println("ghost node: " + node);
1073                     ghostNodeMapper.add(node);
1074                     String nodeId = ghostNodeMapper.getId(node);
1075                     //System.out.println("ghost node id: " + nodeId);
1076                     LinkNode delegate = getOrCreateNode(ghostNode, ElementUtils.generateNodeId(e), LinkNode.class);
1077                     delegate.setDelegateId( nodeId );
1078                 }
1079             }
1080         }
1081
1082         ghostNode.setVisible(true);
1083     }
1084
1085     private <T extends INode> T getOrCreateNode(ParentNode<?> parentNode, String id, Class<T> clazz) {
1086         INode n = ghostNode.getNode(id);
1087         if (clazz.isInstance(n))
1088             return clazz.cast(n);
1089         ghostNode.removeNode(id);
1090         return ghostNode.addNode(id, clazz);
1091     }
1092
1093     protected boolean hasHighlight() {
1094         return highlightMode != null;
1095     }
1096
1097     protected void removeHighlight() {
1098         if (isRemoved())
1099             return;
1100         assert getContext().getThreadAccess().currentThreadAccess();
1101         if (highlightMode != null) {
1102             if (!highlightMode.isRemoved()) {
1103                 highlightMode.remove();
1104                 setDirty();
1105             }
1106             highlightMode = null;
1107         }
1108     }
1109
1110     private boolean inPasteMode(MouseEvent e) {
1111         return (e.stateMask & MouseEvent.CTRL_MASK) != 0;
1112     }
1113
1114     protected void selectedMessage(DiagramSelection ds) {
1115         int size = ds.getOriginalElements().size();
1116         StringBuilder sb = new StringBuilder();
1117         if (size == 0) {
1118             sb.append("No elements to ");
1119             if (ds.isCut())
1120                 sb.append("cut");
1121             else
1122                 sb.append("copy");
1123         } else {
1124             if (ds.isCut())
1125                 sb.append("Cut ");
1126             else
1127                 sb.append("Copied ");
1128             sb.append(size);
1129             sb.append(" element");
1130             if (size > 1)
1131                 sb.append('s');
1132         }
1133         message(sb.toString());
1134     }
1135
1136     protected void message(final String message) {
1137         if (statusLine == null)
1138             return;
1139         swtExec(new Runnable() {
1140             @Override
1141             public void run() {
1142                 statusLine.setMessage(message);
1143                 statusLine.setErrorMessage(null);
1144             }
1145         });
1146     }
1147
1148     protected void error(final String message) {
1149         if (statusLine == null)
1150             return;
1151         swtExec(new Runnable() {
1152             @Override
1153             public void run() {
1154                 statusLine.setErrorMessage(message);
1155             }
1156         });
1157     }
1158
1159     protected void swtExec(Runnable r) {
1160         ThreadUtils.asyncExec(SWTThread.getThreadAccess(Display.getDefault()), r);
1161     }
1162
1163     // MONITOR PASTE SUPPORT
1164
1165     private boolean tryPasteMonitors() {
1166         SimanticsClipboard clipboard = Simantics.getClipboard();
1167         for (Set<Representation> content : clipboard.getContents()) {
1168             try {
1169                 final Variable var_ = ClipboardUtils.accept(content, SimanticsKeys.KEY_VARIABLE);
1170                 if (var_ != null) {
1171                     final Resource diagramResource = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
1172                     final Resource runtime = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RUNTIME_RESOURCE);
1173                     final Resource elementResource = Simantics.getSession().syncRequest(new Read<Resource>() {
1174                         @Override
1175                         public Resource perform(ReadGraph graph) throws DatabaseException {
1176                             DiagramResource DIA = DiagramResource.getInstance(graph);
1177
1178                             String diagramVariable = graph.getPossibleRelatedValue(runtime, DIA.RuntimeDiagram_HasVariable);
1179                             if (diagramVariable == null)
1180                                 return null;
1181
1182                             Variable diaVar = Variables.getPossibleVariable(graph, diagramVariable);
1183                             if (diaVar == null)
1184                                 return null;
1185
1186                             Variable var = Variables.switchRealization(graph, var_, Variables.getRealization(graph, diaVar));
1187                             if(var == null)
1188                                 return null;
1189
1190                             Variable component = Variables.getChild(graph, diaVar, var);
1191                             if (component == null)
1192                                 return null;
1193
1194                             Resource componentResource = component.getPossibleRepresents(graph);
1195                             if (componentResource == null)
1196                                 return null;
1197
1198                             return graph.getPossibleObject(componentResource, ModelingResources.getInstance(graph).ComponentToElement);
1199                         }
1200                     });
1201
1202                     if (elementResource == null)
1203                         return false;
1204
1205                     final AffineTransform monitorTransform = Simantics.getSession().syncRequest(new Read<AffineTransform>() {
1206                         @Override
1207                         public AffineTransform perform(ReadGraph graph) throws DatabaseException {
1208                             AffineTransform at = null;
1209
1210                             if (graph.isInstanceOf(elementResource, DiagramResource.getInstance(graph).Connection)) {
1211                                 Resource tailNode = ConnectionUtil.getConnectionTailNode(graph, elementResource);
1212                                 if (tailNode != null) {
1213                                     at = DiagramGraphUtil.getAffineTransform(graph, tailNode);
1214                                 }
1215                             }
1216                             if (at == null)
1217                                 at = DiagramGraphUtil.getAffineTransform(graph, elementResource);
1218
1219                             return at;
1220                         }
1221                     });
1222
1223                     MouseInfo mi = mouseUtil.getMouseInfo(0);
1224                     if (mi == null)
1225                         mi = mouseInfo;
1226                     final double dx = mi.canvasPosition.getX() - monitorTransform.getTranslateX();
1227                     final double dy = mi.canvasPosition.getY() - monitorTransform.getTranslateY();
1228
1229                     Simantics.getSession().asyncRequest(new WriteRequest() {
1230
1231                         @Override
1232                         public void perform(WriteGraph graph) throws DatabaseException {
1233                             Layer0 L0 = Layer0.getInstance(graph);
1234                             Layer0X L0X = Layer0X.getInstance(graph);
1235                             DiagramResource DIA = DiagramResource.getInstance(graph);
1236                             G2DResource G2D = G2DResource.getInstance(graph);
1237
1238                             String diagramVariable = graph.getPossibleRelatedValue(runtime, DIA.RuntimeDiagram_HasVariable);
1239                             if (diagramVariable == null)
1240                                 return;
1241
1242                             Variable diaVar = Variables.getPossibleVariable(graph, diagramVariable);
1243                             if (diaVar == null)
1244                                 return;
1245
1246                             Variable var = Variables.switchRealization(graph, var_, Variables.getRealization(graph, diaVar));
1247                             if(var == null)
1248                                 return;
1249
1250                             Variable component = Variables.getChild(graph, diaVar, var);
1251                             if (component == null)
1252                                 return;
1253
1254                             Resource componentResource = component.getPossibleRepresents(graph);
1255                             if (componentResource == null)
1256                                 return;
1257
1258                             String suffix = Variables.getRVI(graph, component, var);
1259
1260                             Resource resource = graph.newResource();
1261                             graph.claim(resource, L0.InstanceOf, null, DIA.Monitor);
1262
1263                             final double scale = monitorScale;
1264
1265                             DiagramGraphUtil.setTransform(graph, resource, new AffineTransform(scale, 0, 0, scale, dx, dy));
1266
1267                             OrderedSetUtils.add(graph, diagramResource, resource);
1268
1269                             // 5.1. Give running name to element and increment the counter attached to the diagram.
1270                             Long l = graph.getPossibleRelatedValue(diagramResource, DIA.HasModCount, Bindings.LONG);
1271                             if (l == null)
1272                                 l = Long.valueOf(0L);
1273                             graph.claimLiteral(resource, L0.HasName, l.toString(), Bindings.STRING);
1274                             graph.claimLiteral(diagramResource, DIA.HasModCount, ++l, Bindings.LONG);
1275
1276                             // 5.2. Make the diagram consist of the new element
1277                             graph.claim(diagramResource, L0.ConsistsOf, resource);
1278
1279                             graph.claim(resource, G2D.HasHorizontalAlignment, null, G2D.Alignment_Leading);
1280                             graph.claimLiteral(resource, DIA.HasDirection, 0.0);
1281
1282                             graph.claim(resource, DIA.HasMonitorComponent, componentResource);
1283                             graph.claimLiteral(resource, DIA.HasMonitorSuffix, suffix);
1284
1285                             Resource model = Variables.getModel(graph, diaVar);
1286                             if (model != null) {
1287                                 Resource template = graph.getPossibleObject(model, DIA.HasDefaultMonitorTemplate);
1288                                 if (template != null) {
1289                                     graph.claim(resource, L0X.ObtainsProperty1, null, template);
1290                                 }
1291                             }
1292
1293                         }
1294                     });
1295                 }
1296             } catch (DatabaseException e1) {
1297                 Logger.defaultLogError(e1);
1298             }
1299         }
1300         return true;
1301     }
1302
1303 }