1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.diagram.handler;
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;
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;
119 * CopyPasteHandler is a canvas handler for Commands.CUT, Commands.COPY and
120 * Commands.PASTE commands for an IDiagram.
123 * The handler attempts to copy/paste the current selection for pointer 0,
124 * meaning {@link Selection#SELECTION0}.
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
134 * @see Selection current diagram selection source
136 * @author Tuukka Lehtonen
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.
142 public class CopyPasteHandler extends AbstractDiagramParticipant {
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");
150 * A key for storing the current selection within the currently active
151 * project for copy/paste implementation.
153 private static final Key KEY_DIAGRAM_SELECTION = DiagramSelectionRepresentation.KEY_DIAGRAM_SELECTION;
155 private static final boolean DEBUG = false;
156 private static final boolean DEBUG_SELECTION_UPDATE = false;
158 public static final int COPY_GHOSTING_PAINT_PRIORITY = 600;
160 protected static final int HIGHLIGHT_PAINT_PRIORITY = 500;
163 protected Selection sel;
165 protected MouseUtil mouseUtil;
167 protected final IStatusLineManager statusLine;
168 protected final CopyPasteStrategy strategy;
169 protected IWorkbenchPartSite site;
170 protected IWorkbenchPartSite listenedSite;
173 * Workbench part listener for {@link #listenedSite} to keep proper track of
174 * whether this part is focused or not.
176 IPartListener partListener = new IPartListener() {
178 public void partOpened(IWorkbenchPart part) {
181 public void partDeactivated(IWorkbenchPart part) {
182 if (part == site.getPart())
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);
194 public void partBroughtToTop(IWorkbenchPart part) {
197 public void partActivated(IWorkbenchPart part) {
198 if (part == site.getPart())
204 * Indicates whether CopyPasteHandler thinks that {@link #site} has focus.
206 protected boolean hasFocus = false;
208 protected AbstractCanvasParticipant highlightMode = null;
209 private IProject observedProject = null;
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
218 private int pasteWithoutMovingGhostCounter = 0;
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
225 private final Point2D pasteOffset = new Point2D.Double(0, 0);
228 * Stores the last MouseInfo for mouse 0 from the time of the previous
229 * received mouse event. Used for deciding the paste position.
231 * @see #getPastePos(DiagramSelection)
233 private MouseInfo mouseInfo;
236 * Scale to use for pasted diagram monitors from variables.
238 private double monitorScale = 0.2;
241 * For updating the diagram selection after graph changes.
243 private DiagramSelectionUpdater selectionUpdater = null;
245 public CopyPasteHandler() {
246 this(new DefaultCopyPasteStrategy());
249 public CopyPasteHandler(CopyPasteStrategy strategy) {
250 this(strategy, null);
253 public CopyPasteHandler(IStatusLineManager statusLine) {
254 this(new DefaultCopyPasteStrategy(), statusLine);
257 public CopyPasteHandler(CopyPasteStrategy strategy, IStatusLineManager statusLine) {
258 this.strategy = strategy != null ? strategy : new DefaultCopyPasteStrategy();
259 this.statusLine = statusLine;
262 public CopyPasteHandler(CopyPasteStrategy strategy, IStatusLineManager statusLine, double monitorScale) {
263 this.strategy = strategy != null ? strategy : new DefaultCopyPasteStrategy();
264 this.statusLine = statusLine;
265 setMonitorScale(monitorScale);
268 public CopyPasteHandler setMonitorScale(double scale) {
269 this.monitorScale = scale;
273 public CopyPasteHandler setWorkbenchSite(IWorkbenchPartSite site) {
278 protected boolean isPasteAllowed() {
279 return listenedSite == null || hasFocus;
283 public void addedToContext(ICanvasContext ctx) {
284 super.addedToContext(ctx);
285 addProjectListener(peekProject());
288 if (listenedSite != null) {
289 listenedSite.getPage().addPartListener(partListener);
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();
301 if (listenedSite != null) {
302 listenedSite.getPage().removePartListener(partListener);
306 removeProjectListener();
307 super.removedFromContext(ctx);
311 protected void onDiagramSet(IDiagram newDiagram, IDiagram oldDiagram) {
312 if (oldDiagram != null) {
313 if (selectionUpdater != null) {
314 selectionUpdater.untrack();
315 selectionUpdater = null;
318 if (newDiagram != null) {
319 selectionUpdater = new DiagramSelectionUpdater(getContext(), newDiagram).track();
323 IHintListener projectDiagramSelectionListener = new HintListenerAdapter() {
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() {
343 private void addProjectListener(IProject observable) {
344 if (observable != null) {
345 observable.addKeyHintListener(KEY_DIAGRAM_SELECTION, projectDiagramSelectionListener);
346 observedProject = observable;
350 private void removeProjectListener() {
351 if (observedProject != null) {
352 observedProject.removeKeyHintListener(KEY_DIAGRAM_SELECTION, projectDiagramSelectionListener);
353 observedProject = null;
357 IProject getProject() {
358 return Simantics.getProject();
361 IProject peekProject() {
362 return Simantics.peekProject();
365 public DiagramSelection getClipboardDiagramSelection() {
366 for (Set<Representation> content : Simantics.getClipboard().getContents()) {
368 DiagramSelection sel = ClipboardUtils.accept(content, DiagramSelectionRepresentation.KEY_DIAGRAM_SELECTION);
371 } catch (DatabaseException e) {
372 Activator.getDefault().getLog().log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to retrieve clipboard content.", e));
375 return DiagramSelection.EMPTY;
378 protected DiagramSelection getProjectSelection() {
379 IProject p = peekProject();
381 return DiagramSelection.EMPTY;
382 DiagramSelection ds = p.getHint(KEY_DIAGRAM_SELECTION);
383 return ds != null ? ds : DiagramSelection.EMPTY;
386 protected void setDiagramSelection(DiagramSelection selection) {
387 setProjectSelection(selection);
388 strategy.copyToClipboard(selection);
391 protected void setProjectSelection(DiagramSelection selection) {
392 assert selection != null;
393 IProject p = getProject();
395 throw new IllegalStateException("no active project for selection");
397 pasteWithoutMovingGhostCounter = 0;
398 pasteOffset.setLocation(0, 0);
399 p.setHint(KEY_DIAGRAM_SELECTION, selection);
402 protected void removeProjectSelection() {
403 setProjectSelection(DiagramSelection.EMPTY);
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.
414 @EventHandler(priority = 100)
415 public boolean handleDelete(CommandEvent e) {
416 if (e.command.equals( Commands.DELETE) ) {
417 if (highlightMode != null) {
419 removeProjectSelection();
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();
431 if (e instanceof KeyPressedEvent) {
433 message("Move selection");
435 message("Paste selection");
437 } else if (e instanceof KeyReleasedEvent) {
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()) {
453 removeProjectSelection();
458 if (e.command.equals( Commands.CUT ) || e.command.equals( Commands.COPY )) {
459 boolean ret = initiateCopy( e.command.equals( Commands.CUT ) );
461 removeProjectSelection();
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();
469 return tryPasteMonitors();
471 return paste(e.command, ds);
476 protected boolean initiateCopy(boolean cut) {
477 //System.out.println("INITIATING COPY");
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"));
487 // Validate selection, don't initiate copy if selection is invalid.
488 ElementAssortment ea = new ElementAssortment(ss);
489 String error = fixAssortment(ea, cut);
496 pruneAssortment(ea, cut);
498 message("Nothing to " + (cut ? "cut" : "copy"));
502 // Allow the possible CopyStrategy to filter the copied element
504 if (strategy instanceof CopyStrategy) {
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()) {
511 case IStatus.WARNING:
512 message(status.getMessage());
515 error(status.getMessage());
523 System.out.println("Start copy with " + ea);
525 // Treat OTHER type elements as disconnected floating graphical elements
526 // that are always copied.
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.");
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.");
539 // Pre-validate flag selection cases
540 if (ea.contains(CopyPasteUtil.FLAGS)) {
542 // Allow cutting of single flags or cutting of any amount of
543 // flags within a single diagram.
545 // // Deny flag copy if other kinds of elements are selected.
546 // if (ea.containsAny(NOT_FLAGS)) {
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.");
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);
565 highlightMode = new HighlightMode(ds, selectionId, HIGHLIGHT_PAINT_PRIORITY);
566 getContext().add(highlightMode);
570 // System.out.println("INITIATED COPY: " + ds);
574 public boolean paste(Command command, DiagramSelection ds) {
580 TimeLogger.resetTimeAndLog(getClass(), "paste");
582 ElementObjectAssortment ea = ds.getAssortment();
585 System.out.println("Initiate paste with " + ea);
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))
594 normalPaste(command, ds, ea, true);
596 setDiagramSelection(DiagramSelection.EMPTY);
597 resetSourceSelection(ds);
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.
603 setDiagramSelection(DiagramSelection.EMPTY);
607 normalPaste(command, ds, ea, true);
609 setDiagramSelection(DiagramSelection.EMPTY);
610 resetSourceSelection(ds);
612 normalPaste(command, ds, ea, false);
614 // // This is necessary to keep the ghost diagram properly up-to-date
615 // // after paste operations.
616 // setProjectSelection(ds.remutate());
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) );
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
644 * @param ds the source selection to reset
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);
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);
661 double dx = pastePos.getX() - copyPos.getX();
662 double dy = pastePos.getY() - copyPos.getY();
663 final Point2D pasteOffset = new Point2D.Double(dx, dy);
666 // Get diagram contents before the paste operation
667 Resource diagramResource = diagram.getHint(DiagramModelHints.KEY_DIAGRAM_RESOURCE);
668 final DiagramContentTracker tracker =
669 diagramResource == null ?
671 : DiagramContentTracker.start(getContext(), Simantics.getSession(), diagramResource);
673 strategy.paste(new PasteOperation(command, getContext(), ds.getSourceDiagram(), diagramResource, diagram, ea, cut, pasteOffset));
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());
683 } catch (DatabaseException e) {
684 ErrorLogger.defaultLogError(e);
688 protected String fixAssortment(ElementAssortment ea, boolean cut) {
689 Topology diagramTopology = diagram.getDiagramClass().getAtMostOneItemOfClass(Topology.class);
690 List<Connection> conns = new ArrayList<Connection>();
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);
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);
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) {
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());
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;
733 if (!allConnectorsSelected)
734 connectionsToRemove.add(connection);
736 ea.removeAll(ElementType.Connection, connectionsToRemove);
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)) {
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);
754 ea.removeAll(ElementType.Flag, flagsToRemove);
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)) {
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))
770 return "Cannot cut a node without all its connections.";
775 // Remove all reference elements from the assortment whose parent elements are not in it.
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);
786 // OK, reference element has no parent. Free to copy/cut in any way.
789 if (!referenceElementsToRemove.isEmpty()) {
790 ea.removeAll(ElementType.Reference, referenceElementsToRemove);
792 return "Cannot copy reference elements whose parent is not copied.";
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);
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)
812 for (Terminal t : getTerminals(node))
813 topology.getConnections(node, t, result);
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.
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);
834 ea.clear(ElementType.BranchPoint);
837 private Point2D getPastePos(DiagramSelection ds) {
838 MouseInfo mi = mouseUtil.getMouseInfo(0);
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);
853 pasteWithoutMovingGhostCounter = 0;
854 pasteOffset.setLocation(xoff, yoff);
855 return mi.canvasPosition;
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);
866 private double getOffsetGridSize() {
867 Double grid = getHint(GridPainter.KEY_GRID_SIZE);
868 return (grid == null || grid == 0) ? 1.0 : grid;
875 protected static boolean isConnectionOrEdge(IElement e) {
876 ElementClass ec = e.getElementClass();
877 return ec.containsClass(ConnectionHandler.class)|| ec.containsClass(BendsHandler.class);
884 protected static boolean isMoveable(IElement e) {
885 ElementClass ec = e.getElementClass();
886 return ec.containsClass(Move.class) && ec.containsClass(Transform.class);
891 * @return <code>null</code> if a point of reference cannot be determined
892 * for the specified selection.
894 protected Point2D getCopyStartPos(Set<IElement> ss) {
895 // MouseInfo mi = mouseUtil.getMouseInfo(0);
897 // return (Point2D) mi.canvasPosition.clone();
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))
907 //Point2D pos = ElementUtils.getPos(e);
908 Point2D pos = ElementUtils.getAbsolutePos(e);
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))
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;
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());
941 Point2D snap = CopyPasteUtil.snap(getContext(), new Point2D.Double(dx, dy));
943 ghostNode.setTransform(AffineTransform.getTranslateInstance(snap.getX(), snap.getY()));
944 //System.out.println("ghost node: " + ghostNode);
947 protected SingleElementNode ghostNode = null;
948 protected NodeMapper ghostNodeMapper = new NodeMapper();
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);
959 public void cleanupSG() {
964 ghostNode.removeNodes();
965 ghostNode.setVisible(Boolean.FALSE);
966 ghostNodeMapper.clear();
971 * @return <code>true</code> if the ghost nodes were hidden and a refresh is
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);
984 protected void scheduleActivateOwnerPart() {
987 SWTUtils.asyncExec(PlatformUI.getWorkbench().getDisplay(), new Runnable() {
991 site.getPage().activate(site.getPart());
996 @EventHandler(priority = 0)
997 public boolean handleMouse(MouseExitEvent e) {
998 DiagramSelection ds = getProjectSelection();
1004 // The part might no longer have focus.
1005 // [Tuukka] commented out to fix Apros #3678
1011 @EventHandler(priority = 0)
1012 public boolean handleMouse(MouseEnterEvent e) {
1013 DiagramSelection ds = getProjectSelection();
1014 if (!ds.isEmpty()) {
1016 if (inPasteMode(e)) {
1017 scheduleActivateOwnerPart();
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);
1033 if (inPasteMode(e)) {
1034 // Make sure that this owner part is active now.
1036 scheduleActivateOwnerPart();
1048 void updateSG(DiagramSelection selection) {
1049 MouseInfo mi = mouseUtil.getMouseInfo(0);
1053 //ghostNode.setComposite(AlphaComposite.SrcAtop.derive(0.40f));
1054 //ghostNode.setComposite(null);
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 );
1068 for (IElement e : selection.getOriginalElements()) {
1069 //System.out.println("ghost element: " + e);
1070 INode node = e.getHint(ElementHints.KEY_SG_NODE);
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 );
1082 ghostNode.setVisible(true);
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);
1093 protected boolean hasHighlight() {
1094 return highlightMode != null;
1097 protected void removeHighlight() {
1100 assert getContext().getThreadAccess().currentThreadAccess();
1101 if (highlightMode != null) {
1102 if (!highlightMode.isRemoved()) {
1103 highlightMode.remove();
1106 highlightMode = null;
1110 private boolean inPasteMode(MouseEvent e) {
1111 return (e.stateMask & MouseEvent.CTRL_MASK) != 0;
1114 protected void selectedMessage(DiagramSelection ds) {
1115 int size = ds.getOriginalElements().size();
1116 StringBuilder sb = new StringBuilder();
1118 sb.append("No elements to ");
1127 sb.append("Copied ");
1129 sb.append(" element");
1133 message(sb.toString());
1136 protected void message(final String message) {
1137 if (statusLine == null)
1139 swtExec(new Runnable() {
1142 statusLine.setMessage(message);
1143 statusLine.setErrorMessage(null);
1148 protected void error(final String message) {
1149 if (statusLine == null)
1151 swtExec(new Runnable() {
1154 statusLine.setErrorMessage(message);
1159 protected void swtExec(Runnable r) {
1160 ThreadUtils.asyncExec(SWTThread.getThreadAccess(Display.getDefault()), r);
1163 // MONITOR PASTE SUPPORT
1165 private boolean tryPasteMonitors() {
1166 SimanticsClipboard clipboard = Simantics.getClipboard();
1167 for (Set<Representation> content : clipboard.getContents()) {
1169 final Variable var_ = ClipboardUtils.accept(content, SimanticsKeys.KEY_VARIABLE);
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>() {
1175 public Resource perform(ReadGraph graph) throws DatabaseException {
1176 DiagramResource DIA = DiagramResource.getInstance(graph);
1178 String diagramVariable = graph.getPossibleRelatedValue(runtime, DIA.RuntimeDiagram_HasVariable);
1179 if (diagramVariable == null)
1182 Variable diaVar = Variables.getPossibleVariable(graph, diagramVariable);
1186 Variable var = Variables.switchRealization(graph, var_, Variables.getRealization(graph, diaVar));
1190 Variable component = Variables.getChild(graph, diaVar, var);
1191 if (component == null)
1194 Resource componentResource = component.getPossibleRepresents(graph);
1195 if (componentResource == null)
1198 return graph.getPossibleObject(componentResource, ModelingResources.getInstance(graph).ComponentToElement);
1202 if (elementResource == null)
1205 final AffineTransform monitorTransform = Simantics.getSession().syncRequest(new Read<AffineTransform>() {
1207 public AffineTransform perform(ReadGraph graph) throws DatabaseException {
1208 AffineTransform at = null;
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);
1217 at = DiagramGraphUtil.getAffineTransform(graph, elementResource);
1223 MouseInfo mi = mouseUtil.getMouseInfo(0);
1226 final double dx = mi.canvasPosition.getX() - monitorTransform.getTranslateX();
1227 final double dy = mi.canvasPosition.getY() - monitorTransform.getTranslateY();
1229 Simantics.getSession().asyncRequest(new WriteRequest() {
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);
1238 String diagramVariable = graph.getPossibleRelatedValue(runtime, DIA.RuntimeDiagram_HasVariable);
1239 if (diagramVariable == null)
1242 Variable diaVar = Variables.getPossibleVariable(graph, diagramVariable);
1246 Variable var = Variables.switchRealization(graph, var_, Variables.getRealization(graph, diaVar));
1250 Variable component = Variables.getChild(graph, diaVar, var);
1251 if (component == null)
1254 Resource componentResource = component.getPossibleRepresents(graph);
1255 if (componentResource == null)
1258 String suffix = Variables.getRVI(graph, component, var);
1260 Resource resource = graph.newResource();
1261 graph.claim(resource, L0.InstanceOf, null, DIA.Monitor);
1263 final double scale = monitorScale;
1265 DiagramGraphUtil.setTransform(graph, resource, new AffineTransform(scale, 0, 0, scale, dx, dy));
1267 OrderedSetUtils.add(graph, diagramResource, resource);
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);
1272 l = Long.valueOf(0L);
1273 graph.claimLiteral(resource, L0.HasName, l.toString(), Bindings.STRING);
1274 graph.claimLiteral(diagramResource, DIA.HasModCount, ++l, Bindings.LONG);
1276 // 5.2. Make the diagram consist of the new element
1277 graph.claim(diagramResource, L0.ConsistsOf, resource);
1279 graph.claim(resource, G2D.HasHorizontalAlignment, null, G2D.Alignment_Leading);
1280 graph.claimLiteral(resource, DIA.HasDirection, 0.0);
1282 graph.claim(resource, DIA.HasMonitorComponent, componentResource);
1283 graph.claimLiteral(resource, DIA.HasMonitorSuffix, suffix);
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);
1296 } catch (DatabaseException e1) {
1297 Logger.defaultLogError(e1);