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.g2d.diagram.participant.pointertool;
14 import java.awt.Shape;
15 import java.awt.geom.AffineTransform;
16 import java.awt.geom.Path2D;
17 import java.awt.geom.Point2D;
18 import java.awt.geom.Rectangle2D;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.HashSet;
22 import java.util.List;
25 import org.simantics.g2d.canvas.Hints;
26 import org.simantics.g2d.canvas.ICanvasContext;
27 import org.simantics.g2d.canvas.ICanvasParticipant;
28 import org.simantics.g2d.canvas.IToolMode;
29 import org.simantics.g2d.canvas.impl.CanvasContext;
30 import org.simantics.g2d.canvas.impl.DependencyReflection.Dependency;
31 import org.simantics.g2d.canvas.impl.DependencyReflection.Reference;
32 import org.simantics.g2d.connection.IConnectionAdvisor;
33 import org.simantics.g2d.connection.handler.ConnectionHandler;
34 import org.simantics.g2d.diagram.DiagramHints;
35 import org.simantics.g2d.diagram.handler.PickContext;
36 import org.simantics.g2d.diagram.handler.PickRequest;
37 import org.simantics.g2d.diagram.handler.PickRequest.PickPolicy;
38 import org.simantics.g2d.diagram.handler.PickRequest.PickSorter;
39 import org.simantics.g2d.diagram.participant.AbstractDiagramParticipant;
40 import org.simantics.g2d.diagram.participant.Selection;
41 import org.simantics.g2d.diagram.participant.TerminalPainter;
42 import org.simantics.g2d.diagram.participant.TerminalPainter.ChainedHoverStrategy;
43 import org.simantics.g2d.diagram.participant.TerminalPainter.TerminalHoverStrategy;
44 import org.simantics.g2d.diagram.participant.pointertool.TerminalUtil.TerminalInfo;
45 import org.simantics.g2d.element.ElementClassProviders;
46 import org.simantics.g2d.element.IElement;
47 import org.simantics.g2d.element.IElementClassProvider;
48 import org.simantics.g2d.participant.KeyUtil;
49 import org.simantics.g2d.participant.MouseUtil;
50 import org.simantics.g2d.participant.TransformUtil;
51 import org.simantics.g2d.scenegraph.SceneGraphConstants;
52 import org.simantics.g2d.utils.CanvasUtils;
53 import org.simantics.g2d.utils.GeometryUtils;
54 import org.simantics.scenegraph.g2d.events.Event;
55 import org.simantics.scenegraph.g2d.events.EventHandlerReflection.EventHandler;
56 import org.simantics.scenegraph.g2d.events.KeyEvent;
57 import org.simantics.scenegraph.g2d.events.KeyEvent.KeyPressedEvent;
58 import org.simantics.scenegraph.g2d.events.MouseEvent;
59 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseButtonPressedEvent;
60 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseClickEvent;
61 import org.simantics.scenegraph.g2d.events.MouseEvent.MouseDragBegin;
62 import org.simantics.scenegraph.g2d.events.command.Commands;
63 import org.simantics.scenegraph.g2d.snap.ISnapAdvisor;
64 import org.simantics.utils.ObjectUtils;
65 import org.simantics.utils.datastructures.context.IContext;
66 import org.simantics.utils.datastructures.context.IContextListener;
67 import org.simantics.utils.datastructures.hints.IHintContext.Key;
68 import org.simantics.utils.datastructures.hints.IHintContext.KeyOf;
69 import org.simantics.utils.threads.ThreadUtils;
72 * Pointer tool does the following operations with mouse:
78 * <li>Draws connections (requires re-implementing
79 * {@link #createConnectTool(TerminalInfo, int, Point2D)})</li>
82 * Pointer tool is active only when {@link Hints#KEY_TOOL} is
83 * {@value Hints#POINTERTOOL}.
85 * @author Toni Kalajainen
87 public class PointerInteractor extends AbstractDiagramParticipant {
90 * A hint key for terminal pick distance in control pixels.
93 public static final Key KEY_PICK_DISTANCE = new KeyOf(Double.class, "PICK_DISTANCE");
96 * Default terminal pick distance in control pixels.
97 * @see #DEFAULT_PICK_DISTANCE
99 public static final double PICK_DIST = 10;
102 * @see #altToggled(KeyEvent)
104 protected int lastStateMask;
107 * @see #altToggled(KeyEvent)
109 protected boolean temporarilyEnabledConnectTool = false;
111 public class DefaultHoverStrategy extends ChainedHoverStrategy {
112 public DefaultHoverStrategy(TerminalHoverStrategy orig) {
116 public boolean highlightEnabled() {
117 if (Hints.CONNECTTOOL.equals(getToolMode()))
120 boolean ct = connectToolModifiersPressed(lastStateMask);
121 //System.out.println("highlightEnabled: " + String.format("%x", lastStateMask) + " : " + ct);
125 public boolean canHighlight(TerminalInfo ti) {
126 //boolean alt = (lastStateMask & MouseEvent.ALT_MASK) != 0;
127 //System.out.println("canHighlight: " + String.format("%x", lastStateMask) + " : " + alt);
130 IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);
131 return advisor == null || advisor.canBeginConnection(null, ti.e, ti.t);
135 @Dependency Selection selection;
136 @Dependency KeyUtil keys;
137 @Dependency TransformUtil util;
138 @Dependency PickContext pickContext;
139 @Dependency MouseUtil mice;
140 @Reference TerminalPainter terminalPainter;
143 * This must be higher than
144 * {@link SceneGraphConstants#SCENEGRAPH_EVENT_PRIORITY}
145 * ({@value SceneGraphConstants#SCENEGRAPH_EVENT_PRIORITY}) to allow for
146 * better selection handling than is possible by using the plain scene graph
147 * event handling facilities which are installed in {@link CanvasContext}.
149 public static final int TOOL_PRIORITY = 1 << 21;
152 * This must be lower than
153 * {@link SceneGraphConstants#SCENEGRAPH_EVENT_PRIORITY} (
154 * {@value SceneGraphConstants#SCENEGRAPH_EVENT_PRIORITY}) to not start box
155 * handling before scene graph nodes have been given a chance to react
158 public static final int BOX_SELECT_PRIORITY = 1 << 19;
160 private static final Path2D LINE10;
161 private static final Path2D LINE15;
162 private static final Path2D LINE20;
166 boolean dragElement, dndDragElement;
168 boolean doubleClickEdit;
169 protected IElementClassProvider elementClassProvider;
171 PickPolicy boxSelectMode = PickPolicy.PICK_CONTAINED_OBJECTS;
173 DefaultHoverStrategy hoverStrategy;
175 private PickSorter pickSorter;
177 public PointerInteractor() {
178 this(true, true, true, false, true, false, ElementClassProviders.staticProvider(null), null);
181 public PointerInteractor(PickSorter pickSorter) {
182 this(true, true, true, false, true, false, ElementClassProviders.staticProvider(null), pickSorter);
185 public PointerInteractor(boolean clickSelect, boolean boxSelect, boolean dragElement, boolean dndDragElement, boolean connect, IElementClassProvider ecp) {
186 this(clickSelect, boxSelect, dragElement, dndDragElement, connect, false, ecp, null);
189 public PointerInteractor(boolean clickSelect, boolean boxSelect, boolean dragElement, boolean dndDragElement, boolean connect, boolean doubleClickEdit, IElementClassProvider ecp, PickSorter pickSorter) {
191 this.clickSelect = clickSelect;
192 this.boxSelect = boxSelect;
193 this.dragElement = dragElement;
194 this.dndDragElement = dndDragElement;
195 this.connect = connect;
196 this.doubleClickEdit = doubleClickEdit;
197 this.elementClassProvider = ecp;
198 this.pickSorter = pickSorter;
202 public void addedToContext(ICanvasContext ctx) {
203 super.addedToContext(ctx);
204 hoverStrategy = new DefaultHoverStrategy((TerminalHoverStrategy) getHint(TerminalPainter.TERMINAL_HOVER_STRATEGY));
205 setHint(TerminalPainter.TERMINAL_HOVER_STRATEGY, hoverStrategy);
208 @EventHandler(priority = 0)
209 public boolean handleStateMask(MouseEvent me) {
210 lastStateMask = me.stateMask;
211 if (temporarilyEnabledConnectTool) {
212 if (!connectToolModifiersPressed(me.stateMask)) {
213 temporarilyEnabledConnectTool = false;
214 setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
217 // It may be that the mouse has come into this control
218 // from outside and no key state changes have occurred yet.
219 // In this case this code should take care of moving the canvas
220 // context into CONNECTTOOL mode.
221 if (getToolMode() == Hints.POINTERTOOL
222 && connectToolModifiersPressed(me.stateMask))
224 temporarilyEnabledConnectTool = true;
225 setHint(Hints.KEY_TOOL, Hints.CONNECTTOOL);
231 private static int mask(int mask, int mask2, boolean set) {
232 return set ? mask | mask2 : mask & ~mask2;
235 @EventHandler(priority = -1)
236 public boolean altToggled(KeyEvent ke) {
237 int mods = ke.stateMask;
238 boolean press = ke instanceof KeyPressedEvent;
239 boolean modifierPressed = false;
240 if (ke.keyCode == java.awt.event.KeyEvent.VK_ALT) {
241 mods = mask(mods, MouseEvent.ALT_MASK, press);
242 modifierPressed = true;
244 if (ke.keyCode == java.awt.event.KeyEvent.VK_ALT_GRAPH) {
245 mods = mask(mods, MouseEvent.ALT_GRAPH_MASK, press);
246 modifierPressed = true;
248 if (ke.keyCode == java.awt.event.KeyEvent.VK_SHIFT) {
249 mods = mask(mods, MouseEvent.SHIFT_MASK, press);
250 modifierPressed = true;
252 if (ke.keyCode == java.awt.event.KeyEvent.VK_CONTROL) {
253 mods = mask(mods, MouseEvent.CTRL_MASK, press);
254 modifierPressed = true;
256 if (ke.keyCode == java.awt.event.KeyEvent.VK_META) {
257 // TODO: NO MASK FOR META!
258 modifierPressed = true;
260 // Don't deny connecting when CTRL is marked pressed because ALT_GRAPH
261 // is actually ALT+CTRL in SWT. There's no way in SWT to tell apart
262 // CTRL+ALT and ALT GRAPH.
263 boolean otherModifiers = (mods & (MouseEvent.SHIFT_MASK)) != 0;
264 boolean altModifier = (mods & (MouseEvent.ALT_MASK | MouseEvent.ALT_GRAPH_MASK)) != 0;
265 if (modifierPressed) {
266 boolean altPressed = !otherModifiers && altModifier;
267 lastStateMask = mods;
269 IToolMode mode = getToolMode();
270 if (mode == Hints.POINTERTOOL) {
271 //System.out.println("TEMP++");
272 temporarilyEnabledConnectTool = true;
273 setHint(Hints.KEY_TOOL, Hints.CONNECTTOOL);
276 if (temporarilyEnabledConnectTool) {
277 //System.out.println("TEMP--");
278 temporarilyEnabledConnectTool = false;
279 setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
282 // Make sure that TerminalPainter updates its scene graph.
283 if (terminalPainter != null) {
284 terminalPainter.update(terminalPainter.highlightEnabled());
292 * @return <code>null</code> if current canvas transform is not invertible
294 public Shape getCanvasPickShape(Point2D controlPos) {
295 AffineTransform inverse = util.getInverseTransform();
299 double pd = getPickDistance();
300 Rectangle2D controlPickRect = new Rectangle2D.Double(controlPos.getX()-pd, controlPos.getY()-pd, pd*2+1, pd*2+1);
301 Shape canvasShape = GeometryUtils.transformShape(controlPickRect, inverse);
305 public List<TerminalInfo> pickTerminals(Point2D controlPos)
307 Shape canvasPickRect = getCanvasPickShape(controlPos);
308 if (canvasPickRect == null)
309 return Collections.emptyList();
310 return TerminalUtil.pickTerminals(diagram, canvasPickRect, true, true);
313 public TerminalInfo pickTerminal(Point2D controlPos)
315 Shape canvasPickRect = getCanvasPickShape(controlPos);
316 if (canvasPickRect == null)
318 TerminalInfo ti = TerminalUtil.pickTerminal(diagram, canvasPickRect);
322 @EventHandler(priority = TOOL_PRIORITY)
323 public boolean handlePress(MouseButtonPressedEvent me) {
326 if (me.button != MouseEvent.LEFT_BUTTON)
329 IToolMode mode = getToolMode();
331 // It may be that the mouse has come into this control
332 // from outside without focusing it and without any mouse
333 // buttons being pressed. If the user is pressing the
334 // connection modifier we need to temporarily enable connect
335 // mode here and now.
336 if (mode == Hints.POINTERTOOL && connectToolModifiersPressed(me.stateMask)) {
337 temporarilyEnabledConnectTool = true;
338 mode = Hints.CONNECTTOOL;
339 setHint(Hints.KEY_TOOL, Hints.CONNECTTOOL);
342 if (mode == Hints.CONNECTTOOL) {
343 Point2D curCanvasPos = util.controlToCanvas(me.controlPosition, null);
344 return checkInitiateConnectTool(me, curCanvasPos);
350 protected boolean checkInitiateConnectTool(MouseEvent me, Point2D mouseCanvasPos) {
352 IToolMode mode = getToolMode();
353 if (mode == Hints.CONNECTTOOL || connectToolModifiersPressed(me.stateMask)) {
354 IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);
355 TerminalInfo ti = pickTerminal(me.controlPosition);
357 ICanvasParticipant bsi = null;
359 if (advisor == null || advisor.canBeginConnection(null, ti.e, ti.t)) {
360 bsi = createConnectTool(ti, me.mouseId, mouseCanvasPos);
363 ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
364 if (snapAdvisor != null)
365 snapAdvisor.snap(mouseCanvasPos);
367 // Start connection out of thin air, without a terminal.
368 bsi = createConnectTool(null, me.mouseId, mouseCanvasPos);
371 // Did we catch anything?
373 startConnectTool(bsi);
381 protected void startConnectTool(ICanvasParticipant tool) {
382 getContext().add(tool);
383 //System.out.println("TEMP: " + temporarilyEnabledConnectTool);
384 if (temporarilyEnabledConnectTool) {
385 // Resets pointer tool back into use if necessary after
386 // connection has been finished or canceled.
387 getContext().addContextListener(new ToolModeResetter(tool));
391 @EventHandler(priority = TOOL_PRIORITY)
392 public boolean handleClick(MouseClickEvent me) {
393 //System.out.println(getClass().getSimpleName() + ": mouse clicked: @ " + me.time);
395 if (hasDoubleClickEdit() && me.clickCount == 2) {
396 if (handleDoubleClick(me))
400 if (!hasClickSelect()) return false;
401 if (!hasToolMode(Hints.POINTERTOOL)) return false;
403 // Don't handle any events where click count is more than 1 to prevent
404 // current diagram selection from bouncing around unnecessarily.
405 if (me.clickCount > 1)
408 boolean isLeft = me.button == MouseEvent.LEFT_BUTTON;
409 boolean isRight = me.button == MouseEvent.RIGHT_BUTTON;
410 if (!isLeft && !isRight) return false;
412 boolean popupWasVisible = wasPopupJustClosed(me);
413 boolean noModifiers = !anyModifierPressed(me);
414 boolean isShiftPressed = me.hasAllModifiers(MouseEvent.SHIFT_MASK);
416 assertDependencies();
419 double pickDist = getPickDistance();
420 Rectangle2D controlPickRect = new Rectangle2D.Double(me.controlPosition.getX()-pickDist, me.controlPosition.getY()-pickDist, pickDist*2+1, pickDist*2+1);
421 Shape canvasPickRect = GeometryUtils.transformShape(controlPickRect, util.getInverseTransform());
422 int selectionId = me.mouseId;
424 PickRequest req = new PickRequest(canvasPickRect);
425 req.pickPolicy = PickPolicy.PICK_INTERSECTING_OBJECTS;
426 req.pickSorter = pickSorter;
427 //req.pickSorter = PickRequest.PickSorter.CONNECTIONS_LAST;
428 List<IElement> pickables = new ArrayList<IElement>();
429 pickContext.pick(diagram, req, pickables);
431 Set<IElement> currentSelection = selection.getSelection(selectionId);
434 if (pickables.isEmpty()) {
435 if (!popupWasVisible) {
436 // Only clear selection on left button clicks.
438 selection.clear(selectionId);
442 if (/*!currentSelection.isEmpty() &&*/ noModifiers)
443 setHint(DiagramHints.SHOW_POPUP_MENU, me.controlPosition);
449 if ((me.stateMask & MouseEvent.CTRL_MASK) != 0) {
452 * - If the mouse points to an object not in the selection, add it to selection.
453 * - If the mouse points to multiple objects, add the first.
454 * - If all objects the mouse points are already in selection, remove one of them from selection.
456 IElement removable = null;
457 for (int i = pickables.size() - 1; i >= 0; --i) {
458 IElement pickable = pickables.get(i);
459 if (selection.add(selectionId, pickable)) {
463 removable = pickable;
465 // Do not perform rotating pick in toggle selection
466 // when only CTRL is pressed. Requires SHIFT+CTRL.
470 if (removable != null)
471 selection.remove(selectionId, removable);
478 if (isLeft && popupWasVisible)
479 // Popup menu is visible, just let it close
482 // Don't change selection on right clicks if there's more to pick
483 // than a single element.
484 if (isRight && pickables.size() > 1) {
485 IElement selectElement = singleElementAboveNonselectedConnections(currentSelection, pickables);
486 if (selectElement != null) {
487 selection.setSelection(selectionId, selectElement);
489 if (!currentSelection.isEmpty() && noModifiers)
490 setHint(DiagramHints.SHOW_POPUP_MENU, me.controlPosition);
495 * Select the one object the mouse points to. If multiple object
496 * are picked, select the one that is after the earliest by
497 * index of the current selection when shift is pressed. Otherwise
498 * always pick the topmost element.
500 IElement selectedPick = isShiftPressed
501 ? rotatingPick(currentSelection, pickables)
502 : pickables.get(pickables.size() - 1);
505 // 1. the selection would actually change
507 // 2.1. left button was pressed
509 // 2.2. right button was pressed and the element to-be-selected
510 // is NOT a part of the current selection
511 if (!Collections.singleton(selectedPick).equals(currentSelection)
512 && (isLeft || (isRight && !currentSelection.contains(selectedPick)))) {
513 selection.setSelection(selectionId, selectedPick);
516 if (isRight && pickables.size() == 1 && noModifiers) {
517 setHint(DiagramHints.SHOW_POPUP_MENU, me.controlPosition);
525 * A heuristic needed for implementing right-click diagram selection in a
528 * @param currentSelection
532 private IElement singleElementAboveNonselectedConnections(Set<IElement> currentSelection, List<IElement> pickables) {
533 if (pickables.isEmpty())
536 // Check that the pickable-list doesn't contain anything that is in the current selection.
537 if (!Collections.disjoint(currentSelection, pickables))
540 IElement top = pickables.get(pickables.size() - 1);
541 boolean elementOnTop = !PickRequest.PickFilter.FILTER_CONNECTIONS.accept(top);
544 for (int i = pickables.size() - 2; i >= 0; --i) {
545 IElement e = pickables.get(i);
546 if (!PickRequest.PickFilter.FILTER_CONNECTIONS.accept(e))
553 * Since there's seems to be no better method available for finding out if
554 * the SWT popup menu was just recently closed or not, we use the following
557 * SWT popup was just closed if it was closed < 300ms ago.
559 * Note that this is a very bad heuristic and may fail on slower machines or
560 * under heavy system load.
564 private boolean wasPopupJustClosed(Event event) {
565 Long popupCloseTime = getHint(DiagramHints.POPUP_MENU_HIDDEN);
566 if (popupCloseTime != null) {
567 long timeDiff = event.time - popupCloseTime;
568 //System.out.println("time diff: " + timeDiff);
569 if (timeDiff < 300) {
570 //System.out.println("POPUP WAS JUST CLOSED!");
574 //System.out.println("Popup has been closed for a while.");
578 boolean handleDoubleClick(MouseClickEvent me) {
579 //System.out.println("mouse double clicked: " + me);
580 if (!hasDoubleClickEdit()) return false;
581 if (me.button != MouseEvent.LEFT_BUTTON) return false;
582 if (getToolMode() != Hints.POINTERTOOL) return false;
583 if (me.clickCount < 2) return false;
586 double pickDist = getPickDistance();
587 Rectangle2D controlPickRect = new Rectangle2D.Double(me.controlPosition.getX()-pickDist, me.controlPosition.getY()-pickDist, pickDist*2+1, pickDist*2+1);
588 Shape canvasPickRect = GeometryUtils.transformShape(controlPickRect, util.getInverseTransform());
589 int selectionId = me.mouseId;
591 PickRequest req = new PickRequest(canvasPickRect);
592 req.pickPolicy = PickPolicy.PICK_INTERSECTING_OBJECTS;
593 List<IElement> pick = new ArrayList<IElement>();
594 pickContext.pick(diagram, req, pick);
597 if (pick.isEmpty()) {
598 selection.clear(selectionId);
602 IElement selectedPick = rotatingPick(selectionId, pick);
604 if (!selection.contains(selectionId, selectedPick)) {
605 selection.setSelection(selectionId, selectedPick);
608 CanvasUtils.sendCommand(getContext(), Commands.RENAME);
613 // Values shared by #handleDrag and #handleBoxSelect
614 private transient Point2D curCanvasDragPos = new Point2D.Double();
615 private transient Set<IElement> elementsToDrag = Collections.emptySet();
618 * Invoked before scene graph event handling and {@link #handleBoxSelect(MouseDragBegin)}.
621 * @see #handleBoxSelect(MouseDragBegin)
623 @EventHandler(priority = TOOL_PRIORITY)
624 public boolean handleDrag(MouseDragBegin me) {
625 if (!hasElementDrag() && !hasBoxSelect()) return false;
626 if (me.button != MouseEvent.LEFT_BUTTON) return false;
627 if (getToolMode() != Hints.POINTERTOOL) return false;
628 if (hasToolMode(me.mouseId)) return false;
630 boolean anyModifierPressed = me.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK);
631 boolean nonSelectionModifierPressed = me.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK
632 ^ (MouseEvent.SHIFT_MASK /*| MouseEvent.CTRL_MASK*/));
634 if (nonSelectionModifierPressed)
637 assertDependencies();
639 Point2D curCanvasPos = util.controlToCanvas(me.controlPosition, curCanvasDragPos);
640 PickRequest req = new PickRequest(me.startCanvasPos);
641 req.pickPolicy = PickRequest.PickPolicy.PICK_INTERSECTING_OBJECTS;
642 List<IElement> picks = new ArrayList<IElement>();
643 pickContext.pick(diagram, req, picks);
645 //System.out.println(picks);
646 if (picks.isEmpty()) {
647 // Widen the area of searching if nothing is found with point picking
648 double pickDist = getPickDistance();
649 Rectangle2D controlPickRect = new Rectangle2D.Double(me.controlPosition.getX()-pickDist, me.controlPosition.getY()-pickDist, pickDist*2+1, pickDist*2+1);
650 Shape canvasPickRect = GeometryUtils.transformShape(controlPickRect, util.getInverseTransform());
651 req = new PickRequest(canvasPickRect);
652 req.pickPolicy = PickRequest.PickPolicy.PICK_INTERSECTING_OBJECTS;
653 pickContext.pick(diagram, req, picks);
654 //System.out.println("2nd try: " + picks);
657 Set<IElement> sel = selection.getSelection(me.mouseId);
658 IElement topMostPick = picks.isEmpty() ? null : picks.get(picks.size() - 1);
659 Set<IElement> elementsToDrag = new HashSet<IElement>();
660 this.elementsToDrag = elementsToDrag;
662 if (!Collections.disjoint(sel, picks)) {
663 elementsToDrag.addAll(sel);
665 if (topMostPick != null && (sel.isEmpty() || !sel.contains(topMostPick))) {
666 selection.setSelection(me.mouseId, topMostPick);
667 sel = selection.getSelection(me.mouseId);
668 elementsToDrag.addAll(sel);
673 if (!elementsToDrag.isEmpty() && hasElementDnDDrag()) {
674 // To Be Implemented in the next Diagram data model.
676 if (!anyModifierPressed && !elementsToDrag.isEmpty() && hasElementDrag()) {
677 // Connections are not translatable, re-routing is in RouteGraphNode.
678 boolean onlyConnections = onlyConnections(elementsToDrag);
679 if (!onlyConnections) {
680 ICanvasParticipant tm = createTranslateTool(me.mouseId, me.startCanvasPos, curCanvasPos, elementsToDrag);
682 getContext().add(tm);
683 return !onlyConnections;
693 * Always invoked after after {@link #handleDrag(MouseDragBegin)} and scene
694 * graph event handling to prevent the box selection mode from being
695 * initiated before scene graph nodes have a chance to react.
698 * Note that this method assumes that <code>elementsToDrag</code> and
699 * <code>curCanvasPos</code> are already set by
700 * {@link #handleDrag(MouseDragBegin)}.
705 @EventHandler(priority = BOX_SELECT_PRIORITY)
706 public boolean handleBoxSelect(MouseDragBegin me) {
707 if (!hasBoxSelect()) return false;
708 if (me.button != MouseEvent.LEFT_BUTTON) return false;
709 if (getToolMode() != Hints.POINTERTOOL) return false;
710 if (hasToolMode(me.mouseId)) return false;
712 boolean nonSelectionModifierPressed = me.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK
713 ^ (MouseEvent.SHIFT_MASK /*| MouseEvent.CTRL_MASK*/));
714 if (nonSelectionModifierPressed)
717 if (!nonSelectionModifierPressed && elementsToDrag.isEmpty()) {
719 ICanvasParticipant bsm = createBoxSelectTool(me.mouseId, me.startCanvasPos, curCanvasDragPos, me.button, boxSelectMode);
721 getContext().add(bsm);
727 private static boolean onlyConnections(Set<IElement> elements) {
728 for (IElement e : elements)
729 if (!e.getElementClass().containsClass(ConnectionHandler.class))
734 private IElement rotatingPick(int selectionId, List<IElement> pickables) {
735 Set<IElement> sel = selection.getSelection(selectionId);
736 return rotatingPick(sel, pickables);
739 private IElement rotatingPick(Set<IElement> sel, List<IElement> pickables) {
740 int earliestIndex = pickables.size();
741 for (int i = pickables.size() - 1; i >= 0; --i) {
742 if (sel.contains(pickables.get(i))) {
747 if (earliestIndex == 0)
748 earliestIndex = pickables.size();
749 IElement selectedPick = pickables.get(earliestIndex - 1);
754 * Is mouse in some kind of mode?
758 boolean hasToolMode(int mouseId) {
759 for (AbstractMode am : getContext().getItemsByClass(AbstractMode.class))
760 if (am.mouseId==mouseId) return true;
764 boolean hasToolMode(IToolMode mode) {
765 return ObjectUtils.objectEquals(mode, getToolMode());
768 boolean hasToolMode(IToolMode... modes) {
769 IToolMode current = getToolMode();
772 for (IToolMode mode : modes)
773 if (current.equals(mode))
778 protected IToolMode getToolMode() {
779 return getHint(Hints.KEY_TOOL);
782 /// is box select enabled
783 protected boolean hasBoxSelect() {
787 /// is click select enabled
788 protected boolean hasClickSelect() {
792 /// is double click edit enabled
793 protected boolean hasDoubleClickEdit() {
794 return doubleClickEdit;
797 // is element drag enabled
798 protected boolean hasElementDrag() {
802 // is element drag enabled
803 protected boolean hasElementDnDDrag() {
804 return dndDragElement;
807 // is connect enabled
808 protected boolean connects() {
812 public double getPickDistance() {
813 Double pickDistance = getHint(KEY_PICK_DISTANCE);
814 return pickDistance == null ? PICK_DIST : Math.max(pickDistance, 0);
817 public PickPolicy getBoxSelectMode() {
818 return boxSelectMode;
821 public void setBoxSelectMode(PickPolicy boxSelectMode) {
822 this.boxSelectMode = boxSelectMode;
825 public void setSelectionEnabled(boolean select) {
826 this.clickSelect = select;
827 this.boxSelect = select;
828 if(select == false) { // Clear all selections if select is disabled
829 final int[] ids = selection.getSelectionIds();
831 ThreadUtils.asyncExec(getContext().getThreadAccess(), new Runnable() {
836 getContext().getContentContext().setDirty();
843 boolean anyModifierPressed(MouseEvent e) {
844 return e.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK);
847 boolean connectToolModifiersPressed(int stateMask) {
848 return (stateMask & (MouseEvent.ALT_MASK | MouseEvent.ALT_GRAPH_MASK)) != 0;
852 LINE10 = new Path2D.Double();
854 LINE10.lineTo(10, 0);
855 LINE10.lineTo(7, -3);
856 LINE10.moveTo(10, 0);
859 LINE15 = new Path2D.Double();
861 LINE15.lineTo(15, 0);
862 LINE15.lineTo(12, -3);
863 LINE15.moveTo(15, 0);
864 LINE15.lineTo(12, 3);
866 LINE20 = new Path2D.Double();
868 LINE20.lineTo(20, 0);
869 LINE20.lineTo(17, -3);
870 LINE20.moveTo(20, 0);
871 LINE20.lineTo(17, 3);
877 protected ICanvasParticipant createConnectTool(TerminalInfo ti, int mouseId, Point2D startCanvasPos) {
881 protected ICanvasParticipant createConnectToolWithTerminals(List<TerminalInfo> tis, int mouseId, Point2D startCanvasPos) {
885 protected ICanvasParticipant createTranslateTool(int mouseId, Point2D startCanvasPos, Point2D curCanvasPos, Set<IElement> elementsToDrag) {
886 return new TranslateMode(startCanvasPos, curCanvasPos, mouseId, elementsToDrag);
889 protected ICanvasParticipant createBoxSelectTool(int mouseId, Point2D startCanvasPos, Point2D curCanvasPos, int button, PickPolicy boxSelectMode) {
890 return new BoxSelectionMode(startCanvasPos, curCanvasPos, mouseId, button, boxSelectMode);
894 * A context listener for resetting tool mode back to pointer mode after the
895 * tracked participant has been removed.
897 protected class ToolModeResetter implements IContextListener<ICanvasParticipant> {
898 private ICanvasParticipant tracked;
899 public ToolModeResetter(ICanvasParticipant trackedParticipant) {
900 this.tracked = trackedParticipant;
903 public void itemAdded(IContext<ICanvasParticipant> sender, ICanvasParticipant item) {
906 public void itemRemoved(IContext<ICanvasParticipant> sender, ICanvasParticipant item) {
907 if (item == tracked) {
908 sender.removeContextListener(this);
909 if (!isRemoved() && !connectToolModifiersPressed(lastStateMask)) {
910 temporarilyEnabledConnectTool = false;
911 setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);