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(getContext(), diagram, canvasPickRect, true, true);
313 public TerminalInfo pickTerminal(Point2D controlPos)
315 Shape canvasPickRect = getCanvasPickShape(controlPos);
316 if (canvasPickRect == null)
318 TerminalInfo ti = TerminalUtil.pickTerminal(getContext(), 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).context(getContext());
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);
476 boolean result = false;
480 if (isLeft && popupWasVisible)
481 // Popup menu is visible, just let it close
484 // Don't change selection on right clicks if there's more to pick
485 // than a single element.
486 if (isRight && pickables.size() > 1) {
487 IElement selectElement = singleElementAboveNonselectedConnections(currentSelection, pickables);
488 if (selectElement != null) {
489 selection.setSelection(selectionId, selectElement);
491 if (!currentSelection.isEmpty() && noModifiers)
492 setHint(DiagramHints.SHOW_POPUP_MENU, me.controlPosition);
497 * Select the one object the mouse points to. If multiple object
498 * are picked, select the one that is after the earliest by
499 * index of the current selection when shift is pressed. Otherwise
500 * always pick the topmost element.
502 IElement selectedPick = isShiftPressed
503 ? rotatingPick(currentSelection, pickables)
504 : pickables.get(pickables.size() - 1);
507 // 1. the selection would actually change
509 // 2.1. left button was pressed
511 // 2.2. right button was pressed and the element to-be-selected
512 // is NOT a part of the current selection
513 if (!Collections.singleton(selectedPick).equals(currentSelection)
514 && (isLeft || (isRight && !currentSelection.contains(selectedPick)))) {
515 selection.setSelection(selectionId, selectedPick);
520 if (isRight && pickables.size() == 1 && noModifiers) {
521 setHint(DiagramHints.SHOW_POPUP_MENU, me.controlPosition);
529 * A heuristic needed for implementing right-click diagram selection in a
532 * @param currentSelection
536 private IElement singleElementAboveNonselectedConnections(Set<IElement> currentSelection, List<IElement> pickables) {
537 if (pickables.isEmpty())
540 // Check that the pickable-list doesn't contain anything that is in the current selection.
541 if (!Collections.disjoint(currentSelection, pickables))
544 IElement top = pickables.get(pickables.size() - 1);
545 boolean elementOnTop = !PickRequest.PickFilter.FILTER_CONNECTIONS.accept(top);
548 for (int i = pickables.size() - 2; i >= 0; --i) {
549 IElement e = pickables.get(i);
550 if (!PickRequest.PickFilter.FILTER_CONNECTIONS.accept(e))
557 * Since there's seems to be no better method available for finding out if
558 * the SWT popup menu was just recently closed or not, we use the following
561 * SWT popup was just closed if it was closed < 300ms ago.
563 * Note that this is a very bad heuristic and may fail on slower machines or
564 * under heavy system load.
568 private boolean wasPopupJustClosed(Event event) {
569 Long popupCloseTime = getHint(DiagramHints.POPUP_MENU_HIDDEN);
570 if (popupCloseTime != null) {
571 long timeDiff = event.time - popupCloseTime;
572 //System.out.println("time diff: " + timeDiff);
573 if (timeDiff < 300) {
574 //System.out.println("POPUP WAS JUST CLOSED!");
578 //System.out.println("Popup has been closed for a while.");
582 boolean handleDoubleClick(MouseClickEvent me) {
583 //System.out.println("mouse double clicked: " + me);
584 if (!hasDoubleClickEdit()) return false;
585 if (me.button != MouseEvent.LEFT_BUTTON) return false;
586 if (getToolMode() != Hints.POINTERTOOL) return false;
587 if (me.clickCount < 2) return false;
590 double pickDist = getPickDistance();
591 Rectangle2D controlPickRect = new Rectangle2D.Double(me.controlPosition.getX()-pickDist, me.controlPosition.getY()-pickDist, pickDist*2+1, pickDist*2+1);
592 Shape canvasPickRect = GeometryUtils.transformShape(controlPickRect, util.getInverseTransform());
593 int selectionId = me.mouseId;
595 PickRequest req = new PickRequest(canvasPickRect).context(getContext());
596 req.pickPolicy = PickPolicy.PICK_INTERSECTING_OBJECTS;
597 List<IElement> pick = new ArrayList<IElement>();
598 pickContext.pick(diagram, req, pick);
601 if (pick.isEmpty()) {
602 selection.clear(selectionId);
606 IElement selectedPick = rotatingPick(selectionId, pick);
608 if (!selection.contains(selectionId, selectedPick)) {
609 selection.setSelection(selectionId, selectedPick);
612 CanvasUtils.sendCommand(getContext(), Commands.RENAME);
617 // Values shared by #handleDrag and #handleBoxSelect
618 private transient Point2D curCanvasDragPos = new Point2D.Double();
619 private transient Set<IElement> elementsToDrag = Collections.emptySet();
622 * Invoked before scene graph event handling and {@link #handleBoxSelect(MouseDragBegin)}.
625 * @see #handleBoxSelect(MouseDragBegin)
627 @EventHandler(priority = TOOL_PRIORITY)
628 public boolean handleDrag(MouseDragBegin me) {
629 if (!hasElementDrag() && !hasBoxSelect()) return false;
630 if (me.button != MouseEvent.LEFT_BUTTON) return false;
631 if (getToolMode() != Hints.POINTERTOOL) return false;
632 if (hasToolMode(me.mouseId)) return false;
634 boolean anyModifierPressed = me.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK);
635 boolean nonSelectionModifierPressed = me.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK
636 ^ (MouseEvent.SHIFT_MASK /*| MouseEvent.CTRL_MASK*/));
638 if (nonSelectionModifierPressed)
641 assertDependencies();
643 Point2D curCanvasPos = util.controlToCanvas(me.controlPosition, curCanvasDragPos);
644 PickRequest req = new PickRequest(me.startCanvasPos).context(getContext());
645 req.pickPolicy = PickRequest.PickPolicy.PICK_INTERSECTING_OBJECTS;
646 List<IElement> picks = new ArrayList<IElement>();
647 pickContext.pick(diagram, req, picks);
649 //System.out.println(picks);
650 if (picks.isEmpty()) {
651 // Widen the area of searching if nothing is found with point picking
652 double pickDist = getPickDistance();
653 Rectangle2D controlPickRect = new Rectangle2D.Double(me.controlPosition.getX()-pickDist, me.controlPosition.getY()-pickDist, pickDist*2+1, pickDist*2+1);
654 Shape canvasPickRect = GeometryUtils.transformShape(controlPickRect, util.getInverseTransform());
655 req = new PickRequest(canvasPickRect).context(getContext());
656 req.pickPolicy = PickRequest.PickPolicy.PICK_INTERSECTING_OBJECTS;
657 pickContext.pick(diagram, req, picks);
658 //System.out.println("2nd try: " + picks);
661 Set<IElement> sel = selection.getSelection(me.mouseId);
662 IElement topMostPick = picks.isEmpty() ? null : picks.get(picks.size() - 1);
663 Set<IElement> elementsToDrag = new HashSet<IElement>();
664 this.elementsToDrag = elementsToDrag;
666 if (!Collections.disjoint(sel, picks)) {
667 elementsToDrag.addAll(sel);
669 if (topMostPick != null && (sel.isEmpty() || !sel.contains(topMostPick))) {
670 selection.setSelection(me.mouseId, topMostPick);
671 sel = selection.getSelection(me.mouseId);
672 elementsToDrag.addAll(sel);
677 if (!elementsToDrag.isEmpty() && hasElementDnDDrag()) {
678 // To Be Implemented in the next Diagram data model.
680 if (!anyModifierPressed && !elementsToDrag.isEmpty() && hasElementDrag()) {
681 // Connections are not translatable, re-routing is in RouteGraphNode.
682 boolean onlyConnections = onlyConnections(elementsToDrag);
683 if (!onlyConnections) {
684 ICanvasParticipant tm = createTranslateTool(me.mouseId, me.startCanvasPos, curCanvasPos, elementsToDrag);
686 getContext().add(tm);
687 return !onlyConnections;
697 * Always invoked after after {@link #handleDrag(MouseDragBegin)} and scene
698 * graph event handling to prevent the box selection mode from being
699 * initiated before scene graph nodes have a chance to react.
702 * Note that this method assumes that <code>elementsToDrag</code> and
703 * <code>curCanvasPos</code> are already set by
704 * {@link #handleDrag(MouseDragBegin)}.
709 @EventHandler(priority = BOX_SELECT_PRIORITY)
710 public boolean handleBoxSelect(MouseDragBegin me) {
711 if (!hasBoxSelect()) return false;
712 if (me.button != MouseEvent.LEFT_BUTTON) return false;
713 if (getToolMode() != Hints.POINTERTOOL) return false;
714 if (hasToolMode(me.mouseId)) return false;
716 boolean nonSelectionModifierPressed = me.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK
717 ^ (MouseEvent.SHIFT_MASK /*| MouseEvent.CTRL_MASK*/));
718 if (nonSelectionModifierPressed)
721 if (!nonSelectionModifierPressed && elementsToDrag.isEmpty()) {
723 ICanvasParticipant bsm = createBoxSelectTool(me.mouseId, me.startCanvasPos, curCanvasDragPos, me.button, boxSelectMode);
725 getContext().add(bsm);
731 private static boolean onlyConnections(Set<IElement> elements) {
732 for (IElement e : elements)
733 if (!e.getElementClass().containsClass(ConnectionHandler.class))
738 private IElement rotatingPick(int selectionId, List<IElement> pickables) {
739 Set<IElement> sel = selection.getSelection(selectionId);
740 return rotatingPick(sel, pickables);
743 private IElement rotatingPick(Set<IElement> sel, List<IElement> pickables) {
744 int earliestIndex = pickables.size();
745 for (int i = pickables.size() - 1; i >= 0; --i) {
746 if (sel.contains(pickables.get(i))) {
751 if (earliestIndex == 0)
752 earliestIndex = pickables.size();
753 IElement selectedPick = pickables.get(earliestIndex - 1);
758 * Is mouse in some kind of mode?
762 boolean hasToolMode(int mouseId) {
763 for (AbstractMode am : getContext().getItemsByClass(AbstractMode.class))
764 if (am.mouseId==mouseId) return true;
768 boolean hasToolMode(IToolMode mode) {
769 return ObjectUtils.objectEquals(mode, getToolMode());
772 boolean hasToolMode(IToolMode... modes) {
773 IToolMode current = getToolMode();
776 for (IToolMode mode : modes)
777 if (current.equals(mode))
782 protected IToolMode getToolMode() {
783 return getHint(Hints.KEY_TOOL);
786 /// is box select enabled
787 protected boolean hasBoxSelect() {
791 /// is click select enabled
792 protected boolean hasClickSelect() {
796 /// is double click edit enabled
797 protected boolean hasDoubleClickEdit() {
798 return doubleClickEdit;
801 // is element drag enabled
802 protected boolean hasElementDrag() {
806 // is element drag enabled
807 protected boolean hasElementDnDDrag() {
808 return dndDragElement;
811 // is connect enabled
812 protected boolean connects() {
816 public double getPickDistance() {
817 Double pickDistance = getHint(KEY_PICK_DISTANCE);
818 return pickDistance == null ? PICK_DIST : Math.max(pickDistance, 0);
821 public PickPolicy getBoxSelectMode() {
822 return boxSelectMode;
825 public void setBoxSelectMode(PickPolicy boxSelectMode) {
826 this.boxSelectMode = boxSelectMode;
829 public void setSelectionEnabled(boolean select) {
830 this.clickSelect = select;
831 this.boxSelect = select;
832 if(select == false) { // Clear all selections if select is disabled
833 final int[] ids = selection.getSelectionIds();
835 ThreadUtils.asyncExec(getContext().getThreadAccess(), new Runnable() {
840 getContext().getContentContext().setDirty();
847 boolean anyModifierPressed(MouseEvent e) {
848 return e.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK);
851 boolean connectToolModifiersPressed(int stateMask) {
852 return (stateMask & (MouseEvent.ALT_MASK | MouseEvent.ALT_GRAPH_MASK)) != 0;
856 LINE10 = new Path2D.Double();
858 LINE10.lineTo(10, 0);
859 LINE10.lineTo(7, -3);
860 LINE10.moveTo(10, 0);
863 LINE15 = new Path2D.Double();
865 LINE15.lineTo(15, 0);
866 LINE15.lineTo(12, -3);
867 LINE15.moveTo(15, 0);
868 LINE15.lineTo(12, 3);
870 LINE20 = new Path2D.Double();
872 LINE20.lineTo(20, 0);
873 LINE20.lineTo(17, -3);
874 LINE20.moveTo(20, 0);
875 LINE20.lineTo(17, 3);
881 protected ICanvasParticipant createConnectTool(TerminalInfo ti, int mouseId, Point2D startCanvasPos) {
885 protected ICanvasParticipant createConnectToolWithTerminals(List<TerminalInfo> tis, int mouseId, Point2D startCanvasPos) {
889 protected ICanvasParticipant createTranslateTool(int mouseId, Point2D startCanvasPos, Point2D curCanvasPos, Set<IElement> elementsToDrag) {
890 return new TranslateMode(startCanvasPos, curCanvasPos, mouseId, elementsToDrag);
893 protected ICanvasParticipant createBoxSelectTool(int mouseId, Point2D startCanvasPos, Point2D curCanvasPos, int button, PickPolicy boxSelectMode) {
894 return new BoxSelectionMode(startCanvasPos, curCanvasPos, mouseId, button, boxSelectMode);
898 * A context listener for resetting tool mode back to pointer mode after the
899 * tracked participant has been removed.
901 protected class ToolModeResetter implements IContextListener<ICanvasParticipant> {
902 private ICanvasParticipant tracked;
903 public ToolModeResetter(ICanvasParticipant trackedParticipant) {
904 this.tracked = trackedParticipant;
907 public void itemAdded(IContext<ICanvasParticipant> sender, ICanvasParticipant item) {
910 public void itemRemoved(IContext<ICanvasParticipant> sender, ICanvasParticipant item) {
911 if (item == tracked) {
912 sender.removeContextListener(this);
913 if (!isRemoved() && !connectToolModifiersPressed(lastStateMask)) {
914 temporarilyEnabledConnectTool = false;
915 setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);