Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.fmap.control / src / main / java / org / gvsig / fmap / mapcontrol / MapControl.java @ 44499

History | View | Annotate | Download (89.3 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.fmap.mapcontrol;
25

    
26
import java.awt.Color;
27
import java.awt.Cursor;
28
import java.awt.Dimension;
29
import java.awt.Graphics;
30
import java.awt.Graphics2D;
31
import java.awt.Image;
32
import java.awt.Point;
33
import java.awt.Toolkit;
34
import java.awt.event.ActionEvent;
35
import java.awt.event.ActionListener;
36
import java.awt.event.ComponentEvent;
37
import java.awt.event.ComponentListener;
38
import java.awt.event.MouseEvent;
39
import java.awt.event.MouseListener;
40
import java.awt.event.MouseMotionListener;
41
import java.awt.event.MouseWheelEvent;
42
import java.awt.event.MouseWheelListener;
43
import java.awt.geom.Point2D;
44
import java.awt.image.BufferedImage;
45
import java.awt.image.MemoryImageSource;
46
import java.util.Comparator;
47
import java.util.HashMap;
48
import java.util.List;
49
import java.util.Map;
50
import java.util.Set;
51
import java.util.TreeMap;
52
import java.util.prefs.Preferences;
53

    
54
import javax.swing.JComponent;
55
import javax.swing.SwingUtilities;
56
import javax.swing.Timer;
57
import javax.swing.event.ChangeEvent;
58
import javax.swing.event.ChangeListener;
59

    
60
import org.cresques.cts.IProjection;
61
import org.gvsig.fmap.dal.DataStoreNotification;
62
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
63
import org.gvsig.fmap.geom.Geometry;
64
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
65
import org.gvsig.fmap.geom.GeometryLocator;
66
import org.gvsig.fmap.geom.GeometryManager;
67
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
68
import org.gvsig.fmap.geom.primitive.Envelope;
69
import org.gvsig.fmap.mapcontext.MapContext;
70
import org.gvsig.fmap.mapcontext.MapContextLocator;
71
import org.gvsig.fmap.mapcontext.ViewPort;
72
import org.gvsig.fmap.mapcontext.events.AtomicEvent;
73
import org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener;
74
import org.gvsig.fmap.mapcontext.layers.FLayer;
75
import org.gvsig.fmap.mapcontext.layers.FLayers;
76
import org.gvsig.fmap.mapcontext.layers.LayerCollectionEvent;
77
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
78
import org.gvsig.fmap.mapcontext.layers.SpatialCache;
79
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
80
import org.gvsig.fmap.mapcontext.layers.vectorial.GraphicLayer;
81
import org.gvsig.fmap.mapcontrol.tools.BehaviorException;
82
import org.gvsig.fmap.mapcontrol.tools.CompoundBehavior;
83
import org.gvsig.fmap.mapcontrol.tools.Behavior.Behavior;
84
import org.gvsig.fmap.mapcontrol.tools.Listeners.ToolListener;
85
import org.gvsig.fmap.mapcontrol.tools.grid.Grid;
86
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapper;
87
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapperGeometriesVectorial;
88
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapperRaster;
89
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapperVectorial;
90
import org.gvsig.tools.ToolsLocator;
91
import org.gvsig.tools.dispose.Disposable;
92
import org.gvsig.tools.observer.Observable;
93
import org.gvsig.tools.observer.Observer;
94
import org.gvsig.tools.swing.api.ActionListenerSupport;
95
import org.gvsig.tools.swing.api.ChangeListenerHelper;
96
import org.gvsig.tools.swing.api.ToolsSwingLocator;
97
import org.gvsig.tools.task.Cancellable;
98
import org.gvsig.utils.exceptionHandling.ExceptionHandlingSupport;
99
import org.gvsig.utils.exceptionHandling.ExceptionListener;
100
import org.slf4j.Logger;
101
import org.slf4j.LoggerFactory;
102

    
103
/**
104
 * <p>
105
 * A component that includes a {@link MapContext MapContext} with support for
106
 * use it as a particular {@link Behavior Behavior}.
107
 * </p>
108
 *
109
 * <p>
110
 * A developer can register a set of <code>Behavior</code>, but only one (that
111
 * can be a composition of several) of them can be active. The active one
112
 * defines the way to work and access with its <code>MapContext</code>'s layers.
113
 * The active behavior, in combination with the appropriate {@link ToolListener
114
 * ToolListener} will allow user work with a particular <i>tool</i>.
115
 * </p>
116
 *
117
 * <p>
118
 * All mouse events produced on this component will be delegated to the current
119
 * active behavior, the <i>currentMapTool</i>.
120
 * </p>
121
 *
122
 * <p>
123
 * <b>Drawing process:</b>
124
 * </p>
125
 *
126
 * <p>
127
 * Uses a double buffer for the drawing process of <code>MapContext</code>'s
128
 * information.
129
 * </p>
130
 *
131
 * <p>
132
 * If the double buffer wasn't created, creates a new one.
133
 * </p>
134
 *
135
 * <p>
136
 * Paints the component according the following algorithm: <br>
137
 * &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
138
 * &nbsp &nbsp If there is a <i>double buffer</i>:<br>
139
 * &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the
140
 * <code>MapControl</code> instance, delegates the drawing process to that
141
 * behavior, calling: <code><i>behavior_instance</i>.paintComponent(g)</code>.<br>
142
 * &nbsp &nbsp &nbsp Else, repaints the current graphical information quickly
143
 * calling: <code>g.drawImage(image,0,0,null)</code>.<br>
144
 * &nbsp Else, (<i>status</i> is <i>OUTDATED</i>, or <i>ONLY_GRAPHICS</i>):
145
 * executes a quickly repaint of the previous information calling
146
 * <code>g.drawImage(image,0,0,null)</code>, and creates a <i>painting
147
 * request</i> to delegate the heavy drawing process to the {@link Drawer2
148
 * Drawer2}'s worker thread, according the <i>SingleWorketThread</i> pattern,
149
 * starting a timer to update (invoking <code>repaint()</code>) the view every
150
 * delay of <code>1000 / drawFrameRate</code> ms. during that heavy drawing
151
 * process, and if its enabled <code>drawAnimationEnabled</code>. The
152
 * <i>painting request</i> once is being attended, invokes
153
 * <code>MapContext</code> to draw the layers:
154
 * <code>mapContext.draw(image, g, cancel,mapContext.getScaleView());</code>
155
 * <br>
156
 * <p>
157
 * Some notes:
158
 * <ul>
159
 * <li>The painting process can be cancelled calling {@link #cancelDrawing()
160
 * #cancelDrawing()}.</li>
161
 * <li>At last resort, the particular implementation of each layer in a
162
 * <code>MapControl</code>'s <code>MapContrext</code> will be that one which
163
 * will draw the graphical information, and, if supports, which could cancel its
164
 * drawing subprocess.</li>
165
 * <li>It's possible to force repaint all layers, calling
166
 * {@link #drawMap(boolean doClear) #drawMap(boolean)}.</li>
167
 * <li>It's possible repaint only the dirty layers, calling
168
 * {@link #rePaintDirtyLayers() #rePaintDirtyLayers()}.</li>
169
 * <li>It's possible repaint only the {@link GraphicLayer GraphicLayer}, calling
170
 * {@link #drawGraphics() #drawGraphics()}.</li>
171
 * </ul>
172
 * </p>
173
 *
174
 * <p>
175
 * <b>Tools:</b>
176
 * </p>
177
 *
178
 * <p>
179
 * A developer can:
180
 * <ul>
181
 * <li>Register each tool as:
182
 * <ul>
183
 * <li>A single behavior: {@link #addBehavior(String, Behavior)
184
 * #addMapTool(String, Behavior)}.</li>
185
 * <li>Or, a compound behavior: {@link #addBehavior(String, Behavior)
186
 * #addMapTool(String, Behavior)}.</li>
187
 * </ul>
188
 * </li>
189
 * <li>Get the current active tool: {@link #getCurrentMapTool()
190
 * #getCurrentMapTool()}.</li>
191
 * <li>Get the current active tool name: {@link #getCurrentTool()
192
 * #getCurrentTool()}.</li>
193
 * <li>Get a registered tool: {@link #getMapTool(String) #getMapTool(String)}.</li>
194
 * <li>Get the name of all tools registered: {@link #getMapToolsKeySet()
195
 * #getMapToolsKeySet()}.</li>
196
 * <li>Get all tools registered, including the name they were registered:
197
 * {@link #getNamesMapTools() #getNamesMapTools()}.</li>
198
 * <li>Determine if has a tool registered: {@link #hasTool(String)
199
 * #hasTool(String)}.</li>
200
 * <li>Set as an active tool, one of the registered: {@link #setTool(String)
201
 * #setTool(String)}.</li>
202
 * <li>Set as active tool, the previous used: {@link #setPrevTool()
203
 * #setPrevTool()}.</li>
204
 * <li>Set the current tool: {@link #setCurrentMapTool(Behavior)
205
 * #setCurrentMapTool(Behavior)}.</li>
206
 * <li>Change the draw frame rate: {@link #setDrawFrameRate(int)
207
 * #setDrawFrameRate(int)} and {@link #applyFrameRate() #applyFrameRate()}.</li>
208
 * <li>Get the draw frame rate: {@link #getDrawFrameRate() #getDrawFrameRate()}.
209
 * </li>
210
 * <li>Determine if will repaint this component each time timer finishes:
211
 * {@link #isDrawAnimationEnabled() #isDrawAnimationEnabled()}.</li>
212
 * <li>Change if will repaint this component each time timer finishes:
213
 * {@link #setDrawAnimationEnabled(boolean) #setDrawAnimationEnabled(boolean)}.</li>
214
 * <li>Get the shared object that determines if a drawing process must be
215
 * cancelled or can continue: {@link #getCanceldraw() #getCanceldraw()}.</li>
216
 * <li>Get the combined tool: {@link #getCombinedTool() #getCombinedTool()}.</li>
217
 * <li>Set a combined tool: {@link #setCombinedTool(Behavior)
218
 * #setCombinedTool(Behavior)}.</li>
219
 * <li>Remove the combined tool: {@link #removeCombinedTool()
220
 * #removeCombinedTool()}.</li>
221
 * </ul>
222
 * </p>
223
 *
224
 * <p>
225
 * <b>Exception listener:</b>
226
 * </p>
227
 *
228
 * <p>
229
 * Adding an <code>ExceptionListener</code>, can get notification about any
230
 * exception produced:
231
 * <ul>
232
 * <li>Attending a <i>painting request</i>.</li>
233
 * <li>Working with the active tool.</li>
234
 * <li>Applying a <i>zoom in</i> or <i>zoom out</i> operation.</li>
235
 * </ul>
236
 * </p>
237
 *
238
 * <p>
239
 * <b>Other:</b>
240
 * </p>
241
 *
242
 * <p>
243
 * Other useful capabilities of <code>MapControl</code>:
244
 * <ul>
245
 * <li>Cancel the current drawing process (notifying it also to the inner
246
 * <code>MapContext</code> instance and its layers): {@link #cancelDrawing()
247
 * #cancelDrawing()}.</li>
248
 * <li>Applying a <i>zoom in</i> operation centered at mouse position (without a
249
 * <code>ToolListener</code>): {@link #zoomIn() #zoomIn()}.</li>
250
 * <li>Applying a <i>zoom out</i> operation centered at mouse position (without
251
 * a <code>ToolListener</code>): {@link #zoomOut() #zoomOut()}.</li>
252
 * </ul>
253
 * </p>
254
 *
255
 * @see CancelDraw
256
 * @see Drawer
257
 * @see MapContextListener
258
 * @see MapToolListener
259
 *
260
 * @author Fernando Gonz�lez Cort�s
261
 * @author Pablo Piqueras Bartolom� (pablo.piqueras@iver.es)
262
 */
263
public class MapControl extends JComponent implements ComponentListener,
264
    Observer, Disposable {
265

    
266
    public class AddLayerEvent extends ActionEvent {
267

    
268
        private static final long serialVersionUID = -1857839388303164091L;
269

    
270
        private FLayer layer;
271
        
272
        public AddLayerEvent(FLayer layer, Object source, int id, String command) {
273
            super(source, id, command);
274
            this.layer = layer;
275
        }
276
        
277
        public FLayer getLayer() {
278
            return this.layer;
279
        }
280
        
281
        public void setLayer(FLayer layer) {
282
            this.layer = layer;
283
        }
284
    }
285
    
286
    protected static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
287
    private static final Logger LOG = LoggerFactory.getLogger(GeometryManager.class);
288

    
289
    /**
290
     * <p>
291
     * One of the possible status of <code>MapControl</code>. Determines that
292
     * all visible information has been drawn and its updated.
293
     * </p>
294
     */
295
    public static final int ACTUALIZADO = 0;
296

    
297
    /**
298
     * <p>
299
     * One of the possible status of <code>MapControl</code>. Determines that
300
     * not all visible information has been drawn or isn't updated.
301
     * </p>
302
     */
303
    public static final int DESACTUALIZADO = 1;
304

    
305
    /**
306
     * <p>
307
     * Determines if the drawer can update this <code>MapControl</code> instance
308
     * when the timer launches an event.
309
     * </p>
310
     */
311
    private static boolean drawAnimationEnabled = true;
312

    
313
    public static final int PAINT_PARTIAL_DRAWING_LAYERS = 0;
314
    public static final int PAINT_WHEN_DRAW_LAYERS_IS_COMPLETED = 1;
315

    
316
    private int paintMode = PAINT_PARTIAL_DRAWING_LAYERS;
317
    
318
    /**
319
     * <p>
320
     * Inner model with the layers, event support for drawing them, and the
321
     * <code>ViewPort</code> with information to adapt to the bounds available
322
     * in <i>image coordinates</i>.
323
     * </p>
324
     *
325
     * @see #getMapContext()
326
     * @see #setMapContext(MapContext)
327
     */
328
    private MapContext mapContext = null;
329

    
330
    /**
331
     * <p>
332
     * All registered <code>Behavior</code> that can define a way to work with
333
     * this <code>MapControl</code>.
334
     * </p>
335
     *
336
     * <p>
337
     * Only one of them can be active at a given moment.
338
     * </p>
339
     *
340
     * @see #addBehavior(String, Behavior)
341
     * @see #addBehavior(String, Behavior[])
342
     * @see #getMapTool(String)
343
     * @see #getMapToolsKeySet()
344
     * @see #getNamesMapTools()
345
     */
346
    protected Map<String,Behavior> namesMapTools = new HashMap<String,Behavior>();
347

    
348
    /**
349
     * <p>
350
     * Active {@link Behavior Behavior} that will generate events according a
351
     * criterion, and then, with a {@link ToolListener ToolListener} associated,
352
     * will simulate to user that works with this component as a particular
353
     * tool.
354
     * </p>
355
     *
356
     * @see #getCurrentMapTool()
357
     * @see #getCurrentTool()
358
     * @see #setTool(String)
359
     */
360
    protected Behavior currentMapTool = null;
361

    
362
    /**
363
     * <p>
364
     * Determines which's the current drawn status of this component:
365
     * <ul>
366
     * <li><b>OUTDATED</b>: all visible information has been drawn or isn't
367
     * updated.</li>
368
     * <li><b>UTDATED</b>: all visible information has been drawn and its
369
     * updated.</li>
370
     * <li><b>ONLY_GRAPHICS</b>: only the graphical layer must be drawn /
371
     * updated.</li>
372
     * </ul>
373
     * </p>
374
     *
375
     * <p>
376
     * The <code>MapControl</code> drawing process will consider the value of
377
     * this parameter to decide which elements will be updated or drawn.
378
     * </p>
379
     */
380
    private int status = DESACTUALIZADO;
381

    
382
    /**
383
     * <p>
384
     * Image with a buffer to accelerate the draw the changes of the graphical
385
     * items in this component.
386
     * </p>
387
     *
388
     * <p>
389
     * Firstly, information will be drawn in the buffer, and, when is outright
390
     * drawn, that information will be displayed. Meanwhile, the previous image
391
     * can be kept showed.
392
     * </p>
393
     *
394
     * @see BufferedImage
395
     *
396
     * @see #getImage()
397
     */
398
    private BufferedImage image = null;
399

    
400
    /**
401
     * <p>
402
     * Name of the tool used currently to interact with this component.
403
     * </p>
404
     *
405
     * @see #getCurrentTool()
406
     * @see #setTool(String)
407
     */
408
    protected String currentTool;
409

    
410
    /**
411
     * <p>
412
     * Object to store the flag that notifies a drawing thread task and
413
     * <code>MapContext</code>'s layers, that must be canceled or can continue
414
     * with the process.
415
     * </p>
416
     *
417
     * @see #cancelDrawing()
418
     */
419
    private CancelDraw canceldraw;
420

    
421
    // private boolean isCancelled = true;
422

    
423
    /**
424
     * <p>
425
     * Fires an action events after a specified delay.
426
     * </p>
427
     *
428
     * <p>
429
     * <code>MapControl</code> will use the timer to update its visible
430
     * graphical information during a drawing process, or allowing to cancel
431
     * that process.
432
     * </p>
433
     *
434
     * <p>
435
     * This is very useful to pretend faster interactivity to user when
436
     * <code>MapControl</code> has lots of layers, and / or layers with heavy
437
     * graphical elements, that need a long time to finish drawing all its data.
438
     * </p>
439
     */
440
    private Timer timer;
441

    
442
    /**
443
     * <p>
444
     * Reference to the {@link ViewPort ViewPort} of the {@link MapContext
445
     * MapContext} of this component.
446
     * </p>
447
     *
448
     * <p>
449
     * After, the view port will change adapting itself according the current
450
     * projection and the extent.
451
     * </p>
452
     *
453
     * @see #getViewPort()
454
     *
455
     * @see ViewPort
456
     */
457
    protected ViewPort vp;
458

    
459
    /**
460
     * <p>
461
     * Manager of all <code>MapControl</code> painting requests.
462
     * </p>
463
     */
464
    private Drawer drawer;
465

    
466
    /**
467
     * <p>
468
     * Listener of all kind of mouse events produced in this component.
469
     * </p>
470
     *
471
     * <p>
472
     * Delegates each mouse event to the current map tool.
473
     * </p>
474
     *
475
     * @see #addBehavior(String, Behavior)
476
     * @see #addBehavior(String, Behavior[])
477
     * @see #getMapTool(String)
478
     * @see #getMapToolsKeySet()
479
     * @see #getNamesMapTools()
480
     * @see #setTool(String)
481
     */
482
    protected MapToolListener mapToolListener = new MapToolListener();
483

    
484
    /**
485
     * <p>
486
     * Listener of all events produced in a this component's
487
     * <code>MapContext</code> object during an atomic period of time.
488
     * </p>
489
     */
490
    private MapContextListener mapContextListener = new MapContextListener();
491

    
492
    /**
493
     * <p>
494
     * Group of <code>ExceptionListener</code> that, in whatever moment could be
495
     * notified a Throwable Java error or exception.
496
     * </p>
497
     *
498
     * @see #addExceptionListener(ExceptionListener)
499
     * @see #removeExceptionListener(ExceptionListener)
500
     */
501
    private ExceptionHandlingSupport exceptionHandlingSupport =
502
        new ExceptionHandlingSupport();
503

    
504
    /**
505
     * <p>
506
     * Name of the previous tool used.
507
     * </p>
508
     */
509
    protected String prevTool;
510

    
511
    /**
512
     * <p>
513
     * Tool that will be used combined with the current tool of this
514
     * <code>MapControl</code>.
515
     * </p>
516
     */
517
    private Behavior combinedTool = null;
518

    
519
    /**
520
     * Optional grid that could be applied on the <code>MapControl</code>'s view
521
     * port.
522
     *
523
     * @see #getGrid()
524
     * @see #setAdjustGrid(boolean)
525
     */
526
    private Grid cadgrid = new Grid();
527
    /**
528
     * Represents the cursor's point selected in <i>screen coordinates</i>.
529
     *
530
     * @see ViewPort#fromMapPoint(Point2D)
531
     */
532
    protected Point2D adjustedPoint;
533
    /**
534
     * <p>
535
     * Determines if the position of the snap of the mouse's cursor on the
536
     * <code>MapControl</code> is within the area around a control point of a
537
     * geometry.
538
     * </p>
539
     *
540
     * <p>
541
     * The area is calculated as a circle centered at the control point and with
542
     * radius the pixels tolerance defined in the preferences.
543
     * </p>
544
     */
545
    private boolean bForceCoord = false;
546

    
547
    /**
548
     * Kind of geometry drawn to identify the kind of control point selected by
549
     * the cursor's mouse.
550
     */
551
    private ISnapper usedSnap = null;
552

    
553
    /**
554
     * Determines if the snap tools are enabled or disabled.
555
     *
556
     * @see #isRefentEnabled()
557
     * @see #setRefentEnabled(boolean)
558
     */
559
    private boolean bRefent = true;
560

    
561
    /**
562
     * Stores the 2D map coordinates of the last point added.
563
     */
564
    private double[] previousPoint = null;
565

    
566
    private boolean defaultMouseWheelEnabled = true;
567
    
568
    protected static MapControlManager mapControlManager =
569
        MapControlLocator.getMapControlManager();
570

    
571
    private static TreeMap selected = new TreeMap(new Comparator() {
572

    
573
        public int compare(Object o1, Object o2) {
574
            if (o1.getClass().equals(o2.getClass()))
575
                return 0;
576
            if (((ISnapper) o1).getPriority() > ((ISnapper) o2).getPriority())
577
                return 1;
578
            else
579
                return -1;
580
        }
581

    
582
    });
583

    
584
    /**
585
     * Represents the cursor's point selected in <i>map coordinates</i>.
586
     *
587
     * @see MapControl#toMapPoint
588
     */
589
    protected Point2D mapAdjustedPoint;
590

    
591
    /**
592
     * Renderer used to draw the layers.
593
     */
594
    private MapControlDrawer mapControlDrawer = null;
595
        private Cursor transparentCursor;
596

    
597
        private boolean disposed = false;
598

    
599
    private ActionListenerSupport addLayerHelper;
600
    
601
    /**
602
     * <p>
603
     * Creates a new <code>MapControl</code> instance with the following
604
     * characteristics:
605
     * <ul>
606
     * <li><i>Name</i>: MapControl .</li>
607
     * <li>Disables the double buffer of <code>JComponent</code> .</li>
608
     * <li>Sets opaque <i>(see {@link JComponent#setOpaque(boolean)} )</i>.</li>
609
     * <li>Sets its status to <code>OUTDATED</code> .</li>
610
     * <li>Creates a new {@link CancelDraw CancelDraw} object to notify
611
     * <code>MapContext</code>'s layers if can continue processing the drawn or
612
     * must cancel it.</li>
613
     * <li>Creates a new {@link MapContext MapContext} with a new
614
     * {@link ViewPort ViewPort} in the default projection.</li>
615
     * <li>Creates a new {@link CommandListener CommandListener} for edition
616
     * operations.</li>
617
     * <li>Creates a new {@link MapToolListener MapToolListener}, and associates
618
     * it as a listener of whatever kind of mouse events produced in this
619
     * component.</li>
620
     * <li>Creates a new {@link Drawer2 Drawer2} for managing the painting
621
     * requests.</li>
622
     * <li>Creates a new timer that will invoke refresh this component
623
     * <code>drawFrameRate</code> per second, when is running a drawing process,
624
     * and its enabled <code>drawAnimationEnabled</code>.</li>
625
     * </ul>
626
     * </p>
627
     */
628
    public MapControl() {
629
        this(null);
630
    }
631

    
632
    public MapControl(MapContext theMapContext) {
633
        this.changeToolListenerHelper = ToolsSwingLocator.getToolsSwingManager().createChangeListenerHelper();
634
        if( theMapContext == null ) {
635
            theMapContext = new MapContext(new ViewPort(MapContextLocator.getMapContextManager().getDefaultCRS()));
636
        }
637
        this.setName("MapControl");
638
        this.addLayerHelper = ToolsSwingLocator.getToolsSwingManager().createActionListenerSupport();
639
        Toolkit toolkit = Toolkit.getDefaultToolkit();
640
        Image imageTransparentCursor = toolkit.createImage(new MemoryImageSource(16, 16, new int[16 * 16], 0,16));
641
        transparentCursor =
642
            toolkit.createCustomCursor(imageTransparentCursor, new Point(0, 0), "invisiblecursor");
643

    
644
        setDoubleBuffered(false);
645
        setOpaque(true);
646
        status = DESACTUALIZADO;
647

    
648
        // Clase usada para cancelar el dibujado
649
        canceldraw = new CancelDraw();
650

    
651
        vp = theMapContext.getViewPort();
652

    
653
        setMapContext(theMapContext);
654

    
655
        // eventos
656
        this.addComponentListener(this);
657
        this.addMouseListener(mapToolListener);
658
        this.addMouseMotionListener(mapToolListener);
659
        this.addMouseWheelListener(mapToolListener);
660

    
661
        this.drawer = new Drawer();
662
        // Timer para mostrar el redibujado mientras se dibuja
663
        timer = new Timer(1000 / MapContext.getDrawFrameRate(),
664
                new ActionListener() {
665
                    @Override
666
                    public void actionPerformed(ActionEvent e) {
667
                        if ( paintMode!=PAINT_WHEN_DRAW_LAYERS_IS_COMPLETED && drawAnimationEnabled) {
668
                            MapControl.this.repaint();
669
                        }
670
                    }
671
                }
672
        );
673
        initializeGrid();
674

    
675
        if(ToolsLocator.getDisposableManager() != null) {
676
                        ToolsLocator.getDisposableManager().bind(this);
677
                } else {
678
                        LOG.warn("Can't retrieve the disposable manager,");
679
                }
680
    }
681
    
682
    public void addLayer(FLayer layer) {
683
        AddLayerEvent event = new AddLayerEvent(layer, this, 1, "addLayer");
684
        this.addLayerHelper.fireActionEvent(event);
685
        this.mapContext.getLayers().add(event.getLayer());
686
    }
687
    
688
    public void addLayerListener(ActionListener al) {
689
        this.addLayerHelper.addActionListener(al);
690
    }
691
    
692
    public void setPaintMode(int paintMode) {
693
        this.paintMode = paintMode;
694
    }
695
    
696
    public int getPaintMode() {
697
        return this.paintMode;
698
    }
699
    
700
    /**
701
     * <p>
702
     * Sets a <code>MapContext</code> to this component.
703
     * </p>
704
     *
705
     * <p>
706
     * The <code>MapContext</code> has the <i>model</i>, and most of the
707
     * <i>view</i>, and <i>control</i> logic of the layers of this component,
708
     * including a {@link ViewPort ViewPort} to adapt the information to the
709
     * projection, and to display it in the available area.
710
     * </p>
711
     *
712
     * <p>
713
     * If <code>model</code> hadn't a <code>ViewPort</code>, assigns the current
714
     * one to it, otherwise, use its <code>ViewPort</code>.
715
     * </p>
716
     *
717
     * <p>
718
     * After assigning the <code>MapContext</code> and <code>ViewPort</code>,
719
     * sets the same {@link MapContextListener MapContextListener} that was
720
     * using, and changes the <i>status</i> to <code>OUTDATED</code>.
721
     * </p>
722
     *
723
     * @param model
724
     *            this component's <code>MapContext</code>, that includes the
725
     *            <code>ViewPort</code>.
726
     *
727
     * @see MapContext
728
     *
729
     * @see #getMapContext()
730
     */
731
    public void setMapContext(MapContext model) {
732
        if (mapContext != null) {
733
            mapContext.removeAtomicEventListener(mapContextListener);
734
            mapContext.dispose();
735
        }
736

    
737
        mapContext = model;
738

    
739
        if (mapContext.getViewPort() == null) {
740
            mapContext.setViewPort(vp);
741
        } else {
742
            vp = mapContext.getViewPort();
743
            cadgrid.setViewPort(vp);
744
        }
745

    
746
        mapContext.addAtomicEventListener(mapContextListener);
747

    
748
        status = DESACTUALIZADO;
749
    }
750

    
751
    /**
752
     * @return the mapControlDrawer
753
     */
754
    public MapControlDrawer getMapControlDrawer() {
755
        return mapControlDrawer;
756
    }
757

    
758
    /**
759
     * @param mapControlDrawer
760
     *            the mapControlDrawer to set
761
     */
762
    public void setMapControlDrawer(MapControlDrawer mapControlDrawer) {
763
        this.mapControlDrawer = mapControlDrawer;
764
        this.mapControlDrawer.setViewPort(vp);
765
    }
766

    
767
    /**
768
     * <p>
769
     * Gets this component's {@link MapContext MapContext} projection.
770
     * </p>
771
     *
772
     * @return this component's {@link MapContext MapContext} projection
773
     *
774
     * @see MapContext#getProjection()
775
     * @see MapControl#setProjection(IProjection)
776
     */
777
    public IProjection getProjection() {
778
        return getMapContext().getProjection();
779
    }
780

    
781
    /**
782
     * <p>
783
     * Sets the projection to this component's {@link MapContext MapContext}.
784
     * </p>
785
     *
786
     * @param proj
787
     *            the kind of projection to this component's {@link MapContext
788
     *            MapContext}
789
     *
790
     * @see MapContext#setProjection(IProjection)
791
     * @see MapControl#getProjection()
792
     */
793
    public void setProjection(IProjection proj) {
794
        getMapContext().setProjection(proj);
795
    }
796

    
797
    /**
798
     * <p>
799
     * Gets this component's <code>MapContext</code>, with the <i>model</i>, and
800
     * most of the <i>view</i>, and <i>control</i> logic of the layers of this
801
     * component, including a {@link ViewPort ViewPort} to adapt the information
802
     * to the projection, and display it in the available area.
803
     * </p>
804
     *
805
     * @return this component's <code>MapContext</code>, that includes the
806
     *         <code>ViewPort</code> used to project the
807
     *         graphical information, and display it in the available area
808
     *
809
     * @see MapContext
810
     *
811
     * @see MapControl#setMapContext(MapContext)
812
     */
813
    public MapContext getMapContext() {
814
        return mapContext;
815
    }
816

    
817
    /**
818
     * <p>
819
     * Registers a new behavior to this component.
820
     * </p>
821
     *
822
     * <p>
823
     * According the nature of the {@link Behavior Behavior}, different events
824
     * will be generated. Those events can be caught by a particular
825
     * {@link ToolListener ToolListener}, allowing user to interact with this
826
     * <code>MapControl</code> object as a <i>tool</i>.
827
     * </p>
828
     *
829
     * @param name
830
     *            name to identify the behavior to add
831
     * @param tool
832
     *            the behavior to add
833
     *
834
     * @see #addBehavior(String, Behavior[])
835
     * @see #getNamesMapTools()
836
     * @see #getMapToolsKeySet()
837
     * @see #hasTool(String)
838
     */
839
    public void addBehavior(String name, Behavior tool) {
840
        namesMapTools.put(name, tool);
841
        tool.setMapControl(this);
842
    }
843

    
844
    /**
845
     * <p>
846
     * Registers a new behavior to this component as a {@link CompoundBehavior
847
     * CompoundBehavior} made up of <code>tools</code>.
848
     * </p>
849
     *
850
     * <p>
851
     * According the nature of the behaviors registered, different events will
852
     * be generated. Those events can be caught by a particular
853
     * {@link ToolListener ToolListener}, allowing user to interact with this
854
     * <code>MapControl</code> object as a <i>tool</i>.
855
     * </p>
856
     *
857
     * @param name
858
     *            name to identify the compound behavior to add
859
     * @param tools
860
     *            the compound behavior to add
861
     *
862
     * @see #addBehavior(String, Behavior)
863
     * @see #getNamesMapTools()
864
     * @see #getMapToolsKeySet()
865
     * @see #hasTool(String)
866
     */
867
    public void addBehavior(String name, Behavior[] tools) {
868
        CompoundBehavior tool = new CompoundBehavior(tools);
869
        tool.setMapControl(this);
870
        addBehavior(name, tool);
871
    }
872

    
873
    /**
874
     * <p>
875
     * Gets the <code>Behavior</code> registered in this component, identified
876
     * by <code>name</code>.
877
     * </p>
878
     *
879
     * @param name
880
     *            name of a registered behavior
881
     *
882
     * @return tool the registered behavior in this component as
883
     *         <code>name</code>, or <code>null</code> if
884
     *         no one has that identifier
885
     *
886
     * @see #addBehavior(String, Behavior)
887
     * @see #addBehavior(String, Behavior[])
888
     * @see #hasTool(String)
889
     */
890
    public Behavior getMapTool(String name) {
891
        return (Behavior) namesMapTools.get(name);
892
    }
893

    
894
    /**
895
     * <p>
896
     * Returns a set view of the keys that identified the tools registered.
897
     * </p>
898
     *
899
     * @return a set view of the keys that identified the tools registered
900
     *
901
     * @see HashMap#keySet()
902
     *
903
     * @see #getNamesMapTools()
904
     * @see #addBehavior(String, Behavior)
905
     * @see #addBehavior(String, Behavior[])
906
     */
907
    public Set getMapToolsKeySet() {
908
        return namesMapTools.keySet();
909
    }
910

    
911
    /**
912
     * <p>
913
     * Returns <code>true</code> if this component contains a tool identified by
914
     * <code>toolName</code>.
915
     * </p>
916
     *
917
     * @param toolName
918
     *            identifier of the tool
919
     *
920
     * @return <code>true</code> if this component contains a tool identified by
921
     *         <code>toolName</code>; otherwise <code>false</code>
922
     *
923
     * @see #addBehavior(String, Behavior)
924
     * @see #addBehavior(String, Behavior[])
925
     */
926
    public boolean hasTool(String toolName) {
927
        return namesMapTools.containsKey(toolName);
928
    }
929

    
930
    /**
931
     * <p>
932
     * Sets as current active <code>Behavior</code> associated to this
933
     * component, that one which is registered and identified by
934
     * <code>toolName</code>.
935
     * </p>
936
     *
937
     * <p>
938
     * Changing the current active behavior for this <code>MapControl</code>,
939
     * implies also updating the previous <i>behavior</i> tool, and the current
940
     * cursor.
941
     * </p>
942
     *
943
     * @param toolName
944
     *            name of a registered behavior
945
     *
946
     * @see #getCurrentMapTool()
947
     * @see #getCurrentTool()
948
     */
949
    public void setTool(String toolName) {
950
        prevTool = getCurrentTool();
951
        Behavior mapTool = (Behavior) namesMapTools.get(toolName);
952
        currentMapTool = mapTool;
953
        currentTool = toolName;
954

    
955
        if (combinedTool != null) {
956
            if (mapTool instanceof CompoundBehavior) {
957
                ((CompoundBehavior) mapTool).addMapBehavior(combinedTool, true);
958
            } else {
959
                currentMapTool =
960
                    new CompoundBehavior(new Behavior[] { currentMapTool });
961
                ((CompoundBehavior) currentMapTool).addMapBehavior(
962
                    combinedTool, true);
963
                currentMapTool.setMapControl(this);
964
            }
965
        }
966
        this.changeToolListenerHelper.fireEvent(new ChangeEvent(this));
967
        // this.setCursor(mapTool.getCursor());
968
    }
969

    
970
    /**
971
     * <p>
972
     * Gets as current active <code>Behavior</code> associated to this
973
     * component, that one which is registered and identified by
974
     * <code>toolName</code>.
975
     * </p>
976
     *
977
     * <p>
978
     * Changing the current active behavior for this <code>MapControl</code>,
979
     * implies also updating the previous <i>behavior</i> tool, and the current
980
     * cursor.
981
     * </p>
982
     *
983
     * @param toolName
984
     *            name of a registered behavior
985
     *
986
     * @see #getCurrentTool()
987
     * @see #setTool(String)
988
     */
989
    public Behavior getCurrentMapTool() {
990
        return currentMapTool;
991
    }
992

    
993
    /**
994
     * <p>
995
     * Returns the name of the current selected tool on this MapControl
996
     * </p>
997
     *
998
     * @return the name of the current's behavior tool associated to this
999
     *         component
1000
     *
1001
     * @see #getCurrentMapTool()
1002
     * @see #setTool(String)
1003
     */
1004
    public String getCurrentTool() {
1005
        return currentTool;
1006
    }
1007

    
1008
    /**
1009
     * <p>
1010
     * Determines that current drawing process of <code>MapControl</code>'s
1011
     * <code>MapContext</code>'s data must be canceled.
1012
     * </p>
1013
     *
1014
     * <p>
1015
     * It has no effects if now isn't drawing that graphical information.
1016
     * </p>
1017
     *
1018
     * <p>
1019
     * At last resort, the particular implementation of each layer in this
1020
     * <code>MapControl</code>'s <code>MapContrext</code> will be that one which
1021
     * will draw the graphical information, and, if supports, which could cancel
1022
     * its drawing subprocess.
1023
     * </p>
1024
     */
1025
    public void cancelDrawing() {
1026
        /*
1027
         * if (drawer != null) {
1028
         * if (!drawer.isAlive()) {
1029
         * return;
1030
         * }
1031
         * }
1032
         */
1033
        canceldraw.setCanceled(true);
1034

    
1035
        /*
1036
         * while (!isCancelled) {
1037
         * if (!drawer.isAlive()) {
1038
         * // Si hemos llegado aqu� con un thread vivo, seguramente
1039
         * // no estamos actualizados.
1040
         *
1041
         * break;
1042
         * }
1043
         *
1044
         * }
1045
         * canceldraw.setCancel(false);
1046
         * isCancelled = false;
1047
         * drawerAlive = false;
1048
         */
1049
    }
1050

    
1051
    /**
1052
     * <p>
1053
     * Creates a {@link BufferedImage BufferedImage} image if there was no
1054
     * buffered image, or if its viewport's image height or width is different
1055
     * from this component's size. Once has created a double-buffer, fills it
1056
     * with the vieport's background color, or with <i>white</i> if it had no
1057
     * background color.
1058
     * </p>
1059
     *
1060
     * <p>
1061
     * If no double-buffered existed, creates a {@link BufferedImage
1062
     * BufferedImage} with the size of this component, and as an image with
1063
     * 8-bit RGBA color components packed into integer pixels. That image has a
1064
     * <code>DirectColorModel</code> with alpha. The color data in that image is
1065
     * considered not to be premultiplied with alpha.
1066
     * </p>
1067
     *
1068
     * <p>
1069
     * Once has created and filled the new inner <code>MapControl</code>'s
1070
     * double-buffer, changes the status to <code>OUTDATED</code>.
1071
     * </p>
1072
     *
1073
     * @return <code>true</code> if has created and filled a new double-buffer
1074
     *         for this <code>MapControl</code> instance; otherwise
1075
     *         <code>false</code>
1076
     */
1077
    private boolean adaptToImageSize() {
1078
        if ((image == null) || (vp.getImageWidth() != this.getWidth())
1079
            || (vp.getImageHeight() != this.getHeight())) {
1080
            image = new BufferedImage(this.getWidth(), this.getHeight(),
1081
                    BufferedImage.TYPE_INT_ARGB);
1082
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
1083
            getMapContext().getViewPort().refreshExtent();
1084
            clearImage(image);
1085
            status = DESACTUALIZADO;
1086
            return true;
1087
        }
1088
        return false;
1089
    }
1090

    
1091
    private void clearImage(BufferedImage image) {
1092
        if( image == null ) {
1093
            return;
1094
        }
1095
        Graphics gTemp = image.createGraphics();
1096
        Color theBackColor = vp.getBackColor();
1097
        if (theBackColor == null) {
1098
            gTemp.setColor(Color.WHITE);
1099
        } else {
1100
            gTemp.setColor(theBackColor);
1101
        }
1102
        gTemp.fillRect(0, 0, getWidth(), getHeight());
1103
        gTemp.dispose();
1104
    }
1105
    
1106
    /**
1107
     * <p>
1108
     * Paints the graphical information of this component using a double buffer.
1109
     * </p>
1110
     *
1111
     * <p>
1112
     * If the double buffer wasn't created, creates a new one.
1113
     * </p>
1114
     *
1115
     * <p>
1116
     * Paints the component according the following algorithm: <br>
1117
     * &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
1118
     * &nbsp &nbsp If there is no <i>double buffer</i>:<br>
1119
     * &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the
1120
     * <code>MapControl</code> instance, delegates the drawing process to that
1121
     * behavior, calling:
1122
     * <code><i>behavior_instance</i>.paintComponent(g)</code> &nbsp .<br>
1123
     * &nbsp &nbsp &nbsp Else, repaints the current graphical information
1124
     * quickly calling: <code>g.drawImage(image,0,0,null)</code> &nbsp .<br>
1125
     * &nbsp Else, (<i>status</i> is <i>OUTDATED</i>, or <i>ONLY_GRAPHICS</i>):
1126
     * executes a quickly repaint of the previous information calling
1127
     * <code>g.drawImage(image,0,0,null)</code>, and creates a <i>painting
1128
     * request</i> to delegate the heavy drawing process to the {@link Drawer2
1129
     * Drawer2}'s worker thread, according the <i>SingleWorketThread</i>
1130
     * pattern, starting a timer to update (invoking <code>repaint()</code> that
1131
     * comprises invoke this method) the view every delay of 360 ms. during the
1132
     * the process drawing.
1133
     * </p>
1134
     *
1135
     * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
1136
     * @see Drawer2
1137
     */
1138
    protected void paintComponent(Graphics g) {
1139
        adaptToImageSize();
1140

    
1141
        try {
1142
            mapControlDrawer.startDrawing(this);
1143
        } catch (InterruptedException e) {
1144
            LOG.info("Error locking the MapControlDrawer", e);
1145
        }
1146
        mapControlDrawer.setGraphics(g);
1147
        mapControlDrawer.stopDrawing(this);
1148
        mapControlDrawer.setViewPort(getMapContext().getViewPort());
1149

    
1150
        if (status == ACTUALIZADO) {
1151
            /*
1152
             * Si hay un behaviour y la imagen es distinta de null se delega el
1153
             * dibujado
1154
             * en dicho behaviour
1155
             */
1156
            if (image != null) {
1157
                if (currentMapTool != null) {
1158
                    currentMapTool.paintComponent(mapControlDrawer,true);
1159
                } else {
1160
                    mapControlDrawer.drawImage(image, 0, 0);
1161
                }
1162
            }
1163
                } else if ((status == DESACTUALIZADO)) {
1164
                        mapControlDrawer.drawImage(image, 0, 0);
1165
                        drawer.put(new PaintingRequest());
1166
                        timer.start();
1167
                }
1168
        cadgrid.drawGrid(mapControlDrawer);
1169
        drawCursor();
1170
    }
1171

    
1172
    private String getStatusLabel(int status ) {
1173
        switch(status) {
1174
            case ACTUALIZADO:
1175
                return "ACTUALIZADO";
1176
            case DESACTUALIZADO:
1177
                return "DESACTUALIZADO";
1178
            default:
1179
                return Integer.toString(status);
1180
        }
1181
    }
1182
    /**
1183
     * <p>
1184
     * Gets the {@link BufferedImage BufferedImage} used to accelerate the draw
1185
     * of new ''frames'' with changes, or new graphical items in this component.
1186
     * </p>
1187
     *
1188
     * @return double buffered image used by this component to accelerate the
1189
     *         draw of its graphical information, or <code>null</code> if isn't
1190
     *         already created
1191
     *
1192
     * @see BufferedImage
1193
     */
1194
    public BufferedImage getImage() {
1195
        return image;
1196
    }
1197

    
1198
    /**
1199
     * <p>
1200
     * Forces repaint all visible graphical information in this component.
1201
     * </p>
1202
     *
1203
     * <p>
1204
     * If <code>doClear == true</code>, before repainting, clears the background
1205
     * color, with the inner viewport's background color.
1206
     * </p>
1207
     *
1208
     * @param doClear
1209
     *            <code>true</code> if needs clearing the background color
1210
     *            before drawing the map
1211
     *
1212
     * @see #cancelDrawing()
1213
     * @see FLayers#setDirty(boolean)
1214
     */
1215
    public void drawMap(boolean doClear) {
1216
        cancelDrawing();
1217
        status = DESACTUALIZADO;
1218
        if (doClear) {
1219
            clearImage(image);
1220
        }
1221
        repaint();
1222
        revalidate();
1223
    }
1224

    
1225
    /**
1226
     * <p>
1227
     * Cancels any current drawing process, changing the status to
1228
     * <code>OUTDATED</code>, and forcing repaint only the layers dirty.
1229
     * </p>
1230
     *
1231
     * @see #cancelDrawing()
1232
     */
1233
    public void rePaintDirtyLayers() {
1234
        cancelDrawing();
1235
        status = DESACTUALIZADO;
1236
        repaint();
1237
    }
1238

    
1239
    /**
1240
     * @deprecated use {@link #drawMap(boolean)} instead, or even
1241
     * better {@link #getMapContext()}.invalidate().
1242
     */
1243
    public void drawGraphics() {
1244
        drawMap(false);
1245
    }
1246

    
1247
    /**
1248
     * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1249
     */
1250
    public void componentHidden(ComponentEvent e) {
1251
    }
1252

    
1253
    /**
1254
     * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1255
     */
1256
    public void componentMoved(ComponentEvent e) {
1257
    }
1258

    
1259
    /**
1260
     * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1261
     */
1262
    public void componentResized(ComponentEvent e) {
1263
        /*
1264
         * image = new BufferedImage(this.getWidth(), this.getHeight(),
1265
         * BufferedImage.TYPE_INT_ARGB);
1266
         * Graphics gTemp = image.createGraphics();
1267
         * gTemp.setColor(vp.getBackColor());
1268
         * gTemp.fillRect(0,0,getWidth(), getHeight());
1269
         * System.out.println("MapControl resized");
1270
         * // image = null;
1271
         * vp.setImageSize(new Dimension(getWidth(), getHeight()));
1272
         * getMapContext().getViewPort().setScale();
1273
         */
1274
        // drawMap(true);
1275
    }
1276

    
1277
    /**
1278
     * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1279
     */
1280
    public void componentShown(ComponentEvent e) {
1281
    }
1282

    
1283
    /**
1284
     * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
1285
     */
1286
    public void addExceptionListener(ExceptionListener o) {
1287
        exceptionHandlingSupport.addExceptionListener(o);
1288
    }
1289

    
1290
    /**
1291
     * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
1292
     */
1293
    public boolean removeExceptionListener(ExceptionListener o) {
1294
        return exceptionHandlingSupport.removeExceptionListener(o);
1295
    }
1296

    
1297
    /**
1298
     * @see ExceptionHandlingSupport#throwException(Throwable)
1299
     */
1300
    protected void throwException(Throwable t) {
1301
        exceptionHandlingSupport.throwException(t);
1302
    }
1303

    
1304
    /**
1305
     * <p>
1306
     * Represents each <code>MapControl</code>'s data painting request.
1307
     * </p>
1308
     *
1309
     * <p>
1310
     * The request will be attended by a <code>Drawer2</code>, which will hold
1311
     * it since the <code>Drawer2</code>'s worker takes it, or arrives a new
1312
     * painting request, which will replace it.
1313
     * </p>
1314
     */
1315
    private class PaintingRequest {
1316

    
1317
        /**
1318
         * <p>
1319
         * Creates a new <code>PaintingRequest
1320
         * </p>
1321
         * instance.</p>
1322
         */
1323
        public PaintingRequest() {
1324
        }
1325

    
1326
        /**
1327
         * <p>
1328
         * <code>MapControl</code> paint process:
1329
         * </p>
1330
         *
1331
         * <p>
1332
         * <ul>
1333
         * <li><i>1.- </i>Cancels all previous <code>MapControl</code>'s drawing
1334
         * processes.</li>
1335
         * <li><i>2.- </i>If <i>status</i> was OUTDATED:
1336
         * <ul>
1337
         * <li><i>2.1.- </i>Fills the background color with viewport's
1338
         * background color, or <i>white</i> if it was undefined.</li>
1339
         * <li><i>2.2.- </i>Notifies <i>MapContext</i> to be drawn invoking: <code>mapContext.draw(double-buffer, double-buffer's buffer, shared cancel-draw object, mapContext.getScaleView());</code>
1340
         * .</li>
1341
         * <li><i>2.3.- </i>If <code>canceldraw.isCanceled()</code>
1342
         * <ul>
1343
         * <li><i>2.3.1.- </i>Sets <i>status</i> to OUTDATED.</li>
1344
         * <li><i>2.3.2.- </i>Sets <i>dirty</i> all layers stored in
1345
         * <i>MapContext</i>.</li>
1346
         * </ul>
1347
         * </li>
1348
         * <li><i>2.4.- </i>Else, sets <i>status</i> to UPDATED.</li>
1349
         * </ul>
1350
         * </li>
1351
         * <li><i>3.- </i>Stops the <i>timer</i>.</li>
1352
         * <li><i>4.- </i>Repaints this component invoking:
1353
         * <code>repaint();</code></li>
1354
         * </ul>
1355
         * </p>
1356
         *
1357
         * @see #cancelDrawing()
1358
         * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
1359
         * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable,
1360
         *      double)
1361
         *
1362
         * @see ViewPort
1363
         */
1364
        public void paint() {
1365
            try {
1366
                canceldraw.setCanceled(false);
1367
                if (status == DESACTUALIZADO) {
1368
                    BufferedImage drawImage = image;
1369
                    if( paintMode == PAINT_WHEN_DRAW_LAYERS_IS_COMPLETED ) {
1370
                        drawImage = new BufferedImage(
1371
                            image.getWidth(),
1372
                            image.getHeight(),
1373
                            BufferedImage.TYPE_INT_ARGB
1374
                        );
1375
                    }
1376
                    clearImage(drawImage);
1377
                    Graphics2D g = drawImage.createGraphics();
1378
                    mapContext.draw(drawImage, g, canceldraw, mapContext.getScaleView());
1379
                    g.dispose();
1380
                    image = drawImage;
1381
                    if (!canceldraw.isCanceled()) {
1382
                        status = ACTUALIZADO;
1383
                    }
1384
                                }
1385
                timer.stop();
1386
                repaint();
1387

    
1388
            } catch (Throwable e) {
1389
                timer.stop();
1390
                LOG.warn("Problems drawing mapcontext.",e);
1391
                throwException(e);
1392
            }
1393
        }
1394
    }
1395

    
1396
    /**
1397
     * <p>
1398
     * An instance of <code>Drawer2</code> could manage all
1399
     * <code>MapControl</code> painting requests.
1400
     * </p>
1401
     *
1402
     * <p>
1403
     * Based on the <i>WorkerThread</i> software pattern, creates a worker
1404
     * thread that will attend sequentially the current waiting painting
1405
     * request, after finishing the previous (that could be by a cancel action).
1406
     * </p>
1407
     *
1408
     * <p>
1409
     * All new {@link PaintingRequest PaintingRequest} generated will be stored
1410
     * as <i>waiting requests</i> since the worker attends it.
1411
     * </p>
1412
     *
1413
     * <p>
1414
     * If a worker finished and there was no <i>painting request</i>, the worker
1415
     * would be set to wait until any <i>painting request</i> would be put.
1416
     * </p>
1417
     *
1418
     * @author fjp
1419
     */
1420
    public class Drawer {
1421

    
1422
        // Una mini cola de 2. No acumulamos peticiones de dibujado
1423
        // dibujamos solo lo �ltimo que nos han pedido.
1424

    
1425
        /**
1426
         * <p>
1427
         * Painting request that's been attended by the <code>Drawer2</code>'s
1428
         * worker.
1429
         * </p>
1430
         *
1431
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1432
         * @see #take()
1433
         */
1434
        private PaintingRequest paintingRequest;
1435

    
1436
        /**
1437
         * <p>
1438
         * Painting request waiting to be attended by the <code>Drawer2</code>'s
1439
         * worker.
1440
         * </p>
1441
         *
1442
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1443
         * @see #take()
1444
         */
1445
        private PaintingRequest waitingRequest;
1446

    
1447
        /**
1448
         * <p>
1449
         * Determines that the <code>Drawer2</code>'s worker is busy attending a
1450
         * painting request.
1451
         * </p>
1452
         *
1453
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1454
         * @see #take()
1455
         */
1456
        private boolean waiting;
1457

    
1458
        /**
1459
         * <p>
1460
         * Notifies the <code>Drawer2</code>'s worker to finish or continue with
1461
         * its process.
1462
         * </p>
1463
         *
1464
         * @see #setShutdown(boolean)
1465
         */
1466
        private boolean shutdown;
1467

    
1468
                private Thread worker;
1469

    
1470
        /**
1471
         * <p>
1472
         * Sets this <code>Drawer2</code>'s worker to finish or continue with
1473
         * its process.
1474
         * </p>
1475
         *
1476
         * @param isShutdown
1477
         *            a boolean value
1478
         */
1479
        public void setShutdown(boolean isShutdown) {
1480
            shutdown = isShutdown;
1481
            if (shutdown) {
1482
                    worker.interrupt();
1483
            }
1484
        }
1485

    
1486
        /**
1487
         * <p>
1488
         * Creates a new drawer for managing all data painting requests in
1489
         * <code>MapControl</code>.
1490
         * </p>
1491
         *
1492
         * <p>
1493
         * Includes the following steps:
1494
         * <ul>
1495
         * <li>By default, there is no <i>current painting request</i>.</li>
1496
         * <li>By default, there is no <i>waiting painting request</i>.</li>
1497
         * <li>By default, the worker thread is waiting no <i>painting
1498
         * request</i>.</li>
1499
         * <li>By default, the worker thread is running.</li>
1500
         * <li>Creates and starts a worker thread for attending the <i>painting
1501
         * requests</i>.</li>
1502
         * </ul>
1503
         * </p>
1504
         */
1505
        public Drawer() {
1506
            paintingRequest = null;
1507
            waitingRequest = null;
1508
            waiting = false;
1509
            shutdown = false;
1510
            worker = new Thread(new Worker(), "MapControl Drawer Worker");
1511
            worker.start();
1512
        }
1513

    
1514
        /**
1515
         * <p>
1516
         * Sets a <code>PaintingRequest</code> to be attended by the worker
1517
         * thread of this object. If this one was waiting, wakes up.
1518
         * </p>
1519
         *
1520
         * <p>
1521
         * All waiting threads will be notified synchronized.
1522
         * </p>
1523
         *
1524
         * @param newPaintRequest
1525
         *
1526
         * @see #take()
1527
         */
1528
        public void put(PaintingRequest newPaintRequest) {
1529
            waitingRequest = newPaintRequest;
1530
            if (waiting) {
1531
                synchronized (this) {
1532
                    notifyAll();
1533
                }
1534
            }
1535
        }
1536

    
1537
        /**
1538
         * <p>
1539
         * Used by this object's worker, returns the current waiting drawing
1540
         * request, causing current thread to wait until another thread invokes
1541
         * {@link #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1542
         * #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)}, if there
1543
         * was no waiting request.
1544
         * </p>
1545
         *
1546
         * <p>
1547
         * All threads will access synchronized to the waiting request.
1548
         * </p>
1549
         *
1550
         * @return <code>PaintingRequest</code> that was waiting to be attended
1551
         *
1552
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1553
         */
1554
        public PaintingRequest take() {
1555
            if (waitingRequest == null) {
1556
                synchronized (this) {
1557
                    waiting = true;
1558
                    try {
1559
                        wait();
1560
                    } catch (InterruptedException ie) {
1561
                        waiting = false;
1562
                    }
1563
                }
1564
            }
1565
            paintingRequest = waitingRequest;
1566
            waitingRequest = null;
1567
            return paintingRequest;
1568
        }
1569

    
1570
        /**
1571
         * <p>
1572
         * Thread for attending painting requests.
1573
         * </p>
1574
         *
1575
         * <p>
1576
         * If there was no double buffer, sets the status to
1577
         * <code>OUTDATED</code> and finishes, otherwise takes the painting
1578
         * request (it's probably that would wait some time), cancel the
1579
         * previous drawing process, and starts processing the request.
1580
         * </p>
1581
         *
1582
         * @see Thread
1583
         */
1584
        private class Worker implements Runnable {
1585

    
1586
            /*
1587
             * (non-Javadoc)
1588
             *
1589
             * @see java.lang.Runnable#run()
1590
             */
1591
            public void run() {
1592
                while (!shutdown) {
1593
                    PaintingRequest p = take();
1594
                    // System.out.println("Pintando");
1595
                    if (image != null) {
1596
                        cancelDrawing();
1597
                        if (p != null) {
1598
                                p.paint();
1599
                        }
1600
                    } else {
1601
                        status = DESACTUALIZADO;
1602
                    }
1603
                }
1604
            }
1605
        }
1606
    }
1607

    
1608
    /**
1609
     * <p>
1610
     * An instance of <code>CancelDraw</code> will be shared by all this
1611
     * <code>MapControl</code>'s <code>MapContext</code> layers, allowing
1612
     * receive a notification that, when they're been drawn, to be cancelled.
1613
     * </p>
1614
     *
1615
     * @see Cancellable
1616
     *
1617
     * @author Fernando Gonz�lez Cort�s
1618
     */
1619
    public class CancelDraw implements Cancellable {
1620

    
1621
        /**
1622
         * <p>
1623
         * Determines if the drawing task must be canceled or not.
1624
         * </p>
1625
         *
1626
         * @see #isCanceled()
1627
         * @see #setCanceled(boolean)
1628
         */
1629
        private boolean cancel = false;
1630

    
1631
        /**
1632
         * Creates a new <code>CancelDraw</code> object.
1633
         */
1634
        public CancelDraw() {
1635
        }
1636

    
1637
        /*
1638
         * (non-Javadoc)
1639
         *
1640
         * @see com.iver.utiles.swing.threads.Cancellable#setCanceled(boolean)
1641
         */
1642
        public void setCanceled(boolean b) {
1643
            cancel = b;
1644
        }
1645

    
1646
        /*
1647
         * (non-Javadoc)
1648
         *
1649
         * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
1650
         */
1651
        public boolean isCanceled() {
1652
            return cancel;
1653
        }
1654
    }
1655

    
1656
    /**
1657
     * <p>
1658
     * Listens all kind of mouse events produced in {@link MapControl
1659
     * MapControl}, and invokes its current map tool <i>(
1660
     * {@link MapControl#getCurrentMapTool() MapControl#getCurrentMapTool()}</i>
1661
     * to simulate a behavior.
1662
     * </p>
1663
     *
1664
     * <p>
1665
     * Mouse wheel moved events produce a <i>zoom in</i> operation if wheel
1666
     * rotation is negative, or a <i>zoom out</i> if its positive. Both will be
1667
     * centered in the position of the mouse, but, meanwhile <i>zoom in</i>
1668
     * operation applies a factor of 0.9, <i>zoom out</i> operation applies a
1669
     * factor of 1.2
1670
     * </p>
1671
     *
1672
     * <p>
1673
     * Mouse wheel moved events can be produced as much frequently, that between
1674
     * each one, the drawing process could hadn't finished. This is the reason
1675
     * that, in this situation, cancels always the previous drawing process
1676
     * before applying a <i>zoom</i> operation, and ignores all new mouse
1677
     * positions that are produced before 1 second.
1678
     * </p>
1679
     *
1680
     * @author Fernando Gonz�lez Cort�s
1681
     */
1682
    public class MapToolListener implements MouseListener, MouseWheelListener,
1683
        MouseMotionListener {
1684

    
1685
        /**
1686
         * <p>
1687
         * Used to avoid mouse wheel move events closed.
1688
         * </p>
1689
         *
1690
         * <p>
1691
         * If a mouse wheel move event is produced
1692
         */
1693
        long t1;
1694

    
1695
        /**
1696
         * <p>
1697
         * Position of the mouse, in map coordinates.
1698
         * </p>
1699
         *
1700
         * <p>
1701
         * This point coordinates will be used as center of the <i>zoom</i>
1702
         * operation.
1703
         * </p>
1704
         */
1705
        Point2D pReal;
1706

    
1707
        /**
1708
         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1709
         * @see Behavior#mouseClicked(MouseEvent)
1710
         */
1711
        public void mouseClicked(MouseEvent e) {
1712
            try {
1713
                if (currentMapTool != null) {
1714
                    currentMapTool.mouseClicked(e);
1715
                }
1716
                Point2D p;
1717

    
1718
                if (mapAdjustedPoint != null) {
1719
                    p = mapAdjustedPoint;
1720
                } else {
1721
                    p = vp.toMapPoint(adjustedPoint);
1722
                }
1723
                previousPoint = new double[] { p.getX(), p.getY() };
1724
            } catch (BehaviorException t) {
1725
                throwException(t);
1726
            }
1727
        }
1728

    
1729
        /**
1730
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1731
         * @see Behavior#mouseEntered(MouseEvent)
1732
         */
1733
        public void mouseEntered(MouseEvent e) {
1734
            setToolMouse();
1735
            try {
1736
                if (currentMapTool != null) {
1737
                    currentMapTool.mouseEntered(e);
1738
                }
1739
            } catch (BehaviorException t) {
1740
                throwException(t);
1741
            }
1742
        }
1743

    
1744
        /**
1745
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1746
         * @see Behavior#mouseExited(MouseEvent)
1747
         */
1748
        public void mouseExited(MouseEvent e) {
1749
            try {
1750
                if (currentMapTool != null) {
1751
                    currentMapTool.mouseExited(e);
1752
                }
1753
            } catch (BehaviorException t) {
1754
                throwException(t);
1755
            }
1756
            // Remove the snapping image if exist
1757
            usedSnap = null;
1758
            repaint();
1759
        }
1760

    
1761
        /**
1762
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1763
         * @see Behavior#mousePressed(MouseEvent)
1764
         */
1765
        public void mousePressed(MouseEvent e) {
1766
            try {
1767
                if (currentMapTool != null) {
1768
                    currentMapTool.mousePressed(e);
1769
                }
1770
            } catch (BehaviorException t) {
1771
                throwException(t);
1772
            }
1773
        }
1774

    
1775
        /**
1776
         * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1777
         * @see Behavior#mouseReleased(MouseEvent)
1778
         */
1779
        public void mouseReleased(MouseEvent e) {
1780
            try {
1781
                if (currentMapTool != null) {
1782
                    currentMapTool.mouseReleased(e);
1783
                }
1784
            } catch (BehaviorException t) {
1785
                throwException(t);
1786
            }
1787
        }
1788

    
1789
        /**
1790
         * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
1791
         * @see Behavior#mouseWheelMoved(MouseWheelEvent)
1792
         */
1793
        public void mouseWheelMoved(MouseWheelEvent e) {
1794
            try {
1795
                if (currentMapTool == null) {
1796
                    return;
1797
                }
1798

    
1799
                currentMapTool.mouseWheelMoved(e);
1800

    
1801
                // Si el tool actual no ha consumido el evento
1802
                // entendemos que quiere el comportamiento por defecto.
1803
                if (!e.isConsumed() && defaultMouseWheelEnabled ) {
1804
                    // Para usar el primer punto sobre el que queremos centrar
1805
                    // el mapa, dejamos pasar un segundo para considerar el
1806
                    // siguiente
1807
                    // punto como v�lido.
1808
                    if (t1 == 0) {
1809
                        t1 = System.currentTimeMillis();
1810
                        pReal = vp.toMapPoint(e.getPoint());
1811
                    } else {
1812
                        long t2 = System.currentTimeMillis();
1813
                        if ((t2 - t1) > 1000) {
1814
                            t1 = 0;
1815
                        }
1816
                    }
1817
                    cancelDrawing();
1818
                    ViewPort vp = getViewPort();
1819

    
1820
                    /*
1821
                     * Point2D pReal = new
1822
                     * Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1823
                     * vp.getAdjustedExtent().getCenterY());
1824
                     */
1825
                    int amount = e.getWheelRotation();
1826
                    double nuevoX;
1827
                    double nuevoY;
1828
                    double factor;
1829

    
1830
                    if (amount < 0) // nos acercamos
1831
                    {
1832
                        factor = 0.9;
1833
                    } else // nos alejamos
1834
                    {
1835
                        factor = 1.2;
1836
                    }
1837
                    if (vp.getExtent() != null) {
1838
                        nuevoX =
1839
                            pReal.getX()
1840
                                - ((vp.getExtent().getWidth() * factor) / 2.0);
1841
                        nuevoY =
1842
                            pReal.getY()
1843
                                - ((vp.getExtent().getHeight() * factor) / 2.0);
1844
                        double x = nuevoX;
1845
                        double y = nuevoY;
1846
                        double width = vp.getExtent().getWidth() * factor;
1847
                        double height = vp.getExtent().getHeight() * factor;
1848

    
1849
                        try {
1850
                            vp.setEnvelope(geomManager.createEnvelope(x, y, x
1851
                                + width, y + height, SUBTYPES.GEOM2D));
1852
                        } catch (CreateEnvelopeException e1) {
1853
                            LOG.info("Error creating the envelope", e);
1854
                        }
1855
                    }
1856

    
1857
                }
1858
            } catch (BehaviorException t) {
1859
                throwException(t);
1860
            }
1861
        }
1862

    
1863
        /**
1864
         * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1865
         * @see Behavior#mouseDragged(MouseEvent)
1866
         */
1867
        public void mouseDragged(MouseEvent e) {
1868
            calculateSnapPoint(e.getPoint());
1869
            try {
1870
                if (currentMapTool != null) {
1871
                    currentMapTool.mouseDragged(e);
1872
                }
1873
            } catch (BehaviorException t) {
1874
                throwException(t);
1875
            }
1876
            repaint();
1877
        }
1878

    
1879
        /**
1880
         * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
1881
         * @see Behavior#mouseMoved(MouseEvent)
1882
         */
1883
        public void mouseMoved(MouseEvent e) {
1884
            calculateSnapPoint(e.getPoint());
1885
            try {
1886
                if (currentMapTool != null) {
1887
                    currentMapTool.mouseMoved(e);
1888
                }
1889
            } catch (BehaviorException t) {
1890
                throwException(t);
1891
            }
1892
            repaint();
1893
        }
1894
    }
1895

    
1896
    /**
1897
     * <p<code>MapContextListener</code> listens all events produced in a
1898
     * <code>MapControl</code>'s <code>MapContext</code> object during an atomic
1899
     * period of time, and sets it to dirty, <i>executing
1900
     * <code>drawMap(false)</code>, if any of the
1901
     * following conditions is accomplished</i>:
1902
     * <ul>
1903
     * <li>Any of the <code>LayerEvent</code> in the <code>AtomicEvent</code>
1904
     * parameter notifies a <i>visibility change</i>.</li>
1905
     * <li>There is at least one <code>ColorEvent</code> in the
1906
     * <code>AtomicEvent</code> parameter.</li>
1907
     * <li>There is at least one <code>ExtentEvent</code> in the
1908
     * <code>AtomicEvent</code> parameter.</li>
1909
     * <li>Any of the <code>LayerCollectionEvent</code> in the
1910
     * <code>AtomicEvent</code> parameter notifies that a driver's layer has
1911
     * reloaded it successfully.</li>
1912
     * <li>There is at least one <code>LegendEvent</code> in the
1913
     * <code>AtomicEvent</code> parameter.</li>
1914
     * <li>There is at least one <code>SelectionEvent</code> in the
1915
     * <code>AtomicEvent</code> parameter.</li>
1916
     * </ul>
1917
     * </p>
1918
     *
1919
     * @author Fernando Gonz�lez Cort�s
1920
     */
1921
    public class MapContextListener implements AtomicEventListener {
1922

    
1923
        /**
1924
         * @see org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener#atomicEvent(org.gvsig.fmap.mapcontext.events.AtomicEvent)
1925
         */
1926
        public void atomicEvent(final AtomicEvent e) {
1927
            if (!SwingUtilities.isEventDispatchThread()) {
1928
                SwingUtilities.invokeLater(new Runnable() {
1929

    
1930
                    public void run() {
1931
                        atomicEvent(e);
1932
                    }
1933
                });
1934
                return;
1935
            }
1936
            LayerEvent[] layerEvents = e.getLayerEvents();
1937

    
1938
            for (int i = 0; i < layerEvents.length; i++) {
1939
                if (layerEvents[i].getProperty().equals("visible")) {
1940
                    drawMap(false);
1941
                    return;
1942
                } else
1943
                    if (layerEvents[i].getEventType() == LayerEvent.EDITION_CHANGED) {
1944
                        drawMap(false);
1945
                        return;
1946
                    }
1947
            }
1948

    
1949
            if (e.getColorEvents().length > 0) {
1950
                drawMap(false);
1951
                return;
1952
            }
1953

    
1954
            if (e.getExtentEvents().length > 0) {
1955
                drawMap(false);
1956
                return;
1957
            }
1958

    
1959
            if (e.getProjectionEvents().length > 0) {
1960
                // redraw = true;
1961
            }
1962

    
1963
            LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1964
            if (aux.length > 0) {
1965
                for (int i = 0; i < aux.length; i++) {
1966
                    if (aux[i].getAffectedLayer().getFLayerStatus()
1967
                        .isDriverLoaded()) {
1968
                        drawMap(false);
1969
                        return;
1970
                    }
1971
                }
1972

    
1973
            }
1974

    
1975
            if (e.getLegendEvents().length > 0) {
1976
                drawMap(false);
1977
                return;
1978
            }
1979

    
1980
            if (e.getSelectionEvents().length > 0) {
1981
                drawMap(false);
1982
                return;
1983
            }
1984
        }
1985
    }
1986

    
1987
    /**
1988
     * <p>
1989
     * Gets the <code>ViewPort</code> of this component's {@link MapContext
1990
     * MapContext} .
1991
     * </p>
1992
     *
1993
     * @see MapContext#getViewPort()
1994
     */
1995
    public ViewPort getViewPort() {
1996
        return vp;
1997
    }
1998

    
1999
    /**
2000
     * <p>
2001
     * Returns all registered <code>Behavior</code> that can define a way to
2002
     * work with this <code>MapControl</code>.
2003
     * </p>
2004
     *
2005
     * @return registered <code>Behavior</code> to this <code>MapControl</code>
2006
     *
2007
     * @see #addBehavior(String, Behavior)
2008
     * @see #addBehavior(String, Behavior[])
2009
     * @see #getMapToolsKeySet()
2010
     * @see #hasTool(String)
2011
     */
2012
    public HashMap getNamesMapTools() {
2013
        return (HashMap) namesMapTools;
2014
    }
2015

    
2016
    /*
2017
     * (non-Javadoc)
2018
     *
2019
     * @see
2020
     * com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
2021
     */
2022
    public void commandRepaint() {
2023
        drawMap(false);
2024
    }
2025

    
2026
    /*
2027
     * (non-Javadoc)
2028
     *
2029
     * @see
2030
     * com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
2031
     */
2032
    public void commandRefresh() {
2033
        // TODO Auto-generated method stub
2034
    }
2035

    
2036
    /**
2037
     * <p>
2038
     * Equivalent operation to <i>undo</i>.
2039
     * </p>
2040
     *
2041
     * <p>
2042
     * Exchanges the previous tool with the current one.
2043
     * </p>
2044
     *
2045
     * @see #addBehavior(String, Behavior)
2046
     * @see #addBehavior(String, Behavior[])
2047
     * @see #setTool(String)
2048
     */
2049
    public void setPrevTool() {
2050
        setTool(prevTool);
2051
    }
2052

    
2053
    /**
2054
     * <p>
2055
     * Executes a <i>zoom in</i> operation centered at the center of the extent.
2056
     * </p>
2057
     *
2058
     * <p>
2059
     * This implementation is designed for being invoked outside a
2060
     * <code>Behavior</code>, for example by an action of pressing a button; and
2061
     * simulates that the event has been produced by releasing the <i>button
2062
     * 1</i> of the mouse using the registered <code>Behavior</code> in this
2063
     * <code>MapControl</code> object that's responsible for the <i>zoom in</i>
2064
     * operation.
2065
     * </p>
2066
     *
2067
     * @see #zoomOut()
2068
     */
2069
    public void zoomIn() {
2070
        Behavior mapTool = (Behavior) namesMapTools.get("zoomIn");
2071
        ViewPort vp = getViewPort();
2072
        Envelope r = getViewPort().getAdjustedExtent();
2073
        Point2D pCenter = vp.fromMapPoint(r.getCenter(0), r.getCenter(1));
2074
        MouseEvent e =
2075
            new MouseEvent(this, MouseEvent.MOUSE_RELEASED,
2076
                MouseEvent.ACTION_EVENT_MASK, MouseEvent.BUTTON1_MASK, (int) pCenter
2077
                    .getX(), (int) pCenter.getY(), 1, true, MouseEvent.BUTTON1);
2078
        try {
2079
            mapTool.mousePressed(e);
2080
            mapTool.mouseReleased(e);
2081
        } catch (BehaviorException t) {
2082
            throwException(t);
2083
        }
2084
    }
2085

    
2086
    /**
2087
     * <p>
2088
     * Executes a <i>zoom out</i> operation centered at the center of the
2089
     * extent.
2090
     * </p>
2091
     *
2092
     * <p>
2093
     * This implementation is thought for being invoked outside a
2094
     * <code>Behavior</code>, for example by an action of pressing a button, and
2095
     * simulates that the event has been produced by releasing the <i>button
2096
     * 1</i> of the mouse using the registered <code>Behavior</code> in this
2097
     * <code>MapControl</code> object that's responsible for the <i>zoom out</i>
2098
     * operation.
2099
     * </p>
2100
     *
2101
     * @see #zoomIn()
2102
     */
2103
    public void zoomOut() {
2104
        Behavior mapTool = (Behavior) namesMapTools.get("zoomOut");
2105
        ViewPort vp = getViewPort();
2106
        Envelope r = getViewPort().getAdjustedExtent();
2107
        Point2D pCenter = vp.fromMapPoint(r.getCenter(0), r.getCenter(1));
2108
        MouseEvent e =
2109
            new MouseEvent(this, MouseEvent.MOUSE_RELEASED,
2110
                MouseEvent.ACTION_EVENT_MASK, MouseEvent.BUTTON1_MASK, (int) pCenter
2111
                    .getX(), (int) pCenter.getY(), 1, true, MouseEvent.BUTTON1);
2112
        try {
2113
            mapTool.mousePressed(e);
2114
            mapTool.mouseReleased(e);
2115
        } catch (BehaviorException t) {
2116
            throwException(t);
2117
        }
2118
    }
2119

    
2120
    /**
2121
     * <p>
2122
     * Returns the listener used to catch all mouse events produced in this
2123
     * <code>MapControl</code> instance and that redirects the calls to the
2124
     * current map tool.
2125
     * </p>
2126
     *
2127
     * @return the map tool listener used
2128
     */
2129
    public MapToolListener getMapToolListener() {
2130
        return mapToolListener;
2131
    }
2132

    
2133
    // mapTool can be null, for instance, in 3D's navigation tools
2134
    /**
2135
     * <p>
2136
     * Sets <code>mapTool</code> as this <code>MapControl</code>'s current map
2137
     * tool.
2138
     *
2139
     * @param mapTool
2140
     *            a map tool, or <code>null</code> to disable the interaction
2141
     *            with the user
2142
     *
2143
     * @see #getCurrentMapTool()
2144
     * @see #getCurrentTool()
2145
     * @see #setTool(String)
2146
     * @see #setPrevTool()
2147
     * @see #addBehavior(String, Behavior)
2148
     * @see #addBehavior(String, Behavior[])
2149
     */
2150
    public void setCurrentMapTool(Behavior mapTool) {
2151
        currentMapTool = mapTool;
2152
    }
2153

    
2154
    /**
2155
     * <p>
2156
     * Sets the delay to the timer that refreshes this <code>MapControl</code>
2157
     * instance.
2158
     * </p>
2159
     *
2160
     * <p>
2161
     * <code>Delay (in ms) = 1000 / getDrawFrameRate()</code>
2162
     * </p>
2163
     *
2164
     * @see #getDrawFrameRate()
2165
     * @see #setDrawFrameRate(int)
2166
     */
2167
    public void applyFrameRate() {
2168
        if (MapContext.getDrawFrameRate() > 0) {
2169
            timer.setDelay(1000 / MapContext.getDrawFrameRate());
2170
        }
2171
    }
2172

    
2173
    /**
2174
     * <p>
2175
     * Determines if its enabled the repaint that invokes the timer according to
2176
     * {@link #getDrawFrameRate() #getDrawFrameRate()}.
2177
     * </p>
2178
     *
2179
     * @return <code>true</code> if its enabled; otherwise <code>false</code>
2180
     */
2181
    public static boolean isDrawAnimationEnabled() {
2182
        return drawAnimationEnabled;
2183
    }
2184

    
2185
    /**
2186
     * <p>
2187
     * Sets if its enabled the repaint that invokes the timer according to
2188
     * {@link #getDrawFrameRate() #getDrawFrameRate()}.
2189
     * </p>
2190
     *
2191
     * @param drawAnimationEnabled
2192
     *            <code>true</code> to enable the mode; otherwise
2193
     *            <code>false</code>
2194
     */
2195
    public static void setDrawAnimationEnabled(boolean drawAnimationEnabled) {
2196
        MapControl.drawAnimationEnabled = drawAnimationEnabled;
2197
    }
2198

    
2199
    /**
2200
     * <p>
2201
     * Gets the shared object that determines if a drawing process must be
2202
     * cancelled or can continue.
2203
     * </p>
2204
     *
2205
     * @return the shared object that determines if a drawing process must be
2206
     *         cancelled or can continue
2207
     */
2208
    public CancelDraw getCanceldraw() {
2209
        return canceldraw;
2210
    }
2211

    
2212
    /**
2213
     * <p>
2214
     * Gets the tool used in combination with the current tool of this
2215
     * <code>MapControl</code>.
2216
     * </p>
2217
     *
2218
     * @return the tool used in combination with the <code>currentMapTool</code>
2219
     *         ; <code>null</code> if there is
2220
     *         no combined tool
2221
     */
2222
    public Behavior getCombinedTool() {
2223
        return combinedTool;
2224
    }
2225

    
2226
    /**
2227
     * <p>
2228
     * Sets a tool to be used in combination with the current tool of this
2229
     * <code>MapControl</code>.
2230
     * </p>
2231
     *
2232
     * @param combinedTool
2233
     *            a tool to be used in combination with the current tool of
2234
     *            <code>MapControl</code>
2235
     */
2236
    public void setCombinedTool(Behavior combinedTool) {
2237
        this.combinedTool = combinedTool;
2238

    
2239
        if (currentMapTool == null) {
2240
            return;
2241
        }
2242

    
2243
        if (currentMapTool instanceof CompoundBehavior) {
2244
            ((CompoundBehavior) currentMapTool).addMapBehavior(combinedTool,
2245
                true);
2246
        } else {
2247
            currentMapTool =
2248
                new CompoundBehavior(new Behavior[] { currentMapTool });
2249
            ((CompoundBehavior) currentMapTool).addMapBehavior(combinedTool,
2250
                true);
2251
        }
2252

    
2253
    }
2254

    
2255
    /**
2256
     * <p>
2257
     * Adds a new tool as combined tool.
2258
     * </p>
2259
     * <p>
2260
     * The new tool will be stored with the previous combined tools, and will be
2261
     * combined with the current tool.
2262
     * </p>
2263
     * <p>
2264
     * If <code>tool</code> was already stored as a combined tool, doesn't adds
2265
     * it.
2266
     * </p>
2267
     *
2268
     * @param tool
2269
     *            a new tool to be used combined with the current tool
2270
     */
2271
    public void addCombinedBehavior(Behavior tool) {
2272
        tool.setMapControl(this);
2273
        if (combinedTool == null) {
2274
            combinedTool = tool;
2275
        } else {
2276
            if (combinedTool instanceof CompoundBehavior) {
2277
                if (((CompoundBehavior) combinedTool).containsBehavior(tool)) {
2278
                    return;
2279
                }
2280

    
2281
                ((CompoundBehavior) combinedTool).addMapBehavior(tool, true);
2282
            } else {
2283
                if (combinedTool.equals(tool)) {
2284
                    return;
2285
                }
2286

    
2287
                combinedTool =
2288
                    new CompoundBehavior(new Behavior[] { combinedTool });
2289
                ((CompoundBehavior) combinedTool).addMapBehavior(tool, true);
2290
                combinedTool.setMapControl(this);
2291
            }
2292
        }
2293

    
2294
        if (currentMapTool == null) {
2295
            return;
2296
        }
2297

    
2298
        if (currentMapTool instanceof CompoundBehavior) {
2299
            ((CompoundBehavior) currentMapTool).addMapBehavior(tool, true);
2300
        } else {
2301
            currentMapTool =
2302
                new CompoundBehavior(new Behavior[] { currentMapTool });
2303
            ((CompoundBehavior) currentMapTool).addMapBehavior(tool, true);
2304
        }
2305
    }
2306

    
2307
    /**
2308
     * <p>
2309
     * Removes the tool <code>tool</code> used in combination with the current
2310
     * tool of this <code>MapControl</code>.
2311
     * </p>
2312
     */
2313
    public void removeCombinedTool(Behavior tool) {
2314
        if ((currentMapTool != null)
2315
            && (currentMapTool instanceof CompoundBehavior)) {
2316
            ((CompoundBehavior) currentMapTool).removeMapBehavior(tool);
2317
        }
2318

    
2319
        if (combinedTool == null) {
2320
            return;
2321
        }
2322

    
2323
        if (combinedTool instanceof CompoundBehavior) {
2324
            ((CompoundBehavior) combinedTool).removeMapBehavior(tool);
2325
        } else {
2326
            combinedTool = null;
2327
        }
2328
    }
2329

    
2330
    /**
2331
     * <p>
2332
     * Updates the grid on the <code>ViewPort</code> of the associated
2333
     * <code>MapControl</code> object according the values in the
2334
     * {@link com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences
2335
     * com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences}.
2336
     * </p>
2337
     *
2338
     * <p>
2339
     * The preferences are:
2340
     * <ul>
2341
     * <li>Show/hide the grid.</li>
2342
     * <li>Adjust or not the grid.</li>
2343
     * <li>Horizontal ( X ) line separation.</li>
2344
     * <li>Vertical ( Y ) line separation.</li>
2345
     * </ul>
2346
     * </p>
2347
     */
2348
    public void initializeGrid() {
2349
        Preferences prefs = mapControlManager.getEditionPreferences();
2350
        boolean showGrid =
2351
            prefs.getBoolean("grid.showgrid", cadgrid.isShowGrid());
2352
        boolean adjustGrid =
2353
            prefs.getBoolean("grid.adjustgrid", cadgrid.isAdjustGrid());
2354

    
2355
        double dx = prefs.getDouble("grid.distancex", cadgrid.getGridSizeX());
2356
        double dy = prefs.getDouble("grid.distancey", cadgrid.getGridSizeY());
2357

    
2358
        setGridVisibility(showGrid);
2359
        setAdjustGrid(adjustGrid);
2360
        cadgrid.setGridSizeX(dx);
2361
        cadgrid.setGridSizeY(dy);
2362
    }
2363

    
2364
    public void setAdjustGrid(boolean adjustGrid) {
2365
        cadgrid.setAdjustGrid(adjustGrid);
2366
    }
2367

    
2368
    public void setGridVisibility(boolean showGrid) {
2369
        cadgrid.setShowGrid(showGrid);
2370
        cadgrid.setViewPort(getViewPort());
2371
        this.repaint();
2372
    }
2373

    
2374
    /**
2375
     * Uses like a mouse pointer the image that provides the
2376
     * selected tool.
2377
     *
2378
     */
2379

    
2380
    private Image lastImageCursor = null;
2381
    private Cursor lastCursor = null;
2382

    
2383
    private void setToolMouse() {
2384
        Image imageCursor = getCurrentMapTool().getImageCursor();
2385
        if (imageCursor != null && imageCursor == lastImageCursor && lastCursor != null && lastCursor != transparentCursor) {
2386
            setCursor(lastCursor);
2387
            return;
2388
        }
2389
        lastImageCursor = imageCursor;
2390
        Toolkit toolkit = Toolkit.getDefaultToolkit();
2391
        Cursor c = toolkit.createCustomCursor(imageCursor, new Point(16, 16), "img");
2392
        setCursor(c);
2393
        lastCursor = c;
2394
    }
2395

    
2396
    /**
2397
     * Makes the mouse pointer transparent.
2398
     */
2399
    private void setTransparentMouse() {
2400
        setCursor(transparentCursor);
2401
        lastCursor = transparentCursor;
2402
    }
2403

    
2404
    /**
2405
     * <p>
2406
     * Draws a 31x31 pixels cross round the mouse's cursor with an small
2407
     * geometry centered:
2408
     * <ul>
2409
     * <li><i>an square centered</i>: if isn't over a <i>control point</i>.
2410
     * <li><i>an small geometry centered according to the kind of control
2411
     * point</i>: if it's over a control point. In this case, the small geometry
2412
     * is drawn by a {@link ISnapper ISnapper} type object.<br>
2413
     * On the other hand, a light-yellowed background tool tip text with the
2414
     * type of <i>control point</i> will be displayed.</li>
2415
     * </p>
2416
     *
2417
     * @param g
2418
     *            <code>MapControl</code>'s graphics where the data will be
2419
     *            drawn
2420
     */
2421
    private void drawCursor() {
2422
        if (adjustedPoint == null) {
2423
            return;
2424
        }
2425

    
2426
        if (usedSnap != null) {
2427
            usedSnap.draw(mapControlDrawer, adjustedPoint);
2428
            setTransparentMouse();
2429
        } else {
2430
            setToolMouse();
2431
        }
2432
    }
2433

    
2434
    /**
2435
     * <p>
2436
     * Adjusts the <code>point</code> to the grid if its enabled, and sets
2437
     * <code>mapHandlerAdjustedPoint</code> with that new value.
2438
     * </p>
2439
     *
2440
     * <p>
2441
     * The value returned is the distance between those points: the original and
2442
     * the adjusted one.
2443
     * </p>
2444
     *
2445
     * @param point
2446
     *            point to adjust
2447
     * @param mapHandlerAdjustedPoint
2448
     *            <code>point</code> adjusted
2449
     *
2450
     * @return distance from <code>point</code> to the adjusted one. If there is
2451
     *         no
2452
     *         adjustment, returns <code>Double.MAX_VALUE</code>.
2453
     */
2454

    
2455
    private double adjustToHandler(Point2D point,
2456
        Point2D mapHandlerAdjustedPoint) {
2457

    
2458
        if (!isRefentEnabled())
2459
            return Double.MAX_VALUE;
2460

    
2461
        List layersToSnap = getMapContext().getLayersToSnap();
2462

    
2463
        double mapTolerance =
2464
            vp.toMapDistance(mapControlManager.getTolerance());
2465
        double minDist = mapTolerance;
2466
        double middleTol = mapTolerance * 0.5;
2467
        Point2D mapPoint = point;
2468
        Envelope r = null;
2469
        try {
2470
            r =
2471
                geomManager.createEnvelope(mapPoint.getX() - middleTol,
2472
                    mapPoint.getY() - middleTol, mapPoint.getX() + middleTol,
2473
                    mapPoint.getY() + middleTol, SUBTYPES.GEOM2D);
2474
        } catch (Exception e1) {
2475
            LOG.info("Error creating the envelope", e1);
2476
            return Double.MAX_VALUE;
2477
        }
2478

    
2479
        usedSnap = null;
2480
        Point2D lastPoint = null;
2481
        if (previousPoint != null) {
2482
            lastPoint = new Point2D.Double(previousPoint[0], previousPoint[1]);
2483
        }
2484
        for (int j = 0; j < layersToSnap.size(); j++) {
2485
            FLyrVect lyrVect = (FLyrVect) layersToSnap.get(j);
2486
            SpatialCache cache = lyrVect.getSpatialCache();
2487
            if (lyrVect.isVisible()) {
2488
                // La lista de snappers est� siempre ordenada por prioridad. Los
2489
                // de mayor
2490
                // prioridad est�n primero.
2491
                List geoms = cache.query(r);
2492

    
2493
                for (int i = 0; i < mapControlManager.getSnapperCount(); i++)
2494
                {
2495
                    ISnapper theSnapper = mapControlManager.getSnapperAt(i);
2496
                    if (theSnapper instanceof ISnapperGeometriesVectorial)
2497
                    {
2498
                        ((ISnapperGeometriesVectorial)theSnapper).setGeometries(geoms);
2499
                    }
2500
                }
2501

    
2502
                for (int n = 0; n < geoms.size(); n++) {
2503
                    Geometry geom = (Geometry) geoms.get(n);
2504
                    for (int i = 0; i < mapControlManager.getSnapperCount(); i++) {
2505
                        ISnapper theSnapper = mapControlManager.getSnapperAt(i);
2506
                        if (!theSnapper.isEnabled())
2507
                            continue;
2508

    
2509
                        if (usedSnap != null) {
2510
                            // Si ya tenemos un snap y es de alta prioridad,
2511
                            // cogemos ese. (A no ser que en otra capa
2512
                            // encontremos un snapper mejor)
2513
                            if (theSnapper.getPriority() > usedSnap
2514
                                .getPriority())
2515
                                break;
2516
                        }
2517
                        // SnappingVisitor snapVisitor = null;
2518
                        Point2D theSnappedPoint = null;
2519
                        if (theSnapper instanceof ISnapperVectorial) {
2520
                            theSnappedPoint =
2521
                                ((ISnapperVectorial) theSnapper).getSnapPoint(
2522
                                    point, geom, mapTolerance, lastPoint);
2523
                        }
2524
                        if (theSnapper instanceof ISnapperRaster) {
2525
                            ISnapperRaster snapRaster =
2526
                                (ISnapperRaster) theSnapper;
2527
                            theSnappedPoint =
2528
                                snapRaster.getSnapPoint(this, point,
2529
                                    mapTolerance, lastPoint);
2530
                        }
2531

    
2532
                        if (theSnappedPoint != null) {
2533
                            double distAux = theSnappedPoint.distance(point);
2534
                            if (minDist > distAux) {
2535
                                minDist = distAux;
2536
                                usedSnap = theSnapper;
2537
                                mapHandlerAdjustedPoint
2538
                                    .setLocation(theSnappedPoint);
2539
                            }
2540
                        }
2541
                    }
2542
                } // for n
2543
            } // visible
2544
        }
2545
        if (usedSnap != null)
2546
            return minDist;
2547
        return Double.MAX_VALUE;
2548

    
2549
    }
2550

    
2551
    /**
2552
     * Determines if snap tools are enabled or disabled.
2553
     *
2554
     * @return <code>true</code> to enable the snap tools; <code>false</code> to
2555
     *         disable them
2556
     *
2557
     * @see #setRefentEnabled(boolean)
2558
     */
2559
    public boolean isRefentEnabled() {
2560
        return bRefent;
2561
    }
2562

    
2563
    /**
2564
     * <p>
2565
     * Tries to find the nearest geometry or grid control point by the position
2566
     * of the current snap tool.
2567
     * </p>
2568
     *
2569
     * <p>
2570
     * Prioritizes the grid control points than the geometries ones.
2571
     * </p>
2572
     *
2573
     * <p>
2574
     * If finds any near, stores the <i>map</i> and <i>pixel</i> coordinates for
2575
     * the snap, and enables the <code>bForceCoord</code> attribute for the next
2576
     * draw of the mouse's cursor.
2577
     * </p>
2578
     *
2579
     * @param point
2580
     *            current mouse 2D position
2581
     */
2582
    public void calculateSnapPoint(Point point) {
2583
        // Se comprueba el ajuste a rejilla
2584

    
2585
        Point2D gridAdjustedPoint = vp.toMapPoint(point);
2586
        double minDistance = Double.MAX_VALUE;
2587

    
2588
        minDistance = cadgrid.adjustToGrid(gridAdjustedPoint);
2589
        if (minDistance < Double.MAX_VALUE) {
2590
            adjustedPoint = vp.fromMapPoint(gridAdjustedPoint);
2591
            mapAdjustedPoint = gridAdjustedPoint;
2592
        } else {
2593
            mapAdjustedPoint = null;
2594
        }
2595

    
2596
        Point2D handlerAdjustedPoint = null;
2597

    
2598
        // Se comprueba el ajuste a los handlers
2599
        if (mapAdjustedPoint != null) {
2600
            handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
2601
        } else {
2602
            handlerAdjustedPoint = vp.toMapPoint(point);
2603
        }
2604

    
2605
        Point2D mapPoint = new Point2D.Double();
2606
        double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
2607

    
2608
        if (distance < minDistance) {
2609
            bForceCoord = true;
2610
            adjustedPoint = vp.fromMapPoint(mapPoint);
2611
            mapAdjustedPoint = mapPoint;
2612
            minDistance = distance;
2613
        }
2614

    
2615
        // Si no hay ajuste
2616
        if (minDistance == Double.MAX_VALUE) {
2617
            adjustedPoint = point;
2618
            mapAdjustedPoint = null;
2619
        }
2620
    }
2621

    
2622
    /**
2623
     * Sets the snap tools enabled or disabled.
2624
     *
2625
     * @param activated
2626
     *            <code>true</code> to enable the snap tools; <code>false</code>
2627
     *            to disable them
2628
     *
2629
     * @see #isRefentEnabled()
2630
     */
2631
    public void setRefentEnabled(boolean activated) {
2632
        bRefent = activated;
2633
    }
2634

    
2635
    public Grid getGrid() {
2636
        return cadgrid;
2637
    }
2638

    
2639
    public void update(Observable observable, Object notification) {
2640
        DataStoreNotification ddsn = (DataStoreNotification) notification;
2641
        String type = ddsn.getType();
2642
        if (type.equals(FeatureStoreNotification.AFTER_UNDO)
2643
            || type.equals(FeatureStoreNotification.AFTER_REDO)) {
2644
            repaint();
2645
        }
2646
    }
2647

    
2648
    /**
2649
     * @return the adjustedPoint
2650
     */
2651
    public Point2D getAdjustedPoint() {
2652
        return adjustedPoint;
2653
    }
2654

    
2655
    /**
2656
     * @return the mapAdjustedPoint
2657
     */
2658
    public Point2D getMapAdjustedPoint() {
2659
        return mapAdjustedPoint;
2660
    }
2661

    
2662
    /**
2663
     * Gets the selected point. If the snapping is enabled
2664
     * it returns the selected point.
2665
     *
2666
     * @return
2667
     *         The selected point
2668
     */
2669
    public Point2D getPoint() {
2670
        if (mapAdjustedPoint != null) {
2671
            return mapAdjustedPoint;
2672
        } else {
2673
            return getViewPort().toMapPoint(adjustedPoint);
2674
        }
2675
    }
2676

    
2677
        public synchronized void dispose() {
2678
                // Check if we have already been disposed, and don't do it again
2679
                if (!disposed && ToolsLocator.getDisposableManager().release(this)) {
2680
                        drawer.setShutdown(true);
2681
                        disposed = true;
2682
                }
2683
        }
2684

    
2685
    public boolean isDefaultMouseWheelEnabled() {
2686
        return defaultMouseWheelEnabled;
2687
    }
2688

    
2689
    public void setDefaultMouseWheelEnabled(boolean defaultMouseWheelEnabled) {
2690
        this.defaultMouseWheelEnabled = defaultMouseWheelEnabled;
2691
    }
2692

    
2693
    private ChangeListenerHelper changeToolListenerHelper;
2694
    
2695
    public void addChangeToolListener(ChangeListener listener) {
2696
        this.changeToolListenerHelper.addChangeListener(listener);
2697
    }
2698
    
2699
    public ChangeListener[] getChangeToolListeners() {
2700
        return this.changeToolListenerHelper.getChangeListeners();
2701
    }
2702

    
2703
    public void removeChangeToolListener(ChangeListener listener) {
2704
        this.changeToolListenerHelper.removeChangeListener(listener);
2705
    }
2706

    
2707
    public void removeAllChangeToolListener() {
2708
        this.changeToolListenerHelper.removeAllChangeListener();
2709
    }
2710

    
2711
    public boolean hasChangeToolListeners() {
2712
        return this.changeToolListenerHelper.hasChangeListeners();
2713
    }      
2714
}