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

History | View | Annotate | Download (86.8 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(new MapContext(new ViewPort(MapContextLocator.getMapContextManager().getDefaultCRS())));
598
    }
599
    
600
    public MapControl(MapContext theMapContext) {
601
        this.setName("MapControl");
602
        Toolkit toolkit = Toolkit.getDefaultToolkit();
603
        Image imageTransparentCursor = toolkit.createImage(new MemoryImageSource(16, 16, new int[16 * 16], 0,16));
604
        transparentCursor =
605
            toolkit.createCustomCursor(imageTransparentCursor, new Point(0, 0), "invisiblecursor");
606

    
607
        setDoubleBuffered(false);
608
        setOpaque(true);
609
        status = DESACTUALIZADO;
610

    
611
        // Clase usada para cancelar el dibujado
612
        canceldraw = new CancelDraw();
613

    
614
        vp = theMapContext.getViewPort();
615
        
616
        setMapContext(theMapContext);
617

    
618
        // eventos
619
        this.addComponentListener(this);
620
        this.addMouseListener(mapToolListener);
621
        this.addMouseMotionListener(mapToolListener);
622
        this.addMouseWheelListener(mapToolListener);
623

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

    
630
                    public void actionPerformed(ActionEvent e) {
631

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

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

    
683
        mapContext = model;
684

    
685
        if (mapContext.getViewPort() == null) {
686
            mapContext.setViewPort(vp);
687
        } else {
688
            vp = mapContext.getViewPort();
689
            cadgrid.setViewPort(vp);
690
        }
691

    
692
        mapContext.addAtomicEventListener(mapContextListener);
693

    
694
        status = DESACTUALIZADO;
695
    }
696

    
697
    /**
698
     * @return the mapControlDrawer
699
     */
700
    public MapControlDrawer getMapControlDrawer() {
701
        return mapControlDrawer;
702
    }
703

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

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

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

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

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

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

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

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

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

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

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

    
911
        // this.setCursor(mapTool.getCursor());
912
    }
913

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

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

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

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

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

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

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

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

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

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

    
1110
                        mapControlDrawer.drawImage(image, 0, 0);
1111

    
1112
                        drawer.put(new PaintingRequest());
1113
                        timer.start();
1114
                }
1115
        cadgrid.drawGrid(mapControlDrawer);
1116
        drawCursor();
1117
    }
1118

    
1119
    /**
1120
     * <p>
1121
     * Gets the {@link BufferedImage BufferedImage} used to accelerate the draw
1122
     * of new ''frames'' with changes, or new graphical items in this component.
1123
     * </p>
1124
     * 
1125
     * @return double buffered image used by this component to accelerate the
1126
     *         draw of its graphical information, or <code>null</code> if isn't
1127
     *         already created
1128
     * 
1129
     * @see BufferedImage
1130
     */
1131
    public BufferedImage getImage() {
1132
        return image;
1133
    }
1134

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

    
1173
    /**
1174
     * <p>
1175
     * Cancels any current drawing process, changing the status to
1176
     * <code>OUTDATED</code>, and forcing repaint only the layers dirty.
1177
     * </p>
1178
     * 
1179
     * @see #cancelDrawing()
1180
     */
1181
    public void rePaintDirtyLayers() {
1182
        cancelDrawing();
1183
        status = DESACTUALIZADO;
1184
        repaint();
1185
    }
1186

    
1187
    /**
1188
     * @deprecated use {@link #drawMap(boolean)} instead, or even
1189
     * better {@link #getMapContext()}.invalidate().
1190
     */
1191
    public void drawGraphics() {
1192
        drawMap(false);
1193
    }
1194

    
1195
    /**
1196
     * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
1197
     */
1198
    public void componentHidden(ComponentEvent e) {
1199
    }
1200

    
1201
    /**
1202
     * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1203
     */
1204
    public void componentMoved(ComponentEvent e) {
1205
    }
1206

    
1207
    /**
1208
     * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1209
     */
1210
    public void componentResized(ComponentEvent e) {
1211
        /*
1212
         * image = new BufferedImage(this.getWidth(), this.getHeight(),
1213
         * BufferedImage.TYPE_INT_ARGB);
1214
         * Graphics gTemp = image.createGraphics();
1215
         * gTemp.setColor(vp.getBackColor());
1216
         * gTemp.fillRect(0,0,getWidth(), getHeight());
1217
         * System.out.println("MapControl resized");
1218
         * // image = null;
1219
         * vp.setImageSize(new Dimension(getWidth(), getHeight()));
1220
         * getMapContext().getViewPort().setScale();
1221
         */
1222
        // drawMap(true);
1223
    }
1224

    
1225
    /**
1226
     * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1227
     */
1228
    public void componentShown(ComponentEvent e) {
1229
    }
1230

    
1231
    /**
1232
     * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
1233
     */
1234
    public void addExceptionListener(ExceptionListener o) {
1235
        exceptionHandlingSupport.addExceptionListener(o);
1236
    }
1237

    
1238
    /**
1239
     * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
1240
     */
1241
    public boolean removeExceptionListener(ExceptionListener o) {
1242
        return exceptionHandlingSupport.removeExceptionListener(o);
1243
    }
1244

    
1245
    /**
1246
     * @see ExceptionHandlingSupport#throwException(Throwable)
1247
     */
1248
    protected void throwException(Throwable t) {
1249
        exceptionHandlingSupport.throwException(t);
1250
    }
1251

    
1252
    /**
1253
     * <p>
1254
     * Represents each <code>MapControl</code>'s data painting request.
1255
     * </p>
1256
     * 
1257
     * <p>
1258
     * The request will be attended by a <code>Drawer2</code>, which will hold
1259
     * it since the <code>Drawer2</code>'s worker takes it, or arrives a new
1260
     * painting request, which will replace it.
1261
     * </p>
1262
     */
1263
    private class PaintingRequest {
1264

    
1265
        /**
1266
         * <p>
1267
         * Creates a new <code>PaintingRequest
1268
         * </p>
1269
         * instance.</p>
1270
         */
1271
        public PaintingRequest() {
1272
        }
1273

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

    
1317
                ViewPort viewPort = mapContext.getViewPort();
1318

    
1319
                if (status == DESACTUALIZADO) {
1320
                    Graphics2D gTemp = image.createGraphics();
1321
                    Color theBackColor = viewPort.getBackColor();
1322
                    if (theBackColor == null) {
1323
                        gTemp.setColor(Color.WHITE);
1324
                    } else {
1325
                        gTemp.setColor(theBackColor);
1326
                    }
1327
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort
1328
                        .getImageHeight());
1329
                    mapContext.draw(image, g, canceldraw, mapContext
1330
                        .getScaleView());
1331
                    if (!canceldraw.isCanceled()) {
1332
                        status = ACTUALIZADO;
1333
                    }
1334
                                }
1335

    
1336
                timer.stop();
1337
                repaint();
1338

    
1339
            } catch (Throwable e) {
1340
                timer.stop();
1341
                e.printStackTrace();
1342
                throwException(e);
1343
            } 
1344
        }
1345
    }
1346

    
1347
    /**
1348
     * <p>
1349
     * An instance of <code>Drawer2</code> could manage all
1350
     * <code>MapControl</code> painting requests.
1351
     * </p>
1352
     * 
1353
     * <p>
1354
     * Based on the <i>WorkerThread</i> software pattern, creates a worker
1355
     * thread that will attend sequentially the current waiting painting
1356
     * request, after finishing the previous (that could be by a cancel action).
1357
     * </p>
1358
     * 
1359
     * <p>
1360
     * All new {@link PaintingRequest PaintingRequest} generated will be stored
1361
     * as <i>waiting requests</i> since the worker attends it.
1362
     * </p>
1363
     * 
1364
     * <p>
1365
     * If a worker finished and there was no <i>painting request</i>, the worker
1366
     * would be set to wait until any <i>painting request</i> would be put.
1367
     * </p>
1368
     * 
1369
     * @author fjp
1370
     */
1371
    public class Drawer {
1372

    
1373
        // Una mini cola de 2. No acumulamos peticiones de dibujado
1374
        // dibujamos solo lo �ltimo que nos han pedido.
1375

    
1376
        /**
1377
         * <p>
1378
         * Painting request that's been attended by the <code>Drawer2</code>'s
1379
         * worker.
1380
         * </p>
1381
         * 
1382
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1383
         * @see #take()
1384
         */
1385
        private PaintingRequest paintingRequest;
1386

    
1387
        /**
1388
         * <p>
1389
         * Painting request waiting to be attended by the <code>Drawer2</code>'s
1390
         * worker.
1391
         * </p>
1392
         * 
1393
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1394
         * @see #take()
1395
         */
1396
        private PaintingRequest waitingRequest;
1397

    
1398
        /**
1399
         * <p>
1400
         * Determines that the <code>Drawer2</code>'s worker is busy attending a
1401
         * painting request.
1402
         * </p>
1403
         * 
1404
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1405
         * @see #take()
1406
         */
1407
        private boolean waiting;
1408

    
1409
        /**
1410
         * <p>
1411
         * Notifies the <code>Drawer2</code>'s worker to finish or continue with
1412
         * its process.
1413
         * </p>
1414
         * 
1415
         * @see #setShutdown(boolean)
1416
         */
1417
        private boolean shutdown;
1418

    
1419
                private Thread worker;
1420

    
1421
        /**
1422
         * <p>
1423
         * Sets this <code>Drawer2</code>'s worker to finish or continue with
1424
         * its process.
1425
         * </p>
1426
         * 
1427
         * @param isShutdown
1428
         *            a boolean value
1429
         */
1430
        public void setShutdown(boolean isShutdown) {
1431
            shutdown = isShutdown;
1432
            if (shutdown) {
1433
                    worker.interrupt();
1434
            }
1435
        }
1436

    
1437
        /**
1438
         * <p>
1439
         * Creates a new drawer for managing all data painting requests in
1440
         * <code>MapControl</code>.
1441
         * </p>
1442
         * 
1443
         * <p>
1444
         * Includes the following steps:
1445
         * <ul>
1446
         * <li>By default, there is no <i>current painting request</i>.</li>
1447
         * <li>By default, there is no <i>waiting painting request</i>.</li>
1448
         * <li>By default, the worker thread is waiting no <i>painting
1449
         * request</i>.</li>
1450
         * <li>By default, the worker thread is running.</li>
1451
         * <li>Creates and starts a worker thread for attending the <i>painting
1452
         * requests</i>.</li>
1453
         * </ul>
1454
         * </p>
1455
         */
1456
        public Drawer() {
1457
            paintingRequest = null;
1458
            waitingRequest = null;
1459
            waiting = false;
1460
            shutdown = false;
1461
            worker = new Thread(new Worker(), "MapControl Drawer Worker");
1462
            worker.start();
1463
        }
1464

    
1465
        /**
1466
         * <p>
1467
         * Sets a <code>PaintingRequest</code> to be attended by the worker
1468
         * thread of this object. If this one was waiting, wakes up.
1469
         * </p>
1470
         * 
1471
         * <p>
1472
         * All waiting threads will be notified synchronized.
1473
         * </p>
1474
         * 
1475
         * @param newPaintRequest
1476
         * 
1477
         * @see #take()
1478
         */
1479
        public void put(PaintingRequest newPaintRequest) {
1480
            waitingRequest = newPaintRequest;
1481
            if (waiting) {
1482
                synchronized (this) {
1483
                    notifyAll();
1484
                }
1485
            }
1486
        }
1487

    
1488
        /**
1489
         * <p>
1490
         * Used by this object's worker, returns the current waiting drawing
1491
         * request, causing current thread to wait until another thread invokes
1492
         * {@link #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1493
         * #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)}, if there
1494
         * was no waiting request.
1495
         * </p>
1496
         * 
1497
         * <p>
1498
         * All threads will access synchronized to the waiting request.
1499
         * </p>
1500
         * 
1501
         * @return <code>PaintingRequest</code> that was waiting to be attended
1502
         * 
1503
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1504
         */
1505
        public PaintingRequest take() {
1506
            if (waitingRequest == null) {
1507
                synchronized (this) {
1508
                    waiting = true;
1509
                    try {
1510
                        wait();
1511
                    } catch (InterruptedException ie) {
1512
                        waiting = false;
1513
                    }
1514
                }
1515
            }
1516
            paintingRequest = waitingRequest;
1517
            waitingRequest = null;
1518
            return paintingRequest;
1519
        }
1520

    
1521
        /**
1522
         * <p>
1523
         * Thread for attending painting requests.
1524
         * </p>
1525
         * 
1526
         * <p>
1527
         * If there was no double buffer, sets the status to
1528
         * <code>OUTDATED</code> and finishes, otherwise takes the painting
1529
         * request (it's probably that would wait some time), cancel the
1530
         * previous drawing process, and starts processing the request.
1531
         * </p>
1532
         * 
1533
         * @see Thread
1534
         */
1535
        private class Worker implements Runnable {
1536

    
1537
            /*
1538
             * (non-Javadoc)
1539
             * 
1540
             * @see java.lang.Runnable#run()
1541
             */
1542
            public void run() {
1543
                while (!shutdown) {
1544
                    PaintingRequest p = take();
1545
                    // System.out.println("Pintando");
1546
                    if (image != null) {
1547
                        cancelDrawing();
1548
                        if (p != null) {
1549
                                p.paint();
1550
                        }
1551
                    } else {
1552
                        status = DESACTUALIZADO;
1553
                    }
1554
                }
1555
            }
1556
        }
1557
    }
1558

    
1559
    /**
1560
     * <p>
1561
     * An instance of <code>CancelDraw</code> will be shared by all this
1562
     * <code>MapControl</code>'s <code>MapContext</code> layers, allowing
1563
     * receive a notification that, when they're been drawn, to be cancelled.
1564
     * </p>
1565
     * 
1566
     * @see Cancellable
1567
     * 
1568
     * @author Fernando Gonz�lez Cort�s
1569
     */
1570
    public class CancelDraw implements Cancellable {
1571

    
1572
        /**
1573
         * <p>
1574
         * Determines if the drawing task must be canceled or not.
1575
         * </p>
1576
         * 
1577
         * @see #isCanceled()
1578
         * @see #setCanceled(boolean)
1579
         */
1580
        private boolean cancel = false;
1581

    
1582
        /**
1583
         * Creates a new <code>CancelDraw</code> object.
1584
         */
1585
        public CancelDraw() {
1586
        }
1587

    
1588
        /*
1589
         * (non-Javadoc)
1590
         * 
1591
         * @see com.iver.utiles.swing.threads.Cancellable#setCanceled(boolean)
1592
         */
1593
        public void setCanceled(boolean b) {
1594
            cancel = b;
1595
        }
1596

    
1597
        /*
1598
         * (non-Javadoc)
1599
         * 
1600
         * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
1601
         */
1602
        public boolean isCanceled() {
1603
            return cancel;
1604
        }
1605
    }
1606

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

    
1636
        /**
1637
         * <p>
1638
         * Used to avoid mouse wheel move events closed.
1639
         * </p>
1640
         * 
1641
         * <p>
1642
         * If a mouse wheel move event is produced
1643
         */
1644
        long t1;
1645

    
1646
        /**
1647
         * <p>
1648
         * Position of the mouse, in map coordinates.
1649
         * </p>
1650
         * 
1651
         * <p>
1652
         * This point coordinates will be used as center of the <i>zoom</i>
1653
         * operation.
1654
         * </p>
1655
         */
1656
        Point2D pReal;
1657

    
1658
        /**
1659
         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1660
         * @see Behavior#mouseClicked(MouseEvent)
1661
         */
1662
        public void mouseClicked(MouseEvent e) {
1663
            try {
1664
                if (currentMapTool != null) {
1665
                    currentMapTool.mouseClicked(e);
1666
                }
1667
                Point2D p;
1668

    
1669
                if (mapAdjustedPoint != null) {
1670
                    p = mapAdjustedPoint;
1671
                } else {
1672
                    p = vp.toMapPoint(adjustedPoint);
1673
                }            
1674
                previousPoint = new double[] { p.getX(), p.getY() };                
1675
            } catch (BehaviorException t) {
1676
                throwException(t);
1677
            }
1678
        }
1679

    
1680
        /**
1681
         * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1682
         * @see Behavior#mouseEntered(MouseEvent)
1683
         */
1684
        public void mouseEntered(MouseEvent e) {
1685
            setToolMouse();
1686
            try {
1687
                if (currentMapTool != null) {
1688
                    currentMapTool.mouseEntered(e);
1689
                }
1690
            } catch (BehaviorException t) {
1691
                throwException(t);
1692
            }
1693
        }
1694

    
1695
        /**
1696
         * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1697
         * @see Behavior#mouseExited(MouseEvent)
1698
         */
1699
        public void mouseExited(MouseEvent e) {
1700
            try {
1701
                if (currentMapTool != null) {
1702
                    currentMapTool.mouseExited(e);
1703
                }
1704
            } catch (BehaviorException t) {
1705
                throwException(t);
1706
            }
1707
            // Remove the snapping image if exist
1708
            usedSnap = null;
1709
            repaint();
1710
        }
1711

    
1712
        /**
1713
         * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1714
         * @see Behavior#mousePressed(MouseEvent)
1715
         */
1716
        public void mousePressed(MouseEvent e) {
1717
            try {
1718
                if (currentMapTool != null) {
1719
                    currentMapTool.mousePressed(e);
1720
                }
1721
            } catch (BehaviorException t) {
1722
                throwException(t);
1723
            }
1724
        }
1725

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

    
1740
        /**
1741
         * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
1742
         * @see Behavior#mouseWheelMoved(MouseWheelEvent)
1743
         */
1744
        public void mouseWheelMoved(MouseWheelEvent e) {
1745
            try {
1746
                if (currentMapTool == null) {
1747
                    return;
1748
                }
1749

    
1750
                currentMapTool.mouseWheelMoved(e);
1751

    
1752
                // Si el tool actual no ha consumido el evento
1753
                // entendemos que quiere el comportamiento por defecto.
1754
                if (!e.isConsumed()) {
1755
                    // Para usar el primer punto sobre el que queremos centrar
1756
                    // el mapa, dejamos pasar un segundo para considerar el
1757
                    // siguiente
1758
                    // punto como v�lido.
1759
                    if (t1 == 0) {
1760
                        t1 = System.currentTimeMillis();
1761
                        pReal = vp.toMapPoint(e.getPoint());
1762
                    } else {
1763
                        long t2 = System.currentTimeMillis();
1764
                        if ((t2 - t1) > 1000) {
1765
                            t1 = 0;
1766
                        }
1767
                    }
1768
                    cancelDrawing();
1769
                    ViewPort vp = getViewPort();
1770

    
1771
                    /*
1772
                     * Point2D pReal = new
1773
                     * Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1774
                     * vp.getAdjustedExtent().getCenterY());
1775
                     */
1776
                    int amount = e.getWheelRotation();
1777
                    double nuevoX;
1778
                    double nuevoY;
1779
                    double factor;
1780

    
1781
                    if (amount < 0) // nos acercamos
1782
                    {
1783
                        factor = 0.9;
1784
                    } else // nos alejamos
1785
                    {
1786
                        factor = 1.2;
1787
                    }
1788
                    if (vp.getExtent() != null) {
1789
                        nuevoX =
1790
                            pReal.getX()
1791
                                - ((vp.getExtent().getWidth() * factor) / 2.0);
1792
                        nuevoY =
1793
                            pReal.getY()
1794
                                - ((vp.getExtent().getHeight() * factor) / 2.0);
1795
                        double x = nuevoX;
1796
                        double y = nuevoY;
1797
                        double width = vp.getExtent().getWidth() * factor;
1798
                        double height = vp.getExtent().getHeight() * factor;
1799

    
1800
                        try {
1801
                            vp.setEnvelope(geomManager.createEnvelope(x, y, x
1802
                                + width, y + height, SUBTYPES.GEOM2D));
1803
                        } catch (CreateEnvelopeException e1) {
1804
                            LOG.info("Error creating the envelope", e);
1805
                        }
1806
                    }
1807

    
1808
                }
1809
            } catch (BehaviorException t) {
1810
                throwException(t);
1811
            }
1812
        }
1813

    
1814
        /**
1815
         * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1816
         * @see Behavior#mouseDragged(MouseEvent)
1817
         */
1818
        public void mouseDragged(MouseEvent e) {
1819
            calculateSnapPoint(e.getPoint());
1820
            try {
1821
                if (currentMapTool != null) {
1822
                    currentMapTool.mouseDragged(e);
1823
                }
1824
            } catch (BehaviorException t) {
1825
                throwException(t);
1826
            }
1827
            repaint();
1828
        }
1829

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

    
1847
    /**
1848
     * <p<code>MapContextListener</code> listens all events produced in a
1849
     * <code>MapControl</code>'s <code>MapContext</code> object during an atomic
1850
     * period of time, and sets it to dirty, <i>executing
1851
     * <code>drawMap(false)</code>, if any of the
1852
     * following conditions is accomplished</i>:
1853
     * <ul>
1854
     * <li>Any of the <code>LayerEvent</code> in the <code>AtomicEvent</code>
1855
     * parameter notifies a <i>visibility change</i>.</li>
1856
     * <li>There is at least one <code>ColorEvent</code> in the
1857
     * <code>AtomicEvent</code> parameter.</li>
1858
     * <li>There is at least one <code>ExtentEvent</code> in the
1859
     * <code>AtomicEvent</code> parameter.</li>
1860
     * <li>Any of the <code>LayerCollectionEvent</code> in the
1861
     * <code>AtomicEvent</code> parameter notifies that a driver's layer has
1862
     * reloaded it successfully.</li>
1863
     * <li>There is at least one <code>LegendEvent</code> in the
1864
     * <code>AtomicEvent</code> parameter.</li>
1865
     * <li>There is at least one <code>SelectionEvent</code> in the
1866
     * <code>AtomicEvent</code> parameter.</li>
1867
     * </ul>
1868
     * </p>
1869
     * 
1870
     * @author Fernando Gonz�lez Cort�s
1871
     */
1872
    public class MapContextListener implements AtomicEventListener {
1873

    
1874
        /**
1875
         * @see org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener#atomicEvent(org.gvsig.fmap.mapcontext.events.AtomicEvent)
1876
         */
1877
        public void atomicEvent(final AtomicEvent e) {
1878
            if (!SwingUtilities.isEventDispatchThread()) {
1879
                SwingUtilities.invokeLater(new Runnable() {
1880

    
1881
                    public void run() {
1882
                        atomicEvent(e);
1883
                    }
1884
                });
1885
                return;
1886
            }
1887
            LayerEvent[] layerEvents = e.getLayerEvents();
1888

    
1889
            for (int i = 0; i < layerEvents.length; i++) {
1890
                if (layerEvents[i].getProperty().equals("visible")) {
1891
                    drawMap(false);
1892
                    return;
1893
                } else
1894
                    if (layerEvents[i].getEventType() == LayerEvent.EDITION_CHANGED) {
1895
                        drawMap(false);
1896
                        return;
1897
                    }
1898
            }
1899

    
1900
            if (e.getColorEvents().length > 0) {
1901
                drawMap(false);
1902
                return;
1903
            }
1904

    
1905
            if (e.getExtentEvents().length > 0) {
1906
                drawMap(false);
1907
                return;
1908
            }
1909

    
1910
            if (e.getProjectionEvents().length > 0) {
1911
                // redraw = true;
1912
            }
1913

    
1914
            LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1915
            if (aux.length > 0) {
1916
                for (int i = 0; i < aux.length; i++) {
1917
                    if (aux[i].getAffectedLayer().getFLayerStatus()
1918
                        .isDriverLoaded()) {
1919
                        drawMap(false);
1920
                        return;
1921
                    }
1922
                }
1923

    
1924
            }
1925

    
1926
            if (e.getLegendEvents().length > 0) {
1927
                drawMap(false);
1928
                return;
1929
            }
1930

    
1931
            if (e.getSelectionEvents().length > 0) {
1932
                drawMap(false);
1933
                return;
1934
            }
1935
        }
1936
    }
1937

    
1938
    /**
1939
     * <p>
1940
     * Gets the <code>ViewPort</code> of this component's {@link MapContext
1941
     * MapContext} .
1942
     * </p>
1943
     * 
1944
     * @see MapContext#getViewPort()
1945
     */
1946
    public ViewPort getViewPort() {
1947
        return vp;
1948
    }
1949

    
1950
    /**
1951
     * <p>
1952
     * Returns all registered <code>Behavior</code> that can define a way to
1953
     * work with this <code>MapControl</code>.
1954
     * </p>
1955
     * 
1956
     * @return registered <code>Behavior</code> to this <code>MapControl</code>
1957
     * 
1958
     * @see #addBehavior(String, Behavior)
1959
     * @see #addBehavior(String, Behavior[])
1960
     * @see #getMapToolsKeySet()
1961
     * @see #hasTool(String)
1962
     */
1963
    public HashMap getNamesMapTools() {
1964
        return (HashMap) namesMapTools;
1965
    }
1966

    
1967
    /*
1968
     * (non-Javadoc)
1969
     * 
1970
     * @see
1971
     * com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
1972
     */
1973
    public void commandRepaint() {
1974
        drawMap(false);
1975
    }
1976

    
1977
    /*
1978
     * (non-Javadoc)
1979
     * 
1980
     * @see
1981
     * com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
1982
     */
1983
    public void commandRefresh() {
1984
        // TODO Auto-generated method stub
1985
    }
1986

    
1987
    /**
1988
     * <p>
1989
     * Equivalent operation to <i>undo</i>.
1990
     * </p>
1991
     * 
1992
     * <p>
1993
     * Exchanges the previous tool with the current one.
1994
     * </p>
1995
     * 
1996
     * @see #addBehavior(String, Behavior)
1997
     * @see #addBehavior(String, Behavior[])
1998
     * @see #setTool(String)
1999
     */
2000
    public void setPrevTool() {
2001
        setTool(prevTool);
2002
    }
2003

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

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

    
2071
    /**
2072
     * <p>
2073
     * Returns the listener used to catch all mouse events produced in this
2074
     * <code>MapControl</code> instance and that redirects the calls to the
2075
     * current map tool.
2076
     * </p>
2077
     * 
2078
     * @return the map tool listener used
2079
     */
2080
    public MapToolListener getMapToolListener() {
2081
        return mapToolListener;
2082
    }
2083

    
2084
    // mapTool can be null, for instance, in 3D's navigation tools
2085
    /**
2086
     * <p>
2087
     * Sets <code>mapTool</code> as this <code>MapControl</code>'s current map
2088
     * tool.
2089
     * 
2090
     * @param mapTool
2091
     *            a map tool, or <code>null</code> to disable the interaction
2092
     *            with the user
2093
     * 
2094
     * @see #getCurrentMapTool()
2095
     * @see #getCurrentTool()
2096
     * @see #setTool(String)
2097
     * @see #setPrevTool()
2098
     * @see #addBehavior(String, Behavior)
2099
     * @see #addBehavior(String, Behavior[])
2100
     */
2101
    public void setCurrentMapTool(Behavior mapTool) {
2102
        currentMapTool = mapTool;
2103
    }
2104

    
2105
    /**
2106
     * <p>
2107
     * Sets the delay to the timer that refreshes this <code>MapControl</code>
2108
     * instance.
2109
     * </p>
2110
     * 
2111
     * <p>
2112
     * <code>Delay (in ms) = 1000 / getDrawFrameRate()</code>
2113
     * </p>
2114
     * 
2115
     * @see #getDrawFrameRate()
2116
     * @see #setDrawFrameRate(int)
2117
     */
2118
    public void applyFrameRate() {
2119
        if (MapContext.getDrawFrameRate() > 0) {
2120
            timer.setDelay(1000 / MapContext.getDrawFrameRate());
2121
        }
2122
    }
2123

    
2124
    /**
2125
     * <p>
2126
     * Determines if its enabled the repaint that invokes the timer according to
2127
     * {@link #getDrawFrameRate() #getDrawFrameRate()}.
2128
     * </p>
2129
     * 
2130
     * @return <code>true</code> if its enabled; otherwise <code>false</code>
2131
     */
2132
    public static boolean isDrawAnimationEnabled() {
2133
        return drawAnimationEnabled;
2134
    }
2135

    
2136
    /**
2137
     * <p>
2138
     * Sets if its enabled the repaint that invokes the timer according to
2139
     * {@link #getDrawFrameRate() #getDrawFrameRate()}.
2140
     * </p>
2141
     * 
2142
     * @param drawAnimationEnabled
2143
     *            <code>true</code> to enable the mode; otherwise
2144
     *            <code>false</code>
2145
     */
2146
    public static void setDrawAnimationEnabled(boolean drawAnimationEnabled) {
2147
        MapControl.drawAnimationEnabled = drawAnimationEnabled;
2148
    }
2149

    
2150
    /**
2151
     * <p>
2152
     * Gets the shared object that determines if a drawing process must be
2153
     * cancelled or can continue.
2154
     * </p>
2155
     * 
2156
     * @return the shared object that determines if a drawing process must be
2157
     *         cancelled or can continue
2158
     */
2159
    public CancelDraw getCanceldraw() {
2160
        return canceldraw;
2161
    }
2162

    
2163
    /**
2164
     * <p>
2165
     * Gets the tool used in combination with the current tool of this
2166
     * <code>MapControl</code>.
2167
     * </p>
2168
     * 
2169
     * @return the tool used in combination with the <code>currentMapTool</code>
2170
     *         ; <code>null</code> if there is
2171
     *         no combined tool
2172
     */
2173
    public Behavior getCombinedTool() {
2174
        return combinedTool;
2175
    }
2176

    
2177
    /**
2178
     * <p>
2179
     * Sets a tool to be used in combination with the current tool of this
2180
     * <code>MapControl</code>.
2181
     * </p>
2182
     * 
2183
     * @param combinedTool
2184
     *            a tool to be used in combination with the current tool of
2185
     *            <code>MapControl</code>
2186
     */
2187
    public void setCombinedTool(Behavior combinedTool) {
2188
        this.combinedTool = combinedTool;
2189

    
2190
        if (currentMapTool == null) {
2191
            return;
2192
        }
2193

    
2194
        if (currentMapTool instanceof CompoundBehavior) {
2195
            ((CompoundBehavior) currentMapTool).addMapBehavior(combinedTool,
2196
                true);
2197
        } else {
2198
            currentMapTool =
2199
                new CompoundBehavior(new Behavior[] { currentMapTool });
2200
            ((CompoundBehavior) currentMapTool).addMapBehavior(combinedTool,
2201
                true);
2202
        }
2203

    
2204
    }
2205

    
2206
    /**
2207
     * <p>
2208
     * Adds a new tool as combined tool.
2209
     * </p>
2210
     * <p>
2211
     * The new tool will be stored with the previous combined tools, and will be
2212
     * combined with the current tool.
2213
     * </p>
2214
     * <p>
2215
     * If <code>tool</code> was already stored as a combined tool, doesn't adds
2216
     * it.
2217
     * </p>
2218
     * 
2219
     * @param tool
2220
     *            a new tool to be used combined with the current tool
2221
     */
2222
    public void addCombinedBehavior(Behavior tool) {
2223
        tool.setMapControl(this);
2224
        if (combinedTool == null) {
2225
            combinedTool = tool;
2226
        } else {
2227
            if (combinedTool instanceof CompoundBehavior) {
2228
                if (((CompoundBehavior) combinedTool).containsBehavior(tool)) {
2229
                    return;
2230
                }
2231

    
2232
                ((CompoundBehavior) combinedTool).addMapBehavior(tool, true);
2233
            } else {
2234
                if (combinedTool.equals(tool)) {
2235
                    return;
2236
                }
2237

    
2238
                combinedTool =
2239
                    new CompoundBehavior(new Behavior[] { combinedTool });
2240
                ((CompoundBehavior) combinedTool).addMapBehavior(tool, true);
2241
            }
2242
        }
2243

    
2244
        if (currentMapTool == null) {
2245
            return;
2246
        }
2247

    
2248
        if (currentMapTool instanceof CompoundBehavior) {
2249
            ((CompoundBehavior) currentMapTool).addMapBehavior(tool, true);
2250
        } else {
2251
            currentMapTool =
2252
                new CompoundBehavior(new Behavior[] { currentMapTool });
2253
            ((CompoundBehavior) currentMapTool).addMapBehavior(tool, true);
2254
        }
2255
    }
2256

    
2257
    /**
2258
     * <p>
2259
     * Removes the tool <code>tool</code> used in combination with the current
2260
     * tool of this <code>MapControl</code>.
2261
     * </p>
2262
     */
2263
    public void removeCombinedTool(Behavior tool) {
2264
        if ((currentMapTool != null)
2265
            && (currentMapTool instanceof CompoundBehavior)) {
2266
            ((CompoundBehavior) currentMapTool).removeMapBehavior(tool);
2267
        }
2268

    
2269
        if (combinedTool == null) {
2270
            return;
2271
        }
2272

    
2273
        if (combinedTool instanceof CompoundBehavior) {
2274
            ((CompoundBehavior) combinedTool).removeMapBehavior(tool);
2275
        } else {
2276
            combinedTool = null;
2277
        }
2278
    }
2279

    
2280
    /**
2281
     * <p>
2282
     * Updates the grid on the <code>ViewPort</code> of the associated
2283
     * <code>MapControl</code> object according the values in the
2284
     * {@link com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences
2285
     * com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences}.
2286
     * </p>
2287
     * 
2288
     * <p>
2289
     * The preferences are:
2290
     * <ul>
2291
     * <li>Show/hide the grid.</li>
2292
     * <li>Adjust or not the grid.</li>
2293
     * <li>Horizontal ( X ) line separation.</li>
2294
     * <li>Vertical ( Y ) line separation.</li>
2295
     * </ul>
2296
     * </p>
2297
     */
2298
    public void initializeGrid() {
2299
        Preferences prefs = mapControlManager.getEditionPreferences();
2300
        boolean showGrid =
2301
            prefs.getBoolean("grid.showgrid", cadgrid.isShowGrid());
2302
        boolean adjustGrid =
2303
            prefs.getBoolean("grid.adjustgrid", cadgrid.isAdjustGrid());
2304

    
2305
        double dx = prefs.getDouble("grid.distancex", cadgrid.getGridSizeX());
2306
        double dy = prefs.getDouble("grid.distancey", cadgrid.getGridSizeY());
2307

    
2308
        setGridVisibility(showGrid);
2309
        setAdjustGrid(adjustGrid);
2310
        cadgrid.setGridSizeX(dx);
2311
        cadgrid.setGridSizeY(dy);
2312
    }
2313

    
2314
    public void setAdjustGrid(boolean adjustGrid) {
2315
        cadgrid.setAdjustGrid(adjustGrid);
2316
    }
2317

    
2318
    public void setGridVisibility(boolean showGrid) {
2319
        cadgrid.setShowGrid(showGrid);
2320
        cadgrid.setViewPort(getViewPort());
2321
        this.repaint();
2322
    }
2323

    
2324
    /**
2325
     * Uses like a mouse pointer the image that provides the
2326
     * selected tool.
2327
     * 
2328
     */
2329

    
2330
    private Image lastImageCursor = null;
2331
    private Cursor lastCursor = null;
2332

    
2333
    private void setToolMouse() {
2334
        Image imageCursor = getCurrentMapTool().getImageCursor();
2335
        if (imageCursor != null && imageCursor == lastImageCursor && lastCursor != null && lastCursor != transparentCursor) {
2336
            setCursor(lastCursor);
2337
            return;
2338
        }
2339
        lastImageCursor = imageCursor;
2340
        Toolkit toolkit = Toolkit.getDefaultToolkit();
2341
        Cursor c = toolkit.createCustomCursor(imageCursor, new Point(16, 16), "img");
2342
        setCursor(c);
2343
        lastCursor = c;
2344
    }
2345

    
2346
    /**
2347
     * Makes the mouse pointer transparent.
2348
     */
2349
    private void setTransparentMouse() {
2350
        setCursor(transparentCursor);
2351
        lastCursor = transparentCursor;
2352
    }
2353

    
2354
    /**
2355
     * <p>
2356
     * Draws a 31x31 pixels cross round the mouse's cursor with an small
2357
     * geometry centered:
2358
     * <ul>
2359
     * <li><i>an square centered</i>: if isn't over a <i>control point</i>.
2360
     * <li><i>an small geometry centered according to the kind of control
2361
     * point</i>: if it's over a control point. In this case, the small geometry
2362
     * is drawn by a {@link ISnapper ISnapper} type object.<br>
2363
     * On the other hand, a light-yellowed background tool tip text with the
2364
     * type of <i>control point</i> will be displayed.</li>
2365
     * </p>
2366
     * 
2367
     * @param g
2368
     *            <code>MapControl</code>'s graphics where the data will be
2369
     *            drawn
2370
     */
2371
    private void drawCursor() {
2372
        if (adjustedPoint == null) {
2373
            return;
2374
        }
2375

    
2376
        if (usedSnap != null) {
2377
            usedSnap.draw(mapControlDrawer, adjustedPoint);
2378
            setTransparentMouse();
2379
        } else {
2380
            setToolMouse();
2381
        }
2382
    }
2383

    
2384
    /**
2385
     * <p>
2386
     * Adjusts the <code>point</code> to the grid if its enabled, and sets
2387
     * <code>mapHandlerAdjustedPoint</code> with that new value.
2388
     * </p>
2389
     * 
2390
     * <p>
2391
     * The value returned is the distance between those points: the original and
2392
     * the adjusted one.
2393
     * </p>
2394
     * 
2395
     * @param point
2396
     *            point to adjust
2397
     * @param mapHandlerAdjustedPoint
2398
     *            <code>point</code> adjusted
2399
     * 
2400
     * @return distance from <code>point</code> to the adjusted one. If there is
2401
     *         no
2402
     *         adjustment, returns <code>Double.MAX_VALUE</code>.
2403
     */
2404

    
2405
    private double adjustToHandler(Point2D point,
2406
        Point2D mapHandlerAdjustedPoint) {
2407

    
2408
        if (!isRefentEnabled())
2409
            return Double.MAX_VALUE;
2410

    
2411
        List layersToSnap = getMapContext().getLayersToSnap();
2412

    
2413
        double mapTolerance =
2414
            vp.toMapDistance(mapControlManager.getTolerance());
2415
        double minDist = mapTolerance;
2416
        double middleTol = mapTolerance * 0.5;
2417
        Point2D mapPoint = point;
2418
        Envelope r = null;
2419
        try {
2420
            r =
2421
                geomManager.createEnvelope(mapPoint.getX() - middleTol,
2422
                    mapPoint.getY() - middleTol, mapPoint.getX() + middleTol,
2423
                    mapPoint.getY() + middleTol, SUBTYPES.GEOM2D);
2424
        } catch (Exception e1) {
2425
            LOG.info("Error creating the envelope", e1);
2426
            return Double.MAX_VALUE;
2427
        }
2428

    
2429
        usedSnap = null;
2430
        Point2D lastPoint = null;
2431
        if (previousPoint != null) {
2432
            lastPoint = new Point2D.Double(previousPoint[0], previousPoint[1]);
2433
        }
2434
        for (int j = 0; j < layersToSnap.size(); j++) {
2435
            FLyrVect lyrVect = (FLyrVect) layersToSnap.get(j);
2436
            SpatialCache cache = lyrVect.getSpatialCache();
2437
            if (lyrVect.isVisible()) {
2438
                // La lista de snappers est� siempre ordenada por prioridad. Los
2439
                // de mayor
2440
                // prioridad est�n primero.
2441
                List geoms = cache.query(r);
2442
                
2443
                for (int i = 0; i < mapControlManager.getSnapperCount(); i++)
2444
                {
2445
                    ISnapper theSnapper = mapControlManager.getSnapperAt(i);
2446
                    if (theSnapper instanceof ISnapperGeometriesVectorial)
2447
                    {
2448
                        ((ISnapperGeometriesVectorial)theSnapper).setGeometries(geoms);                        
2449
                    }
2450
                } 
2451
                
2452
                for (int n = 0; n < geoms.size(); n++) {
2453
                    Geometry geom = (Geometry) geoms.get(n);
2454
                    for (int i = 0; i < mapControlManager.getSnapperCount(); i++) {
2455
                        ISnapper theSnapper = mapControlManager.getSnapperAt(i);
2456
                        if (!theSnapper.isEnabled())
2457
                            continue;
2458

    
2459
                        if (usedSnap != null) {
2460
                            // Si ya tenemos un snap y es de alta prioridad,
2461
                            // cogemos ese. (A no ser que en otra capa
2462
                            // encontremos un snapper mejor)
2463
                            if (theSnapper.getPriority() > usedSnap
2464
                                .getPriority())
2465
                                break;
2466
                        }
2467
                        // SnappingVisitor snapVisitor = null;
2468
                        Point2D theSnappedPoint = null;
2469
                        if (theSnapper instanceof ISnapperVectorial) {
2470
                            theSnappedPoint =
2471
                                ((ISnapperVectorial) theSnapper).getSnapPoint(
2472
                                    point, geom, mapTolerance, lastPoint);
2473
                        }
2474
                        if (theSnapper instanceof ISnapperRaster) {
2475
                            ISnapperRaster snapRaster =
2476
                                (ISnapperRaster) theSnapper;
2477
                            theSnappedPoint =
2478
                                snapRaster.getSnapPoint(this, point,
2479
                                    mapTolerance, lastPoint);
2480
                        }
2481

    
2482
                        if (theSnappedPoint != null) {
2483
                            double distAux = theSnappedPoint.distance(point);
2484
                            if (minDist > distAux) {
2485
                                minDist = distAux;
2486
                                usedSnap = theSnapper;
2487
                                mapHandlerAdjustedPoint
2488
                                    .setLocation(theSnappedPoint);
2489
                            }
2490
                        }
2491
                    }
2492
                } // for n
2493
            } // visible
2494
        }
2495
        if (usedSnap != null)
2496
            return minDist;
2497
        return Double.MAX_VALUE;
2498

    
2499
    }
2500

    
2501
    /**
2502
     * Determines if snap tools are enabled or disabled.
2503
     * 
2504
     * @return <code>true</code> to enable the snap tools; <code>false</code> to
2505
     *         disable them
2506
     * 
2507
     * @see #setRefentEnabled(boolean)
2508
     */
2509
    public boolean isRefentEnabled() {
2510
        return bRefent;
2511
    }
2512

    
2513
    /**
2514
     * <p>
2515
     * Tries to find the nearest geometry or grid control point by the position
2516
     * of the current snap tool.
2517
     * </p>
2518
     * 
2519
     * <p>
2520
     * Prioritizes the grid control points than the geometries ones.
2521
     * </p>
2522
     * 
2523
     * <p>
2524
     * If finds any near, stores the <i>map</i> and <i>pixel</i> coordinates for
2525
     * the snap, and enables the <code>bForceCoord</code> attribute for the next
2526
     * draw of the mouse's cursor.
2527
     * </p>
2528
     * 
2529
     * @param point
2530
     *            current mouse 2D position
2531
     */
2532
    public void calculateSnapPoint(Point point) {
2533
        // Se comprueba el ajuste a rejilla
2534

    
2535
        Point2D gridAdjustedPoint = vp.toMapPoint(point);
2536
        double minDistance = Double.MAX_VALUE;
2537

    
2538
        minDistance = cadgrid.adjustToGrid(gridAdjustedPoint);
2539
        if (minDistance < Double.MAX_VALUE) {
2540
            adjustedPoint = vp.fromMapPoint(gridAdjustedPoint);
2541
            mapAdjustedPoint = gridAdjustedPoint;
2542
        } else {
2543
            mapAdjustedPoint = null;
2544
        }
2545

    
2546
        Point2D handlerAdjustedPoint = null;
2547

    
2548
        // Se comprueba el ajuste a los handlers
2549
        if (mapAdjustedPoint != null) {
2550
            handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
2551
        } else {
2552
            handlerAdjustedPoint = vp.toMapPoint(point);
2553
        }
2554

    
2555
        Point2D mapPoint = new Point2D.Double();
2556
        double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
2557

    
2558
        if (distance < minDistance) {
2559
            bForceCoord = true;
2560
            adjustedPoint = vp.fromMapPoint(mapPoint);
2561
            mapAdjustedPoint = mapPoint;
2562
            minDistance = distance;
2563
        }
2564

    
2565
        // Si no hay ajuste
2566
        if (minDistance == Double.MAX_VALUE) {
2567
            adjustedPoint = point;
2568
            mapAdjustedPoint = null;
2569
        }
2570
    }
2571

    
2572
    /**
2573
     * Sets the snap tools enabled or disabled.
2574
     * 
2575
     * @param activated
2576
     *            <code>true</code> to enable the snap tools; <code>false</code>
2577
     *            to disable them
2578
     * 
2579
     * @see #isRefentEnabled()
2580
     */
2581
    public void setRefentEnabled(boolean activated) {
2582
        bRefent = activated;
2583
    }
2584

    
2585
    public Grid getGrid() {
2586
        return cadgrid;
2587
    }
2588

    
2589
    public void update(Observable observable, Object notification) {
2590
        DataStoreNotification ddsn = (DataStoreNotification) notification;
2591
        String type = ddsn.getType();
2592
        if (type.equals(FeatureStoreNotification.AFTER_UNDO)
2593
            || type.equals(FeatureStoreNotification.AFTER_REDO)) {
2594
            repaint();
2595
        }
2596
    }
2597

    
2598
    /**
2599
     * @return the adjustedPoint
2600
     */
2601
    public Point2D getAdjustedPoint() {
2602
        return adjustedPoint;
2603
    }
2604

    
2605
    /**
2606
     * @return the mapAdjustedPoint
2607
     */
2608
    public Point2D getMapAdjustedPoint() {
2609
        return mapAdjustedPoint;
2610
    }
2611

    
2612
    /**
2613
     * Gets the selected point. If the snapping is enabled
2614
     * it returns the selected point.
2615
     * 
2616
     * @return
2617
     *         The selected point
2618
     */
2619
    public Point2D getPoint() {
2620
        if (mapAdjustedPoint != null) {
2621
            return mapAdjustedPoint;
2622
        } else {
2623
            return getViewPort().toMapPoint(adjustedPoint);
2624
        }
2625
    }
2626

    
2627
        public synchronized void dispose() {
2628
                // Check if we have already been disposed, and don't do it again
2629
                if (!disposed && ToolsLocator.getDisposableManager().release(this)) {
2630
                        drawer.setShutdown(true);
2631
                        disposed = true;
2632
                }
2633
        }
2634
}