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 @ 41971

History | View | Annotate | Download (87.2 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

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

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

    
261
    protected static final GeometryManager geomManager =
262
        GeometryLocator.getGeometryManager();
263
    private static final Logger LOG =
264
        LoggerFactory.getLogger(GeometryManager.class);
265

    
266
    /**
267
     * <p>
268
     * One of the possible status of <code>MapControl</code>. Determines that
269
     * all visible information has been drawn and its updated.
270
     * </p>
271
     */
272
    public static final int ACTUALIZADO = 0;
273

    
274
    /**
275
     * <p>
276
     * One of the possible status of <code>MapControl</code>. Determines that
277
     * not all visible information has been drawn or isn't updated.
278
     * </p>
279
     */
280
    public static final int DESACTUALIZADO = 1;
281

    
282
    /**
283
     * <p>
284
     * Determines if the drawer can update this <code>MapControl</code> instance
285
     * when the timer launches an event.
286
     * </p>
287
     */
288
    private static boolean drawAnimationEnabled = true;
289

    
290
    /**
291
     * <p>
292
     * Inner model with the layers, event support for drawing them, and the
293
     * <code>ViewPort</code> with information to adapt to the bounds available
294
     * in <i>image coordinates</i>.
295
     * </p>
296
     * 
297
     * @see #getMapContext()
298
     * @see #setMapContext(MapContext)
299
     */
300
    private MapContext mapContext = null;
301

    
302
    /**
303
     * <p>
304
     * All registered <code>Behavior</code> that can define a way to work with
305
     * this <code>MapControl</code>.
306
     * </p>
307
     * 
308
     * <p>
309
     * Only one of them can be active at a given moment.
310
     * </p>
311
     * 
312
     * @see #addBehavior(String, Behavior)
313
     * @see #addBehavior(String, Behavior[])
314
     * @see #getMapTool(String)
315
     * @see #getMapToolsKeySet()
316
     * @see #getNamesMapTools()
317
     */
318
    protected Map<String,Behavior> namesMapTools = new HashMap<String,Behavior>();
319

    
320
    /**
321
     * <p>
322
     * Active {@link Behavior Behavior} that will generate events according a
323
     * criterion, and then, with a {@link ToolListener ToolListener} associated,
324
     * will simulate to user that works with this component as a particular
325
     * tool.
326
     * </p>
327
     * 
328
     * @see #getCurrentMapTool()
329
     * @see #getCurrentTool()
330
     * @see #setTool(String)
331
     */
332
    protected Behavior currentMapTool = null;
333

    
334
    /**
335
     * <p>
336
     * Determines which's the current drawn status of this component:
337
     * <ul>
338
     * <li><b>OUTDATED</b>: all visible information has been drawn or isn't
339
     * updated.</li>
340
     * <li><b>UTDATED</b>: all visible information has been drawn and its
341
     * updated.</li>
342
     * <li><b>ONLY_GRAPHICS</b>: only the graphical layer must be drawn /
343
     * updated.</li>
344
     * </ul>
345
     * </p>
346
     * 
347
     * <p>
348
     * The <code>MapControl</code> drawing process will consider the value of
349
     * this parameter to decide which elements will be updated or drawn.
350
     * </p>
351
     */
352
    private int status = DESACTUALIZADO;
353

    
354
    /**
355
     * <p>
356
     * Image with a buffer to accelerate the draw the changes of the graphical
357
     * items in this component.
358
     * </p>
359
     * 
360
     * <p>
361
     * Firstly, information will be drawn in the buffer, and, when is outright
362
     * drawn, that information will be displayed. Meanwhile, the previous image
363
     * can be kept showed.
364
     * </p>
365
     * 
366
     * @see BufferedImage
367
     * 
368
     * @see #getImage()
369
     */
370
    private BufferedImage image = null;
371

    
372
    /**
373
     * <p>
374
     * Name of the tool used currently to interact with this component.
375
     * </p>
376
     * 
377
     * @see #getCurrentTool()
378
     * @see #setTool(String)
379
     */
380
    protected String currentTool;
381

    
382
    /**
383
     * <p>
384
     * Object to store the flag that notifies a drawing thread task and
385
     * <code>MapContext</code>'s layers, that must be canceled or can continue
386
     * with the process.
387
     * </p>
388
     * 
389
     * @see #cancelDrawing()
390
     */
391
    private CancelDraw canceldraw;
392

    
393
    // private boolean isCancelled = true;
394

    
395
    /**
396
     * <p>
397
     * Fires an action events after a specified delay.
398
     * </p>
399
     * 
400
     * <p>
401
     * <code>MapControl</code> will use the timer to update its visible
402
     * graphical information during a drawing process, or allowing to cancel
403
     * that process.
404
     * </p>
405
     * 
406
     * <p>
407
     * This is very useful to pretend faster interactivity to user when
408
     * <code>MapControl</code> has lots of layers, and / or layers with heavy
409
     * graphical elements, that need a long time to finish drawing all its data.
410
     * </p>
411
     */
412
    private Timer timer;
413

    
414
    /**
415
     * <p>
416
     * Reference to the {@link ViewPort ViewPort} of the {@link MapContext
417
     * MapContext} of this component.
418
     * </p>
419
     * 
420
     * <p>
421
     * After, the view port will change adapting itself according the current
422
     * projection and the extent.
423
     * </p>
424
     * 
425
     * @see #getViewPort()
426
     * 
427
     * @see ViewPort
428
     */
429
    protected ViewPort vp;
430

    
431
    /**
432
     * <p>
433
     * Manager of all <code>MapControl</code> painting requests.
434
     * </p>
435
     */
436
    private Drawer drawer;
437

    
438
    /**
439
     * <p>
440
     * Listener of all kind of mouse events produced in this component.
441
     * </p>
442
     * 
443
     * <p>
444
     * Delegates each mouse event to the current map tool.
445
     * </p>
446
     * 
447
     * @see #addBehavior(String, Behavior)
448
     * @see #addBehavior(String, Behavior[])
449
     * @see #getMapTool(String)
450
     * @see #getMapToolsKeySet()
451
     * @see #getNamesMapTools()
452
     * @see #setTool(String)
453
     */
454
    protected MapToolListener mapToolListener = new MapToolListener();
455

    
456
    /**
457
     * <p>
458
     * Listener of all events produced in a this component's
459
     * <code>MapContext</code> object during an atomic period of time.
460
     * </p>
461
     */
462
    private MapContextListener mapContextListener = new MapContextListener();
463

    
464
    /**
465
     * <p>
466
     * Group of <code>ExceptionListener</code> that, in whatever moment could be
467
     * notified a Throwable Java error or exception.
468
     * </p>
469
     * 
470
     * @see #addExceptionListener(ExceptionListener)
471
     * @see #removeExceptionListener(ExceptionListener)
472
     */
473
    private ExceptionHandlingSupport exceptionHandlingSupport =
474
        new ExceptionHandlingSupport();
475

    
476
    /**
477
     * <p>
478
     * Name of the previous tool used.
479
     * </p>
480
     */
481
    protected String prevTool;
482

    
483
    /**
484
     * <p>
485
     * Tool that will be used combined with the current tool of this
486
     * <code>MapControl</code>.
487
     * </p>
488
     */
489
    private Behavior combinedTool = null;
490

    
491
    /**
492
     * Optional grid that could be applied on the <code>MapControl</code>'s view
493
     * port.
494
     * 
495
     * @see #getGrid()
496
     * @see #setAdjustGrid(boolean)
497
     */
498
    private Grid cadgrid = new Grid();
499
    /**
500
     * Represents the cursor's point selected in <i>screen coordinates</i>.
501
     * 
502
     * @see ViewPort#fromMapPoint(Point2D)
503
     */
504
    protected Point2D adjustedPoint;
505
    /**
506
     * <p>
507
     * Determines if the position of the snap of the mouse's cursor on the
508
     * <code>MapControl</code> is within the area around a control point of a
509
     * geometry.
510
     * </p>
511
     * 
512
     * <p>
513
     * The area is calculated as a circle centered at the control point and with
514
     * radius the pixels tolerance defined in the preferences.
515
     * </p>
516
     */
517
    private boolean bForceCoord = false;
518

    
519
    /**
520
     * Kind of geometry drawn to identify the kind of control point selected by
521
     * the cursor's mouse.
522
     */
523
    private ISnapper usedSnap = null;
524

    
525
    /**
526
     * Determines if the snap tools are enabled or disabled.
527
     * 
528
     * @see #isRefentEnabled()
529
     * @see #setRefentEnabled(boolean)
530
     */
531
    private boolean bRefent = true;
532

    
533
    /**
534
     * Stores the 2D map coordinates of the last point added.
535
     */
536
    private double[] previousPoint = null;
537

    
538
    protected static MapControlManager mapControlManager =
539
        MapControlLocator.getMapControlManager();
540

    
541
    private static TreeMap selected = new TreeMap(new Comparator() {
542

    
543
        public int compare(Object o1, Object o2) {
544
            if (o1.getClass().equals(o2.getClass()))
545
                return 0;
546
            if (((ISnapper) o1).getPriority() > ((ISnapper) o2).getPriority())
547
                return 1;
548
            else
549
                return -1;
550
        }
551

    
552
    });
553

    
554
    /**
555
     * Represents the cursor's point selected in <i>map coordinates</i>.
556
     * 
557
     * @see MapControl#toMapPoint
558
     */
559
    protected Point2D mapAdjustedPoint;
560

    
561
    /**
562
     * Renderer used to draw the layers.
563
     */
564
    private MapControlDrawer mapControlDrawer = null;
565
        private Cursor transparentCursor;
566
        
567
        private boolean disposed = false;
568

    
569
    /**
570
     * <p>
571
     * Creates a new <code>MapControl</code> instance with the following
572
     * characteristics:
573
     * <ul>
574
     * <li><i>Name</i>: MapControl .</li>
575
     * <li>Disables the double buffer of <code>JComponent</code> .</li>
576
     * <li>Sets opaque <i>(see {@link JComponent#setOpaque(boolean)} )</i>.</li>
577
     * <li>Sets its status to <code>OUTDATED</code> .</li>
578
     * <li>Creates a new {@link CancelDraw CancelDraw} object to notify
579
     * <code>MapContext</code>'s layers if can continue processing the drawn or
580
     * must cancel it.</li>
581
     * <li>Creates a new {@link MapContext MapContext} with a new
582
     * {@link ViewPort ViewPort} in the default projection.</li>
583
     * <li>Creates a new {@link CommandListener CommandListener} for edition
584
     * operations.</li>
585
     * <li>Creates a new {@link MapToolListener MapToolListener}, and associates
586
     * it as a listener of whatever kind of mouse events produced in this
587
     * component.</li>
588
     * <li>Creates a new {@link Drawer2 Drawer2} for managing the painting
589
     * requests.</li>
590
     * <li>Creates a new timer that will invoke refresh this component
591
     * <code>drawFrameRate</code> per second, when is running a drawing process,
592
     * and its enabled <code>drawAnimationEnabled</code>.</li>
593
     * </ul>
594
     * </p>
595
     */
596
    public MapControl() {
597
        this(null);
598
    }
599
    
600
    public MapControl(MapContext theMapContext) {
601
        if( theMapContext == null ) {
602
            theMapContext = new MapContext(new ViewPort(MapContextLocator.getMapContextManager().getDefaultCRS()));
603
        }
604
        this.setName("MapControl");
605
        Toolkit toolkit = Toolkit.getDefaultToolkit();
606
        Image imageTransparentCursor = toolkit.createImage(new MemoryImageSource(16, 16, new int[16 * 16], 0,16));
607
        transparentCursor =
608
            toolkit.createCustomCursor(imageTransparentCursor, new Point(0, 0), "invisiblecursor");
609

    
610
        setDoubleBuffered(false);
611
        setOpaque(true);
612
        status = DESACTUALIZADO;
613

    
614
        // Clase usada para cancelar el dibujado
615
        canceldraw = new CancelDraw();
616

    
617
        vp = theMapContext.getViewPort();
618
        
619
        setMapContext(theMapContext);
620

    
621
        // eventos
622
        this.addComponentListener(this);
623
        this.addMouseListener(mapToolListener);
624
        this.addMouseMotionListener(mapToolListener);
625
        this.addMouseWheelListener(mapToolListener);
626

    
627
        this.drawer = new Drawer();
628
        // Timer para mostrar el redibujado mientras se dibuja
629
        timer =
630
            new Timer(1000 / MapContext.getDrawFrameRate(),
631
                new ActionListener() {
632

    
633
                    public void actionPerformed(ActionEvent e) {
634

    
635
                        if (drawAnimationEnabled) {
636
                            MapControl.this.repaint();
637
                        }
638
                    }
639
                });
640
        initializeGrid();
641
        
642
        if(ToolsLocator.getDisposableManager() != null) {
643
                        ToolsLocator.getDisposableManager().bind(this);
644
                } else {
645
                        LOG.warn("Can't retrieve the disposable manager,");
646
                }
647
    }
648

    
649
    /**
650
     * <p>
651
     * Sets a <code>MapContext</code> to this component.
652
     * </p>
653
     * 
654
     * <p>
655
     * The <code>MapContext</code> has the <i>model</i>, and most of the
656
     * <i>view</i>, and <i>control</i> logic of the layers of this component,
657
     * including a {@link ViewPort ViewPort} to adapt the information to the
658
     * projection, and to display it in the available area.
659
     * </p>
660
     * 
661
     * <p>
662
     * If <code>model</code> hadn't a <code>ViewPort</code>, assigns the current
663
     * one to it, otherwise, use its <code>ViewPort</code>.
664
     * </p>
665
     * 
666
     * <p>
667
     * After assigning the <code>MapContext</code> and <code>ViewPort</code>,
668
     * sets the same {@link MapContextListener MapContextListener} that was
669
     * using, and changes the <i>status</i> to <code>OUTDATED</code>.
670
     * </p>
671
     * 
672
     * @param model
673
     *            this component's <code>MapContext</code>, that includes the
674
     *            <code>ViewPort</code>.
675
     * 
676
     * @see MapContext
677
     * 
678
     * @see #getMapContext()
679
     */
680
    public void setMapContext(MapContext model) {
681
        if (mapContext != null) {
682
            mapContext.removeAtomicEventListener(mapContextListener);
683
            mapContext.dispose();
684
        }
685

    
686
        mapContext = model;
687

    
688
        if (mapContext.getViewPort() == null) {
689
            mapContext.setViewPort(vp);
690
        } else {
691
            vp = mapContext.getViewPort();
692
            cadgrid.setViewPort(vp);
693
        }
694

    
695
        mapContext.addAtomicEventListener(mapContextListener);
696

    
697
        status = DESACTUALIZADO;
698
    }
699

    
700
    /**
701
     * @return the mapControlDrawer
702
     */
703
    public MapControlDrawer getMapControlDrawer() {
704
        return mapControlDrawer;
705
    }
706

    
707
    /**
708
     * @param mapControlDrawer
709
     *            the mapControlDrawer to set
710
     */
711
    public void setMapControlDrawer(MapControlDrawer mapControlDrawer) {
712
        this.mapControlDrawer = mapControlDrawer;
713
        this.mapControlDrawer.setViewPort(vp);
714
    }
715

    
716
    /**
717
     * <p>
718
     * Gets this component's {@link MapContext MapContext} projection.
719
     * </p>
720
     * 
721
     * @return this component's {@link MapContext MapContext} projection
722
     * 
723
     * @see MapContext#getProjection()
724
     * @see MapControl#setProjection(IProjection)
725
     */
726
    public IProjection getProjection() {
727
        return getMapContext().getProjection();
728
    }
729

    
730
    /**
731
     * <p>
732
     * Sets the projection to this component's {@link MapContext MapContext}.
733
     * </p>
734
     * 
735
     * @param proj
736
     *            the kind of projection to this component's {@link MapContext
737
     *            MapContext}
738
     * 
739
     * @see MapContext#setProjection(IProjection)
740
     * @see MapControl#getProjection()
741
     */
742
    public void setProjection(IProjection proj) {
743
        getMapContext().setProjection(proj);
744
    }
745

    
746
    /**
747
     * <p>
748
     * Gets this component's <code>MapContext</code>, with the <i>model</i>, and
749
     * most of the <i>view</i>, and <i>control</i> logic of the layers of this
750
     * component, including a {@link ViewPort ViewPort} to adapt the information
751
     * to the projection, and display it in the available area.
752
     * </p>
753
     * 
754
     * @return this component's <code>MapContext</code>, that includes the
755
     *         <code>ViewPort</code> used to project the
756
     *         graphical information, and display it in the available area
757
     * 
758
     * @see MapContext
759
     * 
760
     * @see MapControl#setMapContext(MapContext)
761
     */
762
    public MapContext getMapContext() {
763
        return mapContext;
764
    }
765

    
766
    /**
767
     * <p>
768
     * Registers a new behavior to this component.
769
     * </p>
770
     * 
771
     * <p>
772
     * According the nature of the {@link Behavior Behavior}, different events
773
     * will be generated. Those events can be caught by a particular
774
     * {@link ToolListener ToolListener}, allowing user to interact with this
775
     * <code>MapControl</code> object as a <i>tool</i>.
776
     * </p>
777
     * 
778
     * @param name
779
     *            name to identify the behavior to add
780
     * @param tool
781
     *            the behavior to add
782
     * 
783
     * @see #addBehavior(String, Behavior[])
784
     * @see #getNamesMapTools()
785
     * @see #getMapToolsKeySet()
786
     * @see #hasTool(String)
787
     */
788
    public void addBehavior(String name, Behavior tool) {
789
        namesMapTools.put(name, tool);
790
        tool.setMapControl(this);
791
    }
792

    
793
    /**
794
     * <p>
795
     * Registers a new behavior to this component as a {@link CompoundBehavior
796
     * CompoundBehavior} made up of <code>tools</code>.
797
     * </p>
798
     * 
799
     * <p>
800
     * According the nature of the behaviors registered, different events will
801
     * be generated. Those events can be caught by a particular
802
     * {@link ToolListener ToolListener}, allowing user to interact with this
803
     * <code>MapControl</code> object as a <i>tool</i>.
804
     * </p>
805
     * 
806
     * @param name
807
     *            name to identify the compound behavior to add
808
     * @param tools
809
     *            the compound behavior to add
810
     * 
811
     * @see #addBehavior(String, Behavior)
812
     * @see #getNamesMapTools()
813
     * @see #getMapToolsKeySet()
814
     * @see #hasTool(String)
815
     */
816
    public void addBehavior(String name, Behavior[] tools) {
817
        CompoundBehavior tool = new CompoundBehavior(tools);
818
        addBehavior(name, tool);
819
    }
820

    
821
    /**
822
     * <p>
823
     * Gets the <code>Behavior</code> registered in this component, identified
824
     * by <code>name</code>.
825
     * </p>
826
     * 
827
     * @param name
828
     *            name of a registered behavior
829
     * 
830
     * @return tool the registered behavior in this component as
831
     *         <code>name</code>, or <code>null</code> if
832
     *         no one has that identifier
833
     * 
834
     * @see #addBehavior(String, Behavior)
835
     * @see #addBehavior(String, Behavior[])
836
     * @see #hasTool(String)
837
     */
838
    public Behavior getMapTool(String name) {
839
        return (Behavior) namesMapTools.get(name);
840
    }
841

    
842
    /**
843
     * <p>
844
     * Returns a set view of the keys that identified the tools registered.
845
     * </p>
846
     * 
847
     * @return a set view of the keys that identified the tools registered
848
     * 
849
     * @see HashMap#keySet()
850
     * 
851
     * @see #getNamesMapTools()
852
     * @see #addBehavior(String, Behavior)
853
     * @see #addBehavior(String, Behavior[])
854
     */
855
    public Set getMapToolsKeySet() {
856
        return namesMapTools.keySet();
857
    }
858

    
859
    /**
860
     * <p>
861
     * Returns <code>true</code> if this component contains a tool identified by
862
     * <code>toolName</code>.
863
     * </p>
864
     * 
865
     * @param toolName
866
     *            identifier of the tool
867
     * 
868
     * @return <code>true</code> if this component contains a tool identified by
869
     *         <code>toolName</code>; otherwise <code>false</code>
870
     * 
871
     * @see #addBehavior(String, Behavior)
872
     * @see #addBehavior(String, Behavior[])
873
     */
874
    public boolean hasTool(String toolName) {
875
        return namesMapTools.containsKey(toolName);
876
    }
877

    
878
    /**
879
     * <p>
880
     * Sets as current active <code>Behavior</code> associated to this
881
     * component, that one which is registered and identified by
882
     * <code>toolName</code>.
883
     * </p>
884
     * 
885
     * <p>
886
     * Changing the current active behavior for this <code>MapControl</code>,
887
     * implies also updating the previous <i>behavior</i> tool, and the current
888
     * cursor.
889
     * </p>
890
     * 
891
     * @param toolName
892
     *            name of a registered behavior
893
     * 
894
     * @see #getCurrentMapTool()
895
     * @see #getCurrentTool()
896
     */
897
    public void setTool(String toolName) {
898
        prevTool = getCurrentTool();
899
        Behavior mapTool = (Behavior) namesMapTools.get(toolName);
900
        currentMapTool = mapTool;
901
        currentTool = toolName;
902

    
903
        if (combinedTool != null) {
904
            if (mapTool instanceof CompoundBehavior) {
905
                ((CompoundBehavior) mapTool).addMapBehavior(combinedTool, true);
906
            } else {
907
                currentMapTool =
908
                    new CompoundBehavior(new Behavior[] { currentMapTool });
909
                ((CompoundBehavior) currentMapTool).addMapBehavior(
910
                    combinedTool, true);
911
            }
912
        }
913

    
914
        // this.setCursor(mapTool.getCursor());
915
    }
916

    
917
    /**
918
     * <p>
919
     * Gets as current active <code>Behavior</code> associated to this
920
     * component, that one which is registered and identified by
921
     * <code>toolName</code>.
922
     * </p>
923
     * 
924
     * <p>
925
     * Changing the current active behavior for this <code>MapControl</code>,
926
     * implies also updating the previous <i>behavior</i> tool, and the current
927
     * cursor.
928
     * </p>
929
     * 
930
     * @param toolName
931
     *            name of a registered behavior
932
     * 
933
     * @see #getCurrentTool()
934
     * @see #setTool(String)
935
     */
936
    public Behavior getCurrentMapTool() {
937
        return currentMapTool;
938
    }
939

    
940
    /**
941
     * <p>
942
     * Returns the name of the current selected tool on this MapControl
943
     * </p>
944
     * 
945
     * @return the name of the current's behavior tool associated to this
946
     *         component
947
     * 
948
     * @see #getCurrentMapTool()
949
     * @see #setTool(String)
950
     */
951
    public String getCurrentTool() {
952
        return currentTool;
953
    }
954

    
955
    /**
956
     * <p>
957
     * Determines that current drawing process of <code>MapControl</code>'s
958
     * <code>MapContext</code>'s data must be canceled.
959
     * </p>
960
     * 
961
     * <p>
962
     * It has no effects if now isn't drawing that graphical information.
963
     * </p>
964
     * 
965
     * <p>
966
     * At last resort, the particular implementation of each layer in this
967
     * <code>MapControl</code>'s <code>MapContrext</code> will be that one which
968
     * will draw the graphical information, and, if supports, which could cancel
969
     * its drawing subprocess.
970
     * </p>
971
     */
972
    public void cancelDrawing() {
973
        /*
974
         * if (drawer != null) {
975
         * if (!drawer.isAlive()) {
976
         * return;
977
         * }
978
         * }
979
         */
980
        canceldraw.setCanceled(true);
981

    
982
        /*
983
         * while (!isCancelled) {
984
         * if (!drawer.isAlive()) {
985
         * // Si hemos llegado aqu� con un thread vivo, seguramente
986
         * // no estamos actualizados.
987
         * 
988
         * break;
989
         * }
990
         * 
991
         * }
992
         * canceldraw.setCancel(false);
993
         * isCancelled = false;
994
         * drawerAlive = false;
995
         */
996
    }
997

    
998
    /**
999
     * <p>
1000
     * Creates a {@link BufferedImage BufferedImage} image if there was no
1001
     * buffered image, or if its viewport's image height or width is different
1002
     * from this component's size. Once has created a double-buffer, fills it
1003
     * with the vieport's background color, or with <i>white</i> if it had no
1004
     * background color.
1005
     * </p>
1006
     * 
1007
     * <p>
1008
     * If no double-buffered existed, creates a {@link BufferedImage
1009
     * BufferedImage} with the size of this component, and as an image with
1010
     * 8-bit RGBA color components packed into integer pixels. That image has a
1011
     * <code>DirectColorModel</code> with alpha. The color data in that image is
1012
     * considered not to be premultiplied with alpha.
1013
     * </p>
1014
     * 
1015
     * <p>
1016
     * Once has created and filled the new inner <code>MapControl</code>'s
1017
     * double-buffer, changes the status to <code>OUTDATED</code>.
1018
     * </p>
1019
     * 
1020
     * @return <code>true</code> if has created and filled a new double-buffer
1021
     *         for this <code>MapControl</code> instance; otherwise
1022
     *         <code>false</code>
1023
     */
1024
    private boolean adaptToImageSize() {
1025
        if ((image == null) || (vp.getImageWidth() != this.getWidth())
1026
            || (vp.getImageHeight() != this.getHeight())) {
1027
            image =
1028
                new BufferedImage(this.getWidth(), this.getHeight(),
1029
                    BufferedImage.TYPE_INT_ARGB);
1030
            // ESTILO MAC
1031
            // image = GraphicsEnvironment.getLocalGraphicsEnvironment()
1032
            // .getDefaultScreenDevice().getDefaultConfiguration()
1033
            // .createCompatibleImage(this.getWidth(), this.getHeight());
1034
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
1035
            getMapContext().getViewPort().refreshExtent();
1036

    
1037
            Graphics gTemp = image.createGraphics();
1038
            Color theBackColor = vp.getBackColor();
1039
            if (theBackColor == null) {
1040
                gTemp.setColor(Color.WHITE);
1041
            } else {
1042
                gTemp.setColor(theBackColor);
1043
            }
1044

    
1045
            gTemp.fillRect(0, 0, getWidth(), getHeight());
1046
            gTemp.dispose();
1047
            status = DESACTUALIZADO;
1048
            // g.drawImage(image,0,0,null);
1049
            return true;
1050
        }
1051
        return false;
1052
    }
1053

    
1054
    /**
1055
     * <p>
1056
     * Paints the graphical information of this component using a double buffer.
1057
     * </p>
1058
     * 
1059
     * <p>
1060
     * If the double buffer wasn't created, creates a new one.
1061
     * </p>
1062
     * 
1063
     * <p>
1064
     * Paints the component according the following algorithm: <br>
1065
     * &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
1066
     * &nbsp &nbsp If there is no <i>double buffer</i>:<br>
1067
     * &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the
1068
     * <code>MapControl</code> instance, delegates the drawing process to that
1069
     * behavior, calling:
1070
     * <code><i>behavior_instance</i>.paintComponent(g)</code> &nbsp .<br>
1071
     * &nbsp &nbsp &nbsp Else, repaints the current graphical information
1072
     * quickly calling: <code>g.drawImage(image,0,0,null)</code> &nbsp .<br>
1073
     * &nbsp Else, (<i>status</i> is <i>OUTDATED</i>, or <i>ONLY_GRAPHICS</i>):
1074
     * executes a quickly repaint of the previous information calling
1075
     * <code>g.drawImage(image,0,0,null)</code>, and creates a <i>painting
1076
     * request</i> to delegate the heavy drawing process to the {@link Drawer2
1077
     * Drawer2}'s worker thread, according the <i>SingleWorketThread</i>
1078
     * pattern, starting a timer to update (invoking <code>repaint()</code> that
1079
     * comprises invoke this method) the view every delay of 360 ms. during the
1080
     * the process drawing.
1081
     * </p>
1082
     * 
1083
     * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
1084
     * @see Drawer2
1085
     */
1086
    protected void paintComponent(Graphics g) {
1087
        adaptToImageSize();
1088

    
1089
        try {
1090
            mapControlDrawer.startDrawing(this);
1091
        } catch (InterruptedException e) {
1092
            LOG.info("Error locking the MapControlDrawer", e);
1093
        }
1094
        mapControlDrawer.setGraphics(g);
1095
        mapControlDrawer.stopDrawing(this);
1096
        mapControlDrawer.setViewPort(getMapContext().getViewPort());
1097

    
1098
        if (status == ACTUALIZADO) {
1099
            /*
1100
             * Si hay un behaviour y la imagen es distinta de null se delega el
1101
             * dibujado
1102
             * en dicho behaviour
1103
             */
1104
            if (image != null) {
1105
                if (currentMapTool != null) {
1106
                    currentMapTool.paintComponent(mapControlDrawer);
1107
                } else {
1108
                    mapControlDrawer.drawImage(image, 0, 0);
1109
                }
1110
            }
1111
                } else if ((status == DESACTUALIZADO)) {
1112

    
1113
                        mapControlDrawer.drawImage(image, 0, 0);
1114

    
1115
                        drawer.put(new PaintingRequest());
1116
                        timer.start();
1117
                }
1118
        cadgrid.drawGrid(mapControlDrawer);
1119
        drawCursor();
1120
    }
1121

    
1122
    private String getStatusLabel(int status ) {
1123
        switch(status) {
1124
            case ACTUALIZADO:
1125
                return "ACTUALIZADO";
1126
            case DESACTUALIZADO:
1127
                return "DESACTUALIZADO";
1128
            default:
1129
                return Integer.toString(status);
1130
        }
1131
    }
1132
    /**
1133
     * <p>
1134
     * Gets the {@link BufferedImage BufferedImage} used to accelerate the draw
1135
     * of new ''frames'' with changes, or new graphical items in this component.
1136
     * </p>
1137
     * 
1138
     * @return double buffered image used by this component to accelerate the
1139
     *         draw of its graphical information, or <code>null</code> if isn't
1140
     *         already created
1141
     * 
1142
     * @see BufferedImage
1143
     */
1144
    public BufferedImage getImage() {
1145
        return image;
1146
    }
1147

    
1148
    /**
1149
     * <p>
1150
     * Forces repaint all visible graphical information in this component.
1151
     * </p>
1152
     * 
1153
     * <p>
1154
     * If <code>doClear == true</code>, before repainting, clears the background
1155
     * color, with the inner viewport's background color.
1156
     * </p>
1157
     * 
1158
     * @param doClear
1159
     *            <code>true</code> if needs clearing the background color
1160
     *            before drawing the map
1161
     * 
1162
     * @see #cancelDrawing()
1163
     * @see FLayers#setDirty(boolean)
1164
     */
1165
    public void drawMap(boolean doClear) {
1166
        cancelDrawing();
1167
        //System.out.println("drawMap con doClear=" + doClear);
1168
        status = DESACTUALIZADO;
1169
        if (doClear) {
1170
            // image = null; // Se usa para el PAN
1171
            if (image != null) {
1172
                Graphics2D g = image.createGraphics();
1173
                Color theBackColor = vp.getBackColor();
1174
                if (theBackColor == null) {
1175
                    g.setColor(Color.WHITE);
1176
                } else {
1177
                    g.setColor(theBackColor);
1178
                }
1179
                g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight());
1180
                g.dispose();
1181
            }
1182
        }
1183
        repaint();
1184
    }
1185

    
1186
    /**
1187
     * <p>
1188
     * Cancels any current drawing process, changing the status to
1189
     * <code>OUTDATED</code>, and forcing repaint only the layers dirty.
1190
     * </p>
1191
     * 
1192
     * @see #cancelDrawing()
1193
     */
1194
    public void rePaintDirtyLayers() {
1195
        cancelDrawing();
1196
        status = DESACTUALIZADO;
1197
        repaint();
1198
    }
1199

    
1200
    /**
1201
     * @deprecated use {@link #drawMap(boolean)} instead, or even
1202
     * better {@link #getMapContext()}.invalidate().
1203
     */
1204
    public void drawGraphics() {
1205
        drawMap(false);
1206
    }
1207

    
1208
    /**
1209
     * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1210
     */
1211
    public void componentHidden(ComponentEvent e) {
1212
    }
1213

    
1214
    /**
1215
     * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1216
     */
1217
    public void componentMoved(ComponentEvent e) {
1218
    }
1219

    
1220
    /**
1221
     * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1222
     */
1223
    public void componentResized(ComponentEvent e) {
1224
        /*
1225
         * image = new BufferedImage(this.getWidth(), this.getHeight(),
1226
         * BufferedImage.TYPE_INT_ARGB);
1227
         * Graphics gTemp = image.createGraphics();
1228
         * gTemp.setColor(vp.getBackColor());
1229
         * gTemp.fillRect(0,0,getWidth(), getHeight());
1230
         * System.out.println("MapControl resized");
1231
         * // image = null;
1232
         * vp.setImageSize(new Dimension(getWidth(), getHeight()));
1233
         * getMapContext().getViewPort().setScale();
1234
         */
1235
        // drawMap(true);
1236
    }
1237

    
1238
    /**
1239
     * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1240
     */
1241
    public void componentShown(ComponentEvent e) {
1242
    }
1243

    
1244
    /**
1245
     * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
1246
     */
1247
    public void addExceptionListener(ExceptionListener o) {
1248
        exceptionHandlingSupport.addExceptionListener(o);
1249
    }
1250

    
1251
    /**
1252
     * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
1253
     */
1254
    public boolean removeExceptionListener(ExceptionListener o) {
1255
        return exceptionHandlingSupport.removeExceptionListener(o);
1256
    }
1257

    
1258
    /**
1259
     * @see ExceptionHandlingSupport#throwException(Throwable)
1260
     */
1261
    protected void throwException(Throwable t) {
1262
        exceptionHandlingSupport.throwException(t);
1263
    }
1264

    
1265
    /**
1266
     * <p>
1267
     * Represents each <code>MapControl</code>'s data painting request.
1268
     * </p>
1269
     * 
1270
     * <p>
1271
     * The request will be attended by a <code>Drawer2</code>, which will hold
1272
     * it since the <code>Drawer2</code>'s worker takes it, or arrives a new
1273
     * painting request, which will replace it.
1274
     * </p>
1275
     */
1276
    private class PaintingRequest {
1277

    
1278
        /**
1279
         * <p>
1280
         * Creates a new <code>PaintingRequest
1281
         * </p>
1282
         * instance.</p>
1283
         */
1284
        public PaintingRequest() {
1285
        }
1286

    
1287
        /**
1288
         * <p>
1289
         * <code>MapControl</code> paint process:
1290
         * </p>
1291
         * 
1292
         * <p>
1293
         * <ul>
1294
         * <li><i>1.- </i>Cancels all previous <code>MapControl</code>'s drawing
1295
         * processes.</li>
1296
         * <li><i>2.- </i>If <i>status</i> was OUTDATED:
1297
         * <ul>
1298
         * <li><i>2.1.- </i>Fills the background color with viewport's
1299
         * background color, or <i>white</i> if it was undefined.</li>
1300
         * <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>
1301
         * .</li>
1302
         * <li><i>2.3.- </i>If <code>canceldraw.isCanceled()</code>
1303
         * <ul>
1304
         * <li><i>2.3.1.- </i>Sets <i>status</i> to OUTDATED.</li>
1305
         * <li><i>2.3.2.- </i>Sets <i>dirty</i> all layers stored in
1306
         * <i>MapContext</i>.</li>
1307
         * </ul>
1308
         * </li>
1309
         * <li><i>2.4.- </i>Else, sets <i>status</i> to UPDATED.</li>
1310
         * </ul>
1311
         * </li>
1312
         * <li><i>3.- </i>Stops the <i>timer</i>.</li>
1313
         * <li><i>4.- </i>Repaints this component invoking:
1314
         * <code>repaint();</code></li>
1315
         * </ul>
1316
         * </p>
1317
         * 
1318
         * @see #cancelDrawing()
1319
         * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
1320
         * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable,
1321
         *      double)
1322
         * 
1323
         * @see ViewPort
1324
         */
1325
        public void paint() {
1326
            try {
1327
                canceldraw.setCanceled(false);
1328
                Graphics2D g = image.createGraphics();
1329

    
1330
                ViewPort viewPort = mapContext.getViewPort();
1331

    
1332
                if (status == DESACTUALIZADO) {
1333
                    Graphics2D gTemp = image.createGraphics();
1334
                    Color theBackColor = viewPort.getBackColor();
1335
                    if (theBackColor == null) {
1336
                        gTemp.setColor(Color.WHITE);
1337
                    } else {
1338
                        gTemp.setColor(theBackColor);
1339
                    }
1340
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort
1341
                        .getImageHeight());
1342
                    mapContext.draw(image, g, canceldraw, mapContext
1343
                        .getScaleView());
1344
                    if (!canceldraw.isCanceled()) {
1345
                        status = ACTUALIZADO;
1346
                    }
1347
                                }
1348

    
1349
                timer.stop();
1350
                repaint();
1351

    
1352
            } catch (Throwable e) {
1353
                timer.stop();
1354
                LOG.warn("Problems drawing mapcontext.",e);
1355
                throwException(e);
1356
            } 
1357
        }
1358
    }
1359

    
1360
    /**
1361
     * <p>
1362
     * An instance of <code>Drawer2</code> could manage all
1363
     * <code>MapControl</code> painting requests.
1364
     * </p>
1365
     * 
1366
     * <p>
1367
     * Based on the <i>WorkerThread</i> software pattern, creates a worker
1368
     * thread that will attend sequentially the current waiting painting
1369
     * request, after finishing the previous (that could be by a cancel action).
1370
     * </p>
1371
     * 
1372
     * <p>
1373
     * All new {@link PaintingRequest PaintingRequest} generated will be stored
1374
     * as <i>waiting requests</i> since the worker attends it.
1375
     * </p>
1376
     * 
1377
     * <p>
1378
     * If a worker finished and there was no <i>painting request</i>, the worker
1379
     * would be set to wait until any <i>painting request</i> would be put.
1380
     * </p>
1381
     * 
1382
     * @author fjp
1383
     */
1384
    public class Drawer {
1385

    
1386
        // Una mini cola de 2. No acumulamos peticiones de dibujado
1387
        // dibujamos solo lo �ltimo que nos han pedido.
1388

    
1389
        /**
1390
         * <p>
1391
         * Painting request that's been attended by the <code>Drawer2</code>'s
1392
         * worker.
1393
         * </p>
1394
         * 
1395
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1396
         * @see #take()
1397
         */
1398
        private PaintingRequest paintingRequest;
1399

    
1400
        /**
1401
         * <p>
1402
         * Painting request waiting to be attended by the <code>Drawer2</code>'s
1403
         * worker.
1404
         * </p>
1405
         * 
1406
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1407
         * @see #take()
1408
         */
1409
        private PaintingRequest waitingRequest;
1410

    
1411
        /**
1412
         * <p>
1413
         * Determines that the <code>Drawer2</code>'s worker is busy attending a
1414
         * painting request.
1415
         * </p>
1416
         * 
1417
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1418
         * @see #take()
1419
         */
1420
        private boolean waiting;
1421

    
1422
        /**
1423
         * <p>
1424
         * Notifies the <code>Drawer2</code>'s worker to finish or continue with
1425
         * its process.
1426
         * </p>
1427
         * 
1428
         * @see #setShutdown(boolean)
1429
         */
1430
        private boolean shutdown;
1431

    
1432
                private Thread worker;
1433

    
1434
        /**
1435
         * <p>
1436
         * Sets this <code>Drawer2</code>'s worker to finish or continue with
1437
         * its process.
1438
         * </p>
1439
         * 
1440
         * @param isShutdown
1441
         *            a boolean value
1442
         */
1443
        public void setShutdown(boolean isShutdown) {
1444
            shutdown = isShutdown;
1445
            if (shutdown) {
1446
                    worker.interrupt();
1447
            }
1448
        }
1449

    
1450
        /**
1451
         * <p>
1452
         * Creates a new drawer for managing all data painting requests in
1453
         * <code>MapControl</code>.
1454
         * </p>
1455
         * 
1456
         * <p>
1457
         * Includes the following steps:
1458
         * <ul>
1459
         * <li>By default, there is no <i>current painting request</i>.</li>
1460
         * <li>By default, there is no <i>waiting painting request</i>.</li>
1461
         * <li>By default, the worker thread is waiting no <i>painting
1462
         * request</i>.</li>
1463
         * <li>By default, the worker thread is running.</li>
1464
         * <li>Creates and starts a worker thread for attending the <i>painting
1465
         * requests</i>.</li>
1466
         * </ul>
1467
         * </p>
1468
         */
1469
        public Drawer() {
1470
            paintingRequest = null;
1471
            waitingRequest = null;
1472
            waiting = false;
1473
            shutdown = false;
1474
            worker = new Thread(new Worker(), "MapControl Drawer Worker");
1475
            worker.start();
1476
        }
1477

    
1478
        /**
1479
         * <p>
1480
         * Sets a <code>PaintingRequest</code> to be attended by the worker
1481
         * thread of this object. If this one was waiting, wakes up.
1482
         * </p>
1483
         * 
1484
         * <p>
1485
         * All waiting threads will be notified synchronized.
1486
         * </p>
1487
         * 
1488
         * @param newPaintRequest
1489
         * 
1490
         * @see #take()
1491
         */
1492
        public void put(PaintingRequest newPaintRequest) {
1493
            waitingRequest = newPaintRequest;
1494
            if (waiting) {
1495
                synchronized (this) {
1496
                    notifyAll();
1497
                }
1498
            }
1499
        }
1500

    
1501
        /**
1502
         * <p>
1503
         * Used by this object's worker, returns the current waiting drawing
1504
         * request, causing current thread to wait until another thread invokes
1505
         * {@link #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1506
         * #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)}, if there
1507
         * was no waiting request.
1508
         * </p>
1509
         * 
1510
         * <p>
1511
         * All threads will access synchronized to the waiting request.
1512
         * </p>
1513
         * 
1514
         * @return <code>PaintingRequest</code> that was waiting to be attended
1515
         * 
1516
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1517
         */
1518
        public PaintingRequest take() {
1519
            if (waitingRequest == null) {
1520
                synchronized (this) {
1521
                    waiting = true;
1522
                    try {
1523
                        wait();
1524
                    } catch (InterruptedException ie) {
1525
                        waiting = false;
1526
                    }
1527
                }
1528
            }
1529
            paintingRequest = waitingRequest;
1530
            waitingRequest = null;
1531
            return paintingRequest;
1532
        }
1533

    
1534
        /**
1535
         * <p>
1536
         * Thread for attending painting requests.
1537
         * </p>
1538
         * 
1539
         * <p>
1540
         * If there was no double buffer, sets the status to
1541
         * <code>OUTDATED</code> and finishes, otherwise takes the painting
1542
         * request (it's probably that would wait some time), cancel the
1543
         * previous drawing process, and starts processing the request.
1544
         * </p>
1545
         * 
1546
         * @see Thread
1547
         */
1548
        private class Worker implements Runnable {
1549

    
1550
            /*
1551
             * (non-Javadoc)
1552
             * 
1553
             * @see java.lang.Runnable#run()
1554
             */
1555
            public void run() {
1556
                while (!shutdown) {
1557
                    PaintingRequest p = take();
1558
                    // System.out.println("Pintando");
1559
                    if (image != null) {
1560
                        cancelDrawing();
1561
                        if (p != null) {
1562
                                p.paint();
1563
                        }
1564
                    } else {
1565
                        status = DESACTUALIZADO;
1566
                    }
1567
                }
1568
            }
1569
        }
1570
    }
1571

    
1572
    /**
1573
     * <p>
1574
     * An instance of <code>CancelDraw</code> will be shared by all this
1575
     * <code>MapControl</code>'s <code>MapContext</code> layers, allowing
1576
     * receive a notification that, when they're been drawn, to be cancelled.
1577
     * </p>
1578
     * 
1579
     * @see Cancellable
1580
     * 
1581
     * @author Fernando Gonz�lez Cort�s
1582
     */
1583
    public class CancelDraw implements Cancellable {
1584

    
1585
        /**
1586
         * <p>
1587
         * Determines if the drawing task must be canceled or not.
1588
         * </p>
1589
         * 
1590
         * @see #isCanceled()
1591
         * @see #setCanceled(boolean)
1592
         */
1593
        private boolean cancel = false;
1594

    
1595
        /**
1596
         * Creates a new <code>CancelDraw</code> object.
1597
         */
1598
        public CancelDraw() {
1599
        }
1600

    
1601
        /*
1602
         * (non-Javadoc)
1603
         * 
1604
         * @see com.iver.utiles.swing.threads.Cancellable#setCanceled(boolean)
1605
         */
1606
        public void setCanceled(boolean b) {
1607
            cancel = b;
1608
        }
1609

    
1610
        /*
1611
         * (non-Javadoc)
1612
         * 
1613
         * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
1614
         */
1615
        public boolean isCanceled() {
1616
            return cancel;
1617
        }
1618
    }
1619

    
1620
    /**
1621
     * <p>
1622
     * Listens all kind of mouse events produced in {@link MapControl
1623
     * MapControl}, and invokes its current map tool <i>(
1624
     * {@link MapControl#getCurrentMapTool() MapControl#getCurrentMapTool()}</i>
1625
     * to simulate a behavior.
1626
     * </p>
1627
     * 
1628
     * <p>
1629
     * Mouse wheel moved events produce a <i>zoom in</i> operation if wheel
1630
     * rotation is negative, or a <i>zoom out</i> if its positive. Both will be
1631
     * centered in the position of the mouse, but, meanwhile <i>zoom in</i>
1632
     * operation applies a factor of 0.9, <i>zoom out</i> operation applies a
1633
     * factor of 1.2
1634
     * </p>
1635
     * 
1636
     * <p>
1637
     * Mouse wheel moved events can be produced as much frequently, that between
1638
     * each one, the drawing process could hadn't finished. This is the reason
1639
     * that, in this situation, cancels always the previous drawing process
1640
     * before applying a <i>zoom</i> operation, and ignores all new mouse
1641
     * positions that are produced before 1 second.
1642
     * </p>
1643
     * 
1644
     * @author Fernando Gonz�lez Cort�s
1645
     */
1646
    public class MapToolListener implements MouseListener, MouseWheelListener,
1647
        MouseMotionListener {
1648

    
1649
        /**
1650
         * <p>
1651
         * Used to avoid mouse wheel move events closed.
1652
         * </p>
1653
         * 
1654
         * <p>
1655
         * If a mouse wheel move event is produced
1656
         */
1657
        long t1;
1658

    
1659
        /**
1660
         * <p>
1661
         * Position of the mouse, in map coordinates.
1662
         * </p>
1663
         * 
1664
         * <p>
1665
         * This point coordinates will be used as center of the <i>zoom</i>
1666
         * operation.
1667
         * </p>
1668
         */
1669
        Point2D pReal;
1670

    
1671
        /**
1672
         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1673
         * @see Behavior#mouseClicked(MouseEvent)
1674
         */
1675
        public void mouseClicked(MouseEvent e) {
1676
            try {
1677
                if (currentMapTool != null) {
1678
                    currentMapTool.mouseClicked(e);
1679
                }
1680
                Point2D p;
1681

    
1682
                if (mapAdjustedPoint != null) {
1683
                    p = mapAdjustedPoint;
1684
                } else {
1685
                    p = vp.toMapPoint(adjustedPoint);
1686
                }            
1687
                previousPoint = new double[] { p.getX(), p.getY() };                
1688
            } catch (BehaviorException t) {
1689
                throwException(t);
1690
            }
1691
        }
1692

    
1693
        /**
1694
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1695
         * @see Behavior#mouseEntered(MouseEvent)
1696
         */
1697
        public void mouseEntered(MouseEvent e) {
1698
            setToolMouse();
1699
            try {
1700
                if (currentMapTool != null) {
1701
                    currentMapTool.mouseEntered(e);
1702
                }
1703
            } catch (BehaviorException t) {
1704
                throwException(t);
1705
            }
1706
        }
1707

    
1708
        /**
1709
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1710
         * @see Behavior#mouseExited(MouseEvent)
1711
         */
1712
        public void mouseExited(MouseEvent e) {
1713
            try {
1714
                if (currentMapTool != null) {
1715
                    currentMapTool.mouseExited(e);
1716
                }
1717
            } catch (BehaviorException t) {
1718
                throwException(t);
1719
            }
1720
            // Remove the snapping image if exist
1721
            usedSnap = null;
1722
            repaint();
1723
        }
1724

    
1725
        /**
1726
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1727
         * @see Behavior#mousePressed(MouseEvent)
1728
         */
1729
        public void mousePressed(MouseEvent e) {
1730
            try {
1731
                if (currentMapTool != null) {
1732
                    currentMapTool.mousePressed(e);
1733
                }
1734
            } catch (BehaviorException t) {
1735
                throwException(t);
1736
            }
1737
        }
1738

    
1739
        /**
1740
         * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1741
         * @see Behavior#mouseReleased(MouseEvent)
1742
         */
1743
        public void mouseReleased(MouseEvent e) {
1744
            try {
1745
                if (currentMapTool != null) {
1746
                    currentMapTool.mouseReleased(e);
1747
                }
1748
            } catch (BehaviorException t) {
1749
                throwException(t);
1750
            }
1751
        }
1752

    
1753
        /**
1754
         * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
1755
         * @see Behavior#mouseWheelMoved(MouseWheelEvent)
1756
         */
1757
        public void mouseWheelMoved(MouseWheelEvent e) {
1758
            try {
1759
                if (currentMapTool == null) {
1760
                    return;
1761
                }
1762

    
1763
                currentMapTool.mouseWheelMoved(e);
1764

    
1765
                // Si el tool actual no ha consumido el evento
1766
                // entendemos que quiere el comportamiento por defecto.
1767
                if (!e.isConsumed()) {
1768
                    // Para usar el primer punto sobre el que queremos centrar
1769
                    // el mapa, dejamos pasar un segundo para considerar el
1770
                    // siguiente
1771
                    // punto como v�lido.
1772
                    if (t1 == 0) {
1773
                        t1 = System.currentTimeMillis();
1774
                        pReal = vp.toMapPoint(e.getPoint());
1775
                    } else {
1776
                        long t2 = System.currentTimeMillis();
1777
                        if ((t2 - t1) > 1000) {
1778
                            t1 = 0;
1779
                        }
1780
                    }
1781
                    cancelDrawing();
1782
                    ViewPort vp = getViewPort();
1783

    
1784
                    /*
1785
                     * Point2D pReal = new
1786
                     * Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1787
                     * vp.getAdjustedExtent().getCenterY());
1788
                     */
1789
                    int amount = e.getWheelRotation();
1790
                    double nuevoX;
1791
                    double nuevoY;
1792
                    double factor;
1793

    
1794
                    if (amount < 0) // nos acercamos
1795
                    {
1796
                        factor = 0.9;
1797
                    } else // nos alejamos
1798
                    {
1799
                        factor = 1.2;
1800
                    }
1801
                    if (vp.getExtent() != null) {
1802
                        nuevoX =
1803
                            pReal.getX()
1804
                                - ((vp.getExtent().getWidth() * factor) / 2.0);
1805
                        nuevoY =
1806
                            pReal.getY()
1807
                                - ((vp.getExtent().getHeight() * factor) / 2.0);
1808
                        double x = nuevoX;
1809
                        double y = nuevoY;
1810
                        double width = vp.getExtent().getWidth() * factor;
1811
                        double height = vp.getExtent().getHeight() * factor;
1812

    
1813
                        try {
1814
                            vp.setEnvelope(geomManager.createEnvelope(x, y, x
1815
                                + width, y + height, SUBTYPES.GEOM2D));
1816
                        } catch (CreateEnvelopeException e1) {
1817
                            LOG.info("Error creating the envelope", e);
1818
                        }
1819
                    }
1820

    
1821
                }
1822
            } catch (BehaviorException t) {
1823
                throwException(t);
1824
            }
1825
        }
1826

    
1827
        /**
1828
         * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1829
         * @see Behavior#mouseDragged(MouseEvent)
1830
         */
1831
        public void mouseDragged(MouseEvent e) {
1832
            calculateSnapPoint(e.getPoint());
1833
            try {
1834
                if (currentMapTool != null) {
1835
                    currentMapTool.mouseDragged(e);
1836
                }
1837
            } catch (BehaviorException t) {
1838
                throwException(t);
1839
            }
1840
            repaint();
1841
        }
1842

    
1843
        /**
1844
         * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
1845
         * @see Behavior#mouseMoved(MouseEvent)
1846
         */
1847
        public void mouseMoved(MouseEvent e) {
1848
            calculateSnapPoint(e.getPoint());
1849
            try {
1850
                if (currentMapTool != null) {
1851
                    currentMapTool.mouseMoved(e);
1852
                }
1853
            } catch (BehaviorException t) {
1854
                throwException(t);
1855
            }
1856
            repaint();
1857
        }
1858
    }
1859

    
1860
    /**
1861
     * <p<code>MapContextListener</code> listens all events produced in a
1862
     * <code>MapControl</code>'s <code>MapContext</code> object during an atomic
1863
     * period of time, and sets it to dirty, <i>executing
1864
     * <code>drawMap(false)</code>, if any of the
1865
     * following conditions is accomplished</i>:
1866
     * <ul>
1867
     * <li>Any of the <code>LayerEvent</code> in the <code>AtomicEvent</code>
1868
     * parameter notifies a <i>visibility change</i>.</li>
1869
     * <li>There is at least one <code>ColorEvent</code> in the
1870
     * <code>AtomicEvent</code> parameter.</li>
1871
     * <li>There is at least one <code>ExtentEvent</code> in the
1872
     * <code>AtomicEvent</code> parameter.</li>
1873
     * <li>Any of the <code>LayerCollectionEvent</code> in the
1874
     * <code>AtomicEvent</code> parameter notifies that a driver's layer has
1875
     * reloaded it successfully.</li>
1876
     * <li>There is at least one <code>LegendEvent</code> in the
1877
     * <code>AtomicEvent</code> parameter.</li>
1878
     * <li>There is at least one <code>SelectionEvent</code> in the
1879
     * <code>AtomicEvent</code> parameter.</li>
1880
     * </ul>
1881
     * </p>
1882
     * 
1883
     * @author Fernando Gonz�lez Cort�s
1884
     */
1885
    public class MapContextListener implements AtomicEventListener {
1886

    
1887
        /**
1888
         * @see org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener#atomicEvent(org.gvsig.fmap.mapcontext.events.AtomicEvent)
1889
         */
1890
        public void atomicEvent(final AtomicEvent e) {
1891
            if (!SwingUtilities.isEventDispatchThread()) {
1892
                SwingUtilities.invokeLater(new Runnable() {
1893

    
1894
                    public void run() {
1895
                        atomicEvent(e);
1896
                    }
1897
                });
1898
                return;
1899
            }
1900
            LayerEvent[] layerEvents = e.getLayerEvents();
1901

    
1902
            for (int i = 0; i < layerEvents.length; i++) {
1903
                if (layerEvents[i].getProperty().equals("visible")) {
1904
                    drawMap(false);
1905
                    return;
1906
                } else
1907
                    if (layerEvents[i].getEventType() == LayerEvent.EDITION_CHANGED) {
1908
                        drawMap(false);
1909
                        return;
1910
                    }
1911
            }
1912

    
1913
            if (e.getColorEvents().length > 0) {
1914
                drawMap(false);
1915
                return;
1916
            }
1917

    
1918
            if (e.getExtentEvents().length > 0) {
1919
                drawMap(false);
1920
                return;
1921
            }
1922

    
1923
            if (e.getProjectionEvents().length > 0) {
1924
                // redraw = true;
1925
            }
1926

    
1927
            LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1928
            if (aux.length > 0) {
1929
                for (int i = 0; i < aux.length; i++) {
1930
                    if (aux[i].getAffectedLayer().getFLayerStatus()
1931
                        .isDriverLoaded()) {
1932
                        drawMap(false);
1933
                        return;
1934
                    }
1935
                }
1936

    
1937
            }
1938

    
1939
            if (e.getLegendEvents().length > 0) {
1940
                drawMap(false);
1941
                return;
1942
            }
1943

    
1944
            if (e.getSelectionEvents().length > 0) {
1945
                drawMap(false);
1946
                return;
1947
            }
1948
        }
1949
    }
1950

    
1951
    /**
1952
     * <p>
1953
     * Gets the <code>ViewPort</code> of this component's {@link MapContext
1954
     * MapContext} .
1955
     * </p>
1956
     * 
1957
     * @see MapContext#getViewPort()
1958
     */
1959
    public ViewPort getViewPort() {
1960
        return vp;
1961
    }
1962

    
1963
    /**
1964
     * <p>
1965
     * Returns all registered <code>Behavior</code> that can define a way to
1966
     * work with this <code>MapControl</code>.
1967
     * </p>
1968
     * 
1969
     * @return registered <code>Behavior</code> to this <code>MapControl</code>
1970
     * 
1971
     * @see #addBehavior(String, Behavior)
1972
     * @see #addBehavior(String, Behavior[])
1973
     * @see #getMapToolsKeySet()
1974
     * @see #hasTool(String)
1975
     */
1976
    public HashMap getNamesMapTools() {
1977
        return (HashMap) namesMapTools;
1978
    }
1979

    
1980
    /*
1981
     * (non-Javadoc)
1982
     * 
1983
     * @see
1984
     * com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
1985
     */
1986
    public void commandRepaint() {
1987
        drawMap(false);
1988
    }
1989

    
1990
    /*
1991
     * (non-Javadoc)
1992
     * 
1993
     * @see
1994
     * com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
1995
     */
1996
    public void commandRefresh() {
1997
        // TODO Auto-generated method stub
1998
    }
1999

    
2000
    /**
2001
     * <p>
2002
     * Equivalent operation to <i>undo</i>.
2003
     * </p>
2004
     * 
2005
     * <p>
2006
     * Exchanges the previous tool with the current one.
2007
     * </p>
2008
     * 
2009
     * @see #addBehavior(String, Behavior)
2010
     * @see #addBehavior(String, Behavior[])
2011
     * @see #setTool(String)
2012
     */
2013
    public void setPrevTool() {
2014
        setTool(prevTool);
2015
    }
2016

    
2017
    /**
2018
     * <p>
2019
     * Executes a <i>zoom in</i> operation centered at the center of the extent.
2020
     * </p>
2021
     * 
2022
     * <p>
2023
     * This implementation is designed for being invoked outside a
2024
     * <code>Behavior</code>, for example by an action of pressing a button; and
2025
     * simulates that the event has been produced by releasing the <i>button
2026
     * 1</i> of the mouse using the registered <code>Behavior</code> in this
2027
     * <code>MapControl</code> object that's responsible for the <i>zoom in</i>
2028
     * operation.
2029
     * </p>
2030
     * 
2031
     * @see #zoomOut()
2032
     */
2033
    public void zoomIn() {
2034
        Behavior mapTool = (Behavior) namesMapTools.get("zoomIn");
2035
        ViewPort vp = getViewPort();
2036
        Envelope r = getViewPort().getAdjustedExtent();
2037
        Point2D pCenter = vp.fromMapPoint(r.getCenter(0), r.getCenter(1));
2038
        MouseEvent e =
2039
            new MouseEvent(this, MouseEvent.MOUSE_RELEASED,
2040
                MouseEvent.ACTION_EVENT_MASK, MouseEvent.BUTTON1, (int) pCenter
2041
                    .getX(), (int) pCenter.getY(), 1, true, MouseEvent.BUTTON1);
2042
        try {
2043
            mapTool.mousePressed(e);
2044
            mapTool.mouseReleased(e);
2045
        } catch (BehaviorException t) {
2046
            throwException(t);
2047
        }
2048
    }
2049

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

    
2084
    /**
2085
     * <p>
2086
     * Returns the listener used to catch all mouse events produced in this
2087
     * <code>MapControl</code> instance and that redirects the calls to the
2088
     * current map tool.
2089
     * </p>
2090
     * 
2091
     * @return the map tool listener used
2092
     */
2093
    public MapToolListener getMapToolListener() {
2094
        return mapToolListener;
2095
    }
2096

    
2097
    // mapTool can be null, for instance, in 3D's navigation tools
2098
    /**
2099
     * <p>
2100
     * Sets <code>mapTool</code> as this <code>MapControl</code>'s current map
2101
     * tool.
2102
     * 
2103
     * @param mapTool
2104
     *            a map tool, or <code>null</code> to disable the interaction
2105
     *            with the user
2106
     * 
2107
     * @see #getCurrentMapTool()
2108
     * @see #getCurrentTool()
2109
     * @see #setTool(String)
2110
     * @see #setPrevTool()
2111
     * @see #addBehavior(String, Behavior)
2112
     * @see #addBehavior(String, Behavior[])
2113
     */
2114
    public void setCurrentMapTool(Behavior mapTool) {
2115
        currentMapTool = mapTool;
2116
    }
2117

    
2118
    /**
2119
     * <p>
2120
     * Sets the delay to the timer that refreshes this <code>MapControl</code>
2121
     * instance.
2122
     * </p>
2123
     * 
2124
     * <p>
2125
     * <code>Delay (in ms) = 1000 / getDrawFrameRate()</code>
2126
     * </p>
2127
     * 
2128
     * @see #getDrawFrameRate()
2129
     * @see #setDrawFrameRate(int)
2130
     */
2131
    public void applyFrameRate() {
2132
        if (MapContext.getDrawFrameRate() > 0) {
2133
            timer.setDelay(1000 / MapContext.getDrawFrameRate());
2134
        }
2135
    }
2136

    
2137
    /**
2138
     * <p>
2139
     * Determines if its enabled the repaint that invokes the timer according to
2140
     * {@link #getDrawFrameRate() #getDrawFrameRate()}.
2141
     * </p>
2142
     * 
2143
     * @return <code>true</code> if its enabled; otherwise <code>false</code>
2144
     */
2145
    public static boolean isDrawAnimationEnabled() {
2146
        return drawAnimationEnabled;
2147
    }
2148

    
2149
    /**
2150
     * <p>
2151
     * Sets if its enabled the repaint that invokes the timer according to
2152
     * {@link #getDrawFrameRate() #getDrawFrameRate()}.
2153
     * </p>
2154
     * 
2155
     * @param drawAnimationEnabled
2156
     *            <code>true</code> to enable the mode; otherwise
2157
     *            <code>false</code>
2158
     */
2159
    public static void setDrawAnimationEnabled(boolean drawAnimationEnabled) {
2160
        MapControl.drawAnimationEnabled = drawAnimationEnabled;
2161
    }
2162

    
2163
    /**
2164
     * <p>
2165
     * Gets the shared object that determines if a drawing process must be
2166
     * cancelled or can continue.
2167
     * </p>
2168
     * 
2169
     * @return the shared object that determines if a drawing process must be
2170
     *         cancelled or can continue
2171
     */
2172
    public CancelDraw getCanceldraw() {
2173
        return canceldraw;
2174
    }
2175

    
2176
    /**
2177
     * <p>
2178
     * Gets the tool used in combination with the current tool of this
2179
     * <code>MapControl</code>.
2180
     * </p>
2181
     * 
2182
     * @return the tool used in combination with the <code>currentMapTool</code>
2183
     *         ; <code>null</code> if there is
2184
     *         no combined tool
2185
     */
2186
    public Behavior getCombinedTool() {
2187
        return combinedTool;
2188
    }
2189

    
2190
    /**
2191
     * <p>
2192
     * Sets a tool to be used in combination with the current tool of this
2193
     * <code>MapControl</code>.
2194
     * </p>
2195
     * 
2196
     * @param combinedTool
2197
     *            a tool to be used in combination with the current tool of
2198
     *            <code>MapControl</code>
2199
     */
2200
    public void setCombinedTool(Behavior combinedTool) {
2201
        this.combinedTool = combinedTool;
2202

    
2203
        if (currentMapTool == null) {
2204
            return;
2205
        }
2206

    
2207
        if (currentMapTool instanceof CompoundBehavior) {
2208
            ((CompoundBehavior) currentMapTool).addMapBehavior(combinedTool,
2209
                true);
2210
        } else {
2211
            currentMapTool =
2212
                new CompoundBehavior(new Behavior[] { currentMapTool });
2213
            ((CompoundBehavior) currentMapTool).addMapBehavior(combinedTool,
2214
                true);
2215
        }
2216

    
2217
    }
2218

    
2219
    /**
2220
     * <p>
2221
     * Adds a new tool as combined tool.
2222
     * </p>
2223
     * <p>
2224
     * The new tool will be stored with the previous combined tools, and will be
2225
     * combined with the current tool.
2226
     * </p>
2227
     * <p>
2228
     * If <code>tool</code> was already stored as a combined tool, doesn't adds
2229
     * it.
2230
     * </p>
2231
     * 
2232
     * @param tool
2233
     *            a new tool to be used combined with the current tool
2234
     */
2235
    public void addCombinedBehavior(Behavior tool) {
2236
        tool.setMapControl(this);
2237
        if (combinedTool == null) {
2238
            combinedTool = tool;
2239
        } else {
2240
            if (combinedTool instanceof CompoundBehavior) {
2241
                if (((CompoundBehavior) combinedTool).containsBehavior(tool)) {
2242
                    return;
2243
                }
2244

    
2245
                ((CompoundBehavior) combinedTool).addMapBehavior(tool, true);
2246
            } else {
2247
                if (combinedTool.equals(tool)) {
2248
                    return;
2249
                }
2250

    
2251
                combinedTool =
2252
                    new CompoundBehavior(new Behavior[] { combinedTool });
2253
                ((CompoundBehavior) combinedTool).addMapBehavior(tool, true);
2254
            }
2255
        }
2256

    
2257
        if (currentMapTool == null) {
2258
            return;
2259
        }
2260

    
2261
        if (currentMapTool instanceof CompoundBehavior) {
2262
            ((CompoundBehavior) currentMapTool).addMapBehavior(tool, true);
2263
        } else {
2264
            currentMapTool =
2265
                new CompoundBehavior(new Behavior[] { currentMapTool });
2266
            ((CompoundBehavior) currentMapTool).addMapBehavior(tool, true);
2267
        }
2268
    }
2269

    
2270
    /**
2271
     * <p>
2272
     * Removes the tool <code>tool</code> used in combination with the current
2273
     * tool of this <code>MapControl</code>.
2274
     * </p>
2275
     */
2276
    public void removeCombinedTool(Behavior tool) {
2277
        if ((currentMapTool != null)
2278
            && (currentMapTool instanceof CompoundBehavior)) {
2279
            ((CompoundBehavior) currentMapTool).removeMapBehavior(tool);
2280
        }
2281

    
2282
        if (combinedTool == null) {
2283
            return;
2284
        }
2285

    
2286
        if (combinedTool instanceof CompoundBehavior) {
2287
            ((CompoundBehavior) combinedTool).removeMapBehavior(tool);
2288
        } else {
2289
            combinedTool = null;
2290
        }
2291
    }
2292

    
2293
    /**
2294
     * <p>
2295
     * Updates the grid on the <code>ViewPort</code> of the associated
2296
     * <code>MapControl</code> object according the values in the
2297
     * {@link com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences
2298
     * com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences}.
2299
     * </p>
2300
     * 
2301
     * <p>
2302
     * The preferences are:
2303
     * <ul>
2304
     * <li>Show/hide the grid.</li>
2305
     * <li>Adjust or not the grid.</li>
2306
     * <li>Horizontal ( X ) line separation.</li>
2307
     * <li>Vertical ( Y ) line separation.</li>
2308
     * </ul>
2309
     * </p>
2310
     */
2311
    public void initializeGrid() {
2312
        Preferences prefs = mapControlManager.getEditionPreferences();
2313
        boolean showGrid =
2314
            prefs.getBoolean("grid.showgrid", cadgrid.isShowGrid());
2315
        boolean adjustGrid =
2316
            prefs.getBoolean("grid.adjustgrid", cadgrid.isAdjustGrid());
2317

    
2318
        double dx = prefs.getDouble("grid.distancex", cadgrid.getGridSizeX());
2319
        double dy = prefs.getDouble("grid.distancey", cadgrid.getGridSizeY());
2320

    
2321
        setGridVisibility(showGrid);
2322
        setAdjustGrid(adjustGrid);
2323
        cadgrid.setGridSizeX(dx);
2324
        cadgrid.setGridSizeY(dy);
2325
    }
2326

    
2327
    public void setAdjustGrid(boolean adjustGrid) {
2328
        cadgrid.setAdjustGrid(adjustGrid);
2329
    }
2330

    
2331
    public void setGridVisibility(boolean showGrid) {
2332
        cadgrid.setShowGrid(showGrid);
2333
        cadgrid.setViewPort(getViewPort());
2334
        this.repaint();
2335
    }
2336

    
2337
    /**
2338
     * Uses like a mouse pointer the image that provides the
2339
     * selected tool.
2340
     * 
2341
     */
2342

    
2343
    private Image lastImageCursor = null;
2344
    private Cursor lastCursor = null;
2345

    
2346
    private void setToolMouse() {
2347
        Image imageCursor = getCurrentMapTool().getImageCursor();
2348
        if (imageCursor != null && imageCursor == lastImageCursor && lastCursor != null && lastCursor != transparentCursor) {
2349
            setCursor(lastCursor);
2350
            return;
2351
        }
2352
        lastImageCursor = imageCursor;
2353
        Toolkit toolkit = Toolkit.getDefaultToolkit();
2354
        Cursor c = toolkit.createCustomCursor(imageCursor, new Point(16, 16), "img");
2355
        setCursor(c);
2356
        lastCursor = c;
2357
    }
2358

    
2359
    /**
2360
     * Makes the mouse pointer transparent.
2361
     */
2362
    private void setTransparentMouse() {
2363
        setCursor(transparentCursor);
2364
        lastCursor = transparentCursor;
2365
    }
2366

    
2367
    /**
2368
     * <p>
2369
     * Draws a 31x31 pixels cross round the mouse's cursor with an small
2370
     * geometry centered:
2371
     * <ul>
2372
     * <li><i>an square centered</i>: if isn't over a <i>control point</i>.
2373
     * <li><i>an small geometry centered according to the kind of control
2374
     * point</i>: if it's over a control point. In this case, the small geometry
2375
     * is drawn by a {@link ISnapper ISnapper} type object.<br>
2376
     * On the other hand, a light-yellowed background tool tip text with the
2377
     * type of <i>control point</i> will be displayed.</li>
2378
     * </p>
2379
     * 
2380
     * @param g
2381
     *            <code>MapControl</code>'s graphics where the data will be
2382
     *            drawn
2383
     */
2384
    private void drawCursor() {
2385
        if (adjustedPoint == null) {
2386
            return;
2387
        }
2388

    
2389
        if (usedSnap != null) {
2390
            usedSnap.draw(mapControlDrawer, adjustedPoint);
2391
            setTransparentMouse();
2392
        } else {
2393
            setToolMouse();
2394
        }
2395
    }
2396

    
2397
    /**
2398
     * <p>
2399
     * Adjusts the <code>point</code> to the grid if its enabled, and sets
2400
     * <code>mapHandlerAdjustedPoint</code> with that new value.
2401
     * </p>
2402
     * 
2403
     * <p>
2404
     * The value returned is the distance between those points: the original and
2405
     * the adjusted one.
2406
     * </p>
2407
     * 
2408
     * @param point
2409
     *            point to adjust
2410
     * @param mapHandlerAdjustedPoint
2411
     *            <code>point</code> adjusted
2412
     * 
2413
     * @return distance from <code>point</code> to the adjusted one. If there is
2414
     *         no
2415
     *         adjustment, returns <code>Double.MAX_VALUE</code>.
2416
     */
2417

    
2418
    private double adjustToHandler(Point2D point,
2419
        Point2D mapHandlerAdjustedPoint) {
2420

    
2421
        if (!isRefentEnabled())
2422
            return Double.MAX_VALUE;
2423

    
2424
        List layersToSnap = getMapContext().getLayersToSnap();
2425

    
2426
        double mapTolerance =
2427
            vp.toMapDistance(mapControlManager.getTolerance());
2428
        double minDist = mapTolerance;
2429
        double middleTol = mapTolerance * 0.5;
2430
        Point2D mapPoint = point;
2431
        Envelope r = null;
2432
        try {
2433
            r =
2434
                geomManager.createEnvelope(mapPoint.getX() - middleTol,
2435
                    mapPoint.getY() - middleTol, mapPoint.getX() + middleTol,
2436
                    mapPoint.getY() + middleTol, SUBTYPES.GEOM2D);
2437
        } catch (Exception e1) {
2438
            LOG.info("Error creating the envelope", e1);
2439
            return Double.MAX_VALUE;
2440
        }
2441

    
2442
        usedSnap = null;
2443
        Point2D lastPoint = null;
2444
        if (previousPoint != null) {
2445
            lastPoint = new Point2D.Double(previousPoint[0], previousPoint[1]);
2446
        }
2447
        for (int j = 0; j < layersToSnap.size(); j++) {
2448
            FLyrVect lyrVect = (FLyrVect) layersToSnap.get(j);
2449
            SpatialCache cache = lyrVect.getSpatialCache();
2450
            if (lyrVect.isVisible()) {
2451
                // La lista de snappers est� siempre ordenada por prioridad. Los
2452
                // de mayor
2453
                // prioridad est�n primero.
2454
                List geoms = cache.query(r);
2455
                
2456
                for (int i = 0; i < mapControlManager.getSnapperCount(); i++)
2457
                {
2458
                    ISnapper theSnapper = mapControlManager.getSnapperAt(i);
2459
                    if (theSnapper instanceof ISnapperGeometriesVectorial)
2460
                    {
2461
                        ((ISnapperGeometriesVectorial)theSnapper).setGeometries(geoms);                        
2462
                    }
2463
                } 
2464
                
2465
                for (int n = 0; n < geoms.size(); n++) {
2466
                    Geometry geom = (Geometry) geoms.get(n);
2467
                    for (int i = 0; i < mapControlManager.getSnapperCount(); i++) {
2468
                        ISnapper theSnapper = mapControlManager.getSnapperAt(i);
2469
                        if (!theSnapper.isEnabled())
2470
                            continue;
2471

    
2472
                        if (usedSnap != null) {
2473
                            // Si ya tenemos un snap y es de alta prioridad,
2474
                            // cogemos ese. (A no ser que en otra capa
2475
                            // encontremos un snapper mejor)
2476
                            if (theSnapper.getPriority() > usedSnap
2477
                                .getPriority())
2478
                                break;
2479
                        }
2480
                        // SnappingVisitor snapVisitor = null;
2481
                        Point2D theSnappedPoint = null;
2482
                        if (theSnapper instanceof ISnapperVectorial) {
2483
                            theSnappedPoint =
2484
                                ((ISnapperVectorial) theSnapper).getSnapPoint(
2485
                                    point, geom, mapTolerance, lastPoint);
2486
                        }
2487
                        if (theSnapper instanceof ISnapperRaster) {
2488
                            ISnapperRaster snapRaster =
2489
                                (ISnapperRaster) theSnapper;
2490
                            theSnappedPoint =
2491
                                snapRaster.getSnapPoint(this, point,
2492
                                    mapTolerance, lastPoint);
2493
                        }
2494

    
2495
                        if (theSnappedPoint != null) {
2496
                            double distAux = theSnappedPoint.distance(point);
2497
                            if (minDist > distAux) {
2498
                                minDist = distAux;
2499
                                usedSnap = theSnapper;
2500
                                mapHandlerAdjustedPoint
2501
                                    .setLocation(theSnappedPoint);
2502
                            }
2503
                        }
2504
                    }
2505
                } // for n
2506
            } // visible
2507
        }
2508
        if (usedSnap != null)
2509
            return minDist;
2510
        return Double.MAX_VALUE;
2511

    
2512
    }
2513

    
2514
    /**
2515
     * Determines if snap tools are enabled or disabled.
2516
     * 
2517
     * @return <code>true</code> to enable the snap tools; <code>false</code> to
2518
     *         disable them
2519
     * 
2520
     * @see #setRefentEnabled(boolean)
2521
     */
2522
    public boolean isRefentEnabled() {
2523
        return bRefent;
2524
    }
2525

    
2526
    /**
2527
     * <p>
2528
     * Tries to find the nearest geometry or grid control point by the position
2529
     * of the current snap tool.
2530
     * </p>
2531
     * 
2532
     * <p>
2533
     * Prioritizes the grid control points than the geometries ones.
2534
     * </p>
2535
     * 
2536
     * <p>
2537
     * If finds any near, stores the <i>map</i> and <i>pixel</i> coordinates for
2538
     * the snap, and enables the <code>bForceCoord</code> attribute for the next
2539
     * draw of the mouse's cursor.
2540
     * </p>
2541
     * 
2542
     * @param point
2543
     *            current mouse 2D position
2544
     */
2545
    public void calculateSnapPoint(Point point) {
2546
        // Se comprueba el ajuste a rejilla
2547

    
2548
        Point2D gridAdjustedPoint = vp.toMapPoint(point);
2549
        double minDistance = Double.MAX_VALUE;
2550

    
2551
        minDistance = cadgrid.adjustToGrid(gridAdjustedPoint);
2552
        if (minDistance < Double.MAX_VALUE) {
2553
            adjustedPoint = vp.fromMapPoint(gridAdjustedPoint);
2554
            mapAdjustedPoint = gridAdjustedPoint;
2555
        } else {
2556
            mapAdjustedPoint = null;
2557
        }
2558

    
2559
        Point2D handlerAdjustedPoint = null;
2560

    
2561
        // Se comprueba el ajuste a los handlers
2562
        if (mapAdjustedPoint != null) {
2563
            handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
2564
        } else {
2565
            handlerAdjustedPoint = vp.toMapPoint(point);
2566
        }
2567

    
2568
        Point2D mapPoint = new Point2D.Double();
2569
        double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
2570

    
2571
        if (distance < minDistance) {
2572
            bForceCoord = true;
2573
            adjustedPoint = vp.fromMapPoint(mapPoint);
2574
            mapAdjustedPoint = mapPoint;
2575
            minDistance = distance;
2576
        }
2577

    
2578
        // Si no hay ajuste
2579
        if (minDistance == Double.MAX_VALUE) {
2580
            adjustedPoint = point;
2581
            mapAdjustedPoint = null;
2582
        }
2583
    }
2584

    
2585
    /**
2586
     * Sets the snap tools enabled or disabled.
2587
     * 
2588
     * @param activated
2589
     *            <code>true</code> to enable the snap tools; <code>false</code>
2590
     *            to disable them
2591
     * 
2592
     * @see #isRefentEnabled()
2593
     */
2594
    public void setRefentEnabled(boolean activated) {
2595
        bRefent = activated;
2596
    }
2597

    
2598
    public Grid getGrid() {
2599
        return cadgrid;
2600
    }
2601

    
2602
    public void update(Observable observable, Object notification) {
2603
        DataStoreNotification ddsn = (DataStoreNotification) notification;
2604
        String type = ddsn.getType();
2605
        if (type.equals(FeatureStoreNotification.AFTER_UNDO)
2606
            || type.equals(FeatureStoreNotification.AFTER_REDO)) {
2607
            repaint();
2608
        }
2609
    }
2610

    
2611
    /**
2612
     * @return the adjustedPoint
2613
     */
2614
    public Point2D getAdjustedPoint() {
2615
        return adjustedPoint;
2616
    }
2617

    
2618
    /**
2619
     * @return the mapAdjustedPoint
2620
     */
2621
    public Point2D getMapAdjustedPoint() {
2622
        return mapAdjustedPoint;
2623
    }
2624

    
2625
    /**
2626
     * Gets the selected point. If the snapping is enabled
2627
     * it returns the selected point.
2628
     * 
2629
     * @return
2630
     *         The selected point
2631
     */
2632
    public Point2D getPoint() {
2633
        if (mapAdjustedPoint != null) {
2634
            return mapAdjustedPoint;
2635
        } else {
2636
            return getViewPort().toMapPoint(adjustedPoint);
2637
        }
2638
    }
2639

    
2640
        public synchronized void dispose() {
2641
                // Check if we have already been disposed, and don't do it again
2642
                if (!disposed && ToolsLocator.getDisposableManager().release(this)) {
2643
                        drawer.setShutdown(true);
2644
                        disposed = true;
2645
                }
2646
        }
2647
}