]> gerrit.simantics Code Review - simantics/platform.git/blob
33b4402db56b46dfc738a5aea43f17445133318d
[simantics/platform.git] /
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 package org.simantics.g2d.diagram.participant.pointertool;
13
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;
23 import java.util.Set;
24
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;
70
71 /**
72  * Pointer tool does the following operations with mouse:
73  * <ul>
74  * <li>Selections</li>
75  * <li>Scale</li>
76  * <li>Rotate</li>
77  * <li>Translate</li>
78  * <li>Draws connections (requires re-implementing
79  * {@link #createConnectTool(TerminalInfo, int, Point2D)})</li>
80  * </ul>
81  * 
82  * Pointer tool is active only when {@link Hints#KEY_TOOL} is
83  * {@value Hints#POINTERTOOL}.
84  * 
85  * @author Toni Kalajainen
86  */
87 public class PointerInteractor extends AbstractDiagramParticipant {
88
89     /**
90      * A hint key for terminal pick distance in control pixels.
91      * @see #PICK_DIST
92      */
93     public static final Key KEY_PICK_DISTANCE = new KeyOf(Double.class, "PICK_DISTANCE");
94
95     /**
96      * Default terminal pick distance in control pixels.
97      * @see #DEFAULT_PICK_DISTANCE
98      */
99     public static final double PICK_DIST = 10;
100
101     /**
102      * @see #altToggled(KeyEvent)
103      */
104     protected int              lastStateMask;
105
106     /**
107      * @see #altToggled(KeyEvent)
108      */
109     protected boolean          temporarilyEnabledConnectTool = false;
110
111     public class DefaultHoverStrategy extends ChainedHoverStrategy {
112         public DefaultHoverStrategy(TerminalHoverStrategy orig) {
113             super(orig);
114         }
115         @Override
116         public boolean highlightEnabled() {
117             if (Hints.CONNECTTOOL.equals(getToolMode()))
118                 return true;
119
120             boolean ct = connectToolModifiersPressed(lastStateMask);
121             //System.out.println("highlightEnabled: " + String.format("%x", lastStateMask) + " : " + ct);
122             return ct;
123         }
124         @Override
125         public boolean canHighlight(TerminalInfo ti) {
126             //boolean alt = (lastStateMask & MouseEvent.ALT_MASK) != 0;
127             //System.out.println("canHighlight: " + String.format("%x", lastStateMask) + " : " + alt);
128             //if (!alt)
129             //   return false;
130             IConnectionAdvisor advisor = diagram.getHint(DiagramHints.CONNECTION_ADVISOR);
131             return advisor == null || advisor.canBeginConnection(null, ti.e, ti.t);
132         }
133     }
134
135     @Dependency Selection selection;
136     @Dependency KeyUtil keys;
137     @Dependency TransformUtil util;
138     @Dependency PickContext pickContext;
139     @Dependency MouseUtil mice;
140     @Reference TerminalPainter terminalPainter;
141
142     /**
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}.
148      */
149     public static final int TOOL_PRIORITY = 1 << 21;
150
151     /**
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
156      * events.
157      */
158     public static final int BOX_SELECT_PRIORITY = 1 << 19;
159
160     private static final Path2D LINE10;
161     private static final Path2D LINE15;
162     private static final Path2D LINE20;
163
164     boolean clickSelect;
165     boolean boxSelect;
166     boolean dragElement, dndDragElement;
167     boolean connect;
168     boolean doubleClickEdit;
169     protected IElementClassProvider elementClassProvider;
170
171     PickPolicy boxSelectMode = PickPolicy.PICK_CONTAINED_OBJECTS;
172
173     DefaultHoverStrategy hoverStrategy;
174
175     private PickSorter pickSorter;
176     
177     public PointerInteractor() {
178         this(true, true, true, false, true, false, ElementClassProviders.staticProvider(null), null);
179     }
180
181     public PointerInteractor(PickSorter pickSorter) {
182         this(true, true, true, false, true, false, ElementClassProviders.staticProvider(null), pickSorter);
183     }
184
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);
187     }
188
189     public PointerInteractor(boolean clickSelect, boolean boxSelect, boolean dragElement, boolean dndDragElement, boolean connect, boolean doubleClickEdit, IElementClassProvider ecp, PickSorter pickSorter) {
190         super();
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;
199     }
200
201     @Override
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);
206     }
207
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);
215             }
216         } else {
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))
223             {
224                 temporarilyEnabledConnectTool = true;
225                 setHint(Hints.KEY_TOOL, Hints.CONNECTTOOL);
226             }
227         }
228         return false;
229     }
230
231     private static int mask(int mask, int mask2, boolean set) {
232         return set ? mask | mask2 : mask & ~mask2;
233     }
234
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;
243         }
244         if (ke.keyCode == java.awt.event.KeyEvent.VK_ALT_GRAPH) {
245             mods = mask(mods, MouseEvent.ALT_GRAPH_MASK, press);
246             modifierPressed = true;
247         }
248         if (ke.keyCode == java.awt.event.KeyEvent.VK_SHIFT) {
249             mods = mask(mods, MouseEvent.SHIFT_MASK, press);
250             modifierPressed = true;
251         }
252         if (ke.keyCode == java.awt.event.KeyEvent.VK_CONTROL) {
253             mods = mask(mods, MouseEvent.CTRL_MASK, press);
254             modifierPressed = true;
255         }
256         if (ke.keyCode == java.awt.event.KeyEvent.VK_META) {
257             // TODO: NO MASK FOR META!
258             modifierPressed = true;
259         }
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;
268             if (altPressed) {
269                 IToolMode mode = getToolMode();
270                 if (mode == Hints.POINTERTOOL) {
271                     //System.out.println("TEMP++");
272                     temporarilyEnabledConnectTool = true;
273                     setHint(Hints.KEY_TOOL, Hints.CONNECTTOOL);
274                 }
275             } else {
276                 if (temporarilyEnabledConnectTool) {
277                     //System.out.println("TEMP--");
278                     temporarilyEnabledConnectTool = false;
279                     setHint(Hints.KEY_TOOL, Hints.POINTERTOOL);
280                 }
281             }
282             // Make sure that TerminalPainter updates its scene graph.
283             if (terminalPainter != null) {
284                 terminalPainter.update(terminalPainter.highlightEnabled());
285             }
286         }
287         return false;
288     }
289
290     /**
291      * @param controlPos
292      * @return <code>null</code> if current canvas transform is not invertible
293      */
294     public Shape getCanvasPickShape(Point2D controlPos) {
295         AffineTransform inverse = util.getInverseTransform();
296         if (inverse == null)
297             return null;
298
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);
302         return canvasShape;
303     }
304
305     public List<TerminalInfo> pickTerminals(Point2D controlPos)
306     {
307         Shape canvasPickRect = getCanvasPickShape(controlPos);
308         if (canvasPickRect == null)
309             return Collections.emptyList();
310         return TerminalUtil.pickTerminals(diagram, canvasPickRect, true, true);
311     }
312
313     public TerminalInfo pickTerminal(Point2D controlPos)
314     {
315         Shape canvasPickRect = getCanvasPickShape(controlPos);
316         if (canvasPickRect == null)
317             return null;
318         TerminalInfo ti = TerminalUtil.pickTerminal(diagram, canvasPickRect);
319         return ti;
320     }
321
322     @EventHandler(priority = TOOL_PRIORITY)
323     public boolean handlePress(MouseButtonPressedEvent me) {
324         if (!connects())
325             return false;
326         if (me.button != MouseEvent.LEFT_BUTTON)
327             return false;
328
329         IToolMode mode = getToolMode();
330
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);
340         }
341
342         if (mode == Hints.CONNECTTOOL) {
343             Point2D curCanvasPos = util.controlToCanvas(me.controlPosition, null);
344             return checkInitiateConnectTool(me, curCanvasPos);
345         }
346
347         return false;
348     }
349
350     protected boolean checkInitiateConnectTool(MouseEvent me, Point2D mouseCanvasPos) {
351         // Pick Terminal
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);
356
357             ICanvasParticipant bsi = null;
358             if (ti != null) {
359                 if (advisor == null || advisor.canBeginConnection(null, ti.e, ti.t)) {
360                     bsi = createConnectTool(ti, me.mouseId, mouseCanvasPos);
361                 }
362             } else {
363                 ISnapAdvisor snapAdvisor = getHint(DiagramHints.SNAP_ADVISOR);
364                 if (snapAdvisor != null)
365                     snapAdvisor.snap(mouseCanvasPos);
366
367                 // Start connection out of thin air, without a terminal.
368                 bsi = createConnectTool(null, me.mouseId, mouseCanvasPos);
369             }
370
371             // Did we catch anything?
372             if (bsi != null) {
373                 startConnectTool(bsi);
374                 return true;
375             }
376         }
377
378         return false;
379     }
380
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));
388         }
389     }
390
391     @EventHandler(priority = TOOL_PRIORITY)
392     public boolean handleClick(MouseClickEvent me) {
393         //System.out.println(getClass().getSimpleName() + ": mouse clicked: @ " + me.time);
394
395         if (hasDoubleClickEdit() && me.clickCount == 2) {
396             if (handleDoubleClick(me))
397                 return true;
398         }
399
400         if (!hasClickSelect()) return false;
401         if (!hasToolMode(Hints.POINTERTOOL)) return false;
402
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)
406             return false;
407
408         boolean isLeft = me.button == MouseEvent.LEFT_BUTTON;
409         boolean isRight = me.button == MouseEvent.RIGHT_BUTTON;
410         if (!isLeft && !isRight) return false;
411
412         boolean popupWasVisible = wasPopupJustClosed(me);
413         boolean noModifiers = !anyModifierPressed(me);
414         boolean isShiftPressed = me.hasAllModifiers(MouseEvent.SHIFT_MASK);
415
416         assertDependencies();
417
418         // Pick Terminal
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;
423
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);
430
431         Set<IElement> currentSelection = selection.getSelection(selectionId);
432
433         // Clear selection
434         if (pickables.isEmpty()) {
435             if (!popupWasVisible) {
436                 // Only clear selection on left button clicks.
437                 if (isLeft) {
438                     selection.clear(selectionId);
439                 }
440             }
441             if (isRight) {
442                 if (/*!currentSelection.isEmpty() &&*/ noModifiers)
443                     setHint(DiagramHints.SHOW_POPUP_MENU, me.controlPosition);
444             }
445             return false;
446         }
447
448         // Toggle select
449         if ((me.stateMask & MouseEvent.CTRL_MASK) != 0) {
450             if (isLeft) {
451                 /*
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.
455                  */
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)) {
460                         removable = null;
461                         break;
462                     } else
463                         removable = pickable;
464
465                     // Do not perform rotating pick in toggle selection
466                     // when only CTRL is pressed. Requires SHIFT+CTRL.
467                     if (!isShiftPressed)
468                         break;
469                 }
470                 if (removable != null)
471                     selection.remove(selectionId, removable);
472             }
473             return false;
474         }
475
476         // Click Select
477         {
478             if (isLeft && popupWasVisible)
479                 // Popup menu is visible, just let it close
480                 return false;
481
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);
488                 }
489                 if (!currentSelection.isEmpty() && noModifiers)
490                     setHint(DiagramHints.SHOW_POPUP_MENU, me.controlPosition);
491                 return false;
492             }
493
494             /*
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.
499              */
500             IElement selectedPick = isShiftPressed
501                     ? rotatingPick(currentSelection, pickables)
502                             : pickables.get(pickables.size() - 1);
503
504             // Only select when
505             // 1. the selection would actually change
506             // AND
507             //   2.1. left button was pressed
508             //   OR
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);
514             }
515
516             if (isRight && pickables.size() == 1 && noModifiers) {
517                 setHint(DiagramHints.SHOW_POPUP_MENU, me.controlPosition);
518             }
519         }
520
521         return false;
522     }
523
524     /**
525      * A heuristic needed for implementing right-click diagram selection in a
526      * sensible manner.
527      * 
528      * @param currentSelection
529      * @param pickables
530      * @return
531      */
532     private IElement singleElementAboveNonselectedConnections(Set<IElement> currentSelection, List<IElement> pickables) {
533         if (pickables.isEmpty())
534             return null;
535
536         // Check that the pickable-list doesn't contain anything that is in the current selection.
537         if (!Collections.disjoint(currentSelection, pickables))
538             return null;
539
540         IElement top = pickables.get(pickables.size() - 1);
541         boolean elementOnTop = !PickRequest.PickFilter.FILTER_CONNECTIONS.accept(top);
542         if (!elementOnTop)
543             return null;
544         for (int i = pickables.size() - 2; i >= 0; --i) {
545             IElement e = pickables.get(i);
546             if (!PickRequest.PickFilter.FILTER_CONNECTIONS.accept(e))
547                 return null;
548         }
549         return top;
550     }
551
552     /**
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
555      * heuristic:
556      * 
557      * SWT popup was just closed if it was closed < 300ms ago.
558      * 
559      * Note that this is a very bad heuristic and may fail on slower machines or
560      * under heavy system load.
561      * 
562      * @return
563      */
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!");
571                 return true;
572             }
573         }
574         //System.out.println("Popup has been closed for a while.");
575         return false;
576     }
577
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;
584
585         // Pick Terminal
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;
590
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);
595
596         // Clear selection
597         if (pick.isEmpty()) {
598             selection.clear(selectionId);
599             return false;
600         }
601
602         IElement selectedPick = rotatingPick(selectionId, pick);
603
604         if (!selection.contains(selectionId, selectedPick)) {
605             selection.setSelection(selectionId, selectedPick);
606         }
607
608         CanvasUtils.sendCommand(getContext(), Commands.RENAME);
609
610         return false;
611     }
612
613     // Values shared by #handleDrag and #handleBoxSelect
614     private transient Point2D curCanvasDragPos = new Point2D.Double();
615     private transient Set<IElement> elementsToDrag = Collections.emptySet();
616
617     /**
618      * Invoked before scene graph event handling and {@link #handleBoxSelect(MouseDragBegin)}.
619      * @param me
620      * @return
621      * @see #handleBoxSelect(MouseDragBegin)
622      */
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;
629
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*/));
633
634         if (nonSelectionModifierPressed)
635             return false;
636
637         assertDependencies();
638
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);
644
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);
655         }
656
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;
661
662         if (!Collections.disjoint(sel, picks)) {
663             elementsToDrag.addAll(sel);
664         } else {
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);
669             }
670         }
671
672         // Drag Elements
673         if (!elementsToDrag.isEmpty() && hasElementDnDDrag()) {
674             // To Be Implemented in the next Diagram data model.
675         } else {
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);
681                     if (tm != null) {
682                         getContext().add(tm);
683                         return !onlyConnections;
684                     }
685                 }
686             }
687         }
688
689         return false;
690     }
691
692     /**
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.
696      * 
697      * <p>
698      * Note that this method assumes that <code>elementsToDrag</code> and
699      * <code>curCanvasPos</code> are already set by
700      * {@link #handleDrag(MouseDragBegin)}.
701      * 
702      * @param me
703      * @return
704      */
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;
711
712         boolean nonSelectionModifierPressed = me.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK
713                 ^ (MouseEvent.SHIFT_MASK /*| MouseEvent.CTRL_MASK*/));
714         if (nonSelectionModifierPressed)
715             return false;
716
717         if (!nonSelectionModifierPressed && elementsToDrag.isEmpty()) {
718             // Box Select
719             ICanvasParticipant bsm = createBoxSelectTool(me.mouseId, me.startCanvasPos, curCanvasDragPos, me.button, boxSelectMode);
720             if (bsm != null)
721                 getContext().add(bsm);
722         }
723
724         return false;
725     }
726
727     private static boolean onlyConnections(Set<IElement> elements) {
728         for (IElement e : elements)
729             if (!e.getElementClass().containsClass(ConnectionHandler.class))
730                 return false;
731         return true;
732     }
733
734     private IElement rotatingPick(int selectionId, List<IElement> pickables) {
735         Set<IElement> sel = selection.getSelection(selectionId);
736         return rotatingPick(sel, pickables);
737     }
738
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))) {
743                 earliestIndex = i;
744                 break;
745             }
746         }
747         if (earliestIndex == 0)
748             earliestIndex = pickables.size();
749         IElement selectedPick = pickables.get(earliestIndex - 1);
750         return selectedPick;
751     }
752
753     /**
754      * Is mouse in some kind of mode?
755      * @param mouseId
756      * @return
757      */
758     boolean hasToolMode(int mouseId) {
759         for (AbstractMode am : getContext().getItemsByClass(AbstractMode.class))
760             if (am.mouseId==mouseId) return true;
761         return false;
762     }
763
764     boolean hasToolMode(IToolMode mode) {
765         return ObjectUtils.objectEquals(mode, getToolMode());
766     }
767
768     boolean hasToolMode(IToolMode... modes) {
769         IToolMode current = getToolMode();
770         if (current == null)
771             return false;
772         for (IToolMode mode : modes)
773             if (current.equals(mode))
774                 return true;
775         return false;
776     }
777
778     protected IToolMode getToolMode() {
779         return getHint(Hints.KEY_TOOL);
780     }
781
782     /// is box select enabled
783     protected boolean hasBoxSelect() {
784         return boxSelect;
785     }
786
787     /// is click select enabled
788     protected boolean hasClickSelect() {
789         return clickSelect;
790     }
791
792     /// is double click edit enabled
793     protected boolean hasDoubleClickEdit() {
794         return doubleClickEdit;
795     }
796
797     // is element drag enabled
798     protected boolean hasElementDrag() {
799         return dragElement;
800     }
801
802     // is element drag enabled
803     protected boolean hasElementDnDDrag() {
804         return dndDragElement;
805     }
806
807     // is connect enabled
808     protected boolean connects() {
809         return connect;
810     }
811
812     public double getPickDistance() {
813         Double pickDistance = getHint(KEY_PICK_DISTANCE);
814         return pickDistance == null ? PICK_DIST : Math.max(pickDistance, 0);
815     }
816
817     public PickPolicy getBoxSelectMode() {
818         return boxSelectMode;
819     }
820
821     public void setBoxSelectMode(PickPolicy boxSelectMode) {
822         this.boxSelectMode = boxSelectMode;
823     }
824
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();
830             if(ids.length > 0) {
831                 ThreadUtils.asyncExec(getContext().getThreadAccess(), new Runnable() {
832                     @Override
833                     public void run() {
834                         for(int id : ids)
835                             selection.clear(id);
836                         getContext().getContentContext().setDirty();
837                     }
838                 });
839             }
840         }
841     }
842
843     boolean anyModifierPressed(MouseEvent e) {
844         return e.hasAnyModifier(MouseEvent.ALL_MODIFIERS_MASK);
845     }
846
847     boolean connectToolModifiersPressed(int stateMask) {
848         return (stateMask & (MouseEvent.ALT_MASK | MouseEvent.ALT_GRAPH_MASK)) != 0;
849     }
850
851     static {
852         LINE10 = new Path2D.Double();
853         LINE10.moveTo(0, 0);
854         LINE10.lineTo(10, 0);
855         LINE10.lineTo(7, -3);
856         LINE10.moveTo(10, 0);
857         LINE10.lineTo(7, 3);
858
859         LINE15 = new Path2D.Double();
860         LINE15.moveTo(0, 0);
861         LINE15.lineTo(15, 0);
862         LINE15.lineTo(12, -3);
863         LINE15.moveTo(15, 0);
864         LINE15.lineTo(12, 3);
865
866         LINE20 = new Path2D.Double();
867         LINE20.moveTo(0, 0);
868         LINE20.lineTo(20, 0);
869         LINE20.lineTo(17, -3);
870         LINE20.moveTo(20, 0);
871         LINE20.lineTo(17, 3);
872
873     }
874
875     // CUSTOMIZE
876
877     protected ICanvasParticipant createConnectTool(TerminalInfo ti, int mouseId, Point2D startCanvasPos) {
878         return null;
879     }
880
881     protected ICanvasParticipant createConnectToolWithTerminals(List<TerminalInfo> tis, int mouseId, Point2D startCanvasPos) {
882         return null;
883     }
884
885     protected ICanvasParticipant createTranslateTool(int mouseId, Point2D startCanvasPos, Point2D curCanvasPos, Set<IElement> elementsToDrag) {
886         return new TranslateMode(startCanvasPos, curCanvasPos, mouseId, elementsToDrag);
887     }
888
889     protected ICanvasParticipant createBoxSelectTool(int mouseId, Point2D startCanvasPos, Point2D curCanvasPos, int button, PickPolicy boxSelectMode) {
890         return new BoxSelectionMode(startCanvasPos, curCanvasPos, mouseId, button, boxSelectMode);
891     }
892
893     /**
894      * A context listener for resetting tool mode back to pointer mode after the
895      * tracked participant has been removed.
896      */
897     protected class ToolModeResetter implements IContextListener<ICanvasParticipant> {
898         private ICanvasParticipant tracked;
899         public ToolModeResetter(ICanvasParticipant trackedParticipant) {
900             this.tracked = trackedParticipant;
901         }
902         @Override
903         public void itemAdded(IContext<ICanvasParticipant> sender, ICanvasParticipant item) {
904         }
905         @Override
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);
912                 }
913             }
914         }
915     }
916
917 }