Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / libraries / libFMap / src / org / gvsig / fmap / mapcontrol / MapControl.java @ 21156

History | View | Annotate | Download (64.9 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package org.gvsig.fmap.mapcontrol;
42

    
43
import java.awt.Color;
44
import java.awt.Component;
45
import java.awt.Dimension;
46
import java.awt.Graphics;
47
import java.awt.Graphics2D;
48
import java.awt.event.ActionEvent;
49
import java.awt.event.ActionListener;
50
import java.awt.event.ComponentEvent;
51
import java.awt.event.ComponentListener;
52
import java.awt.event.MouseEvent;
53
import java.awt.event.MouseListener;
54
import java.awt.event.MouseMotionListener;
55
import java.awt.event.MouseWheelEvent;
56
import java.awt.event.MouseWheelListener;
57
import java.awt.geom.Point2D;
58
import java.awt.geom.Rectangle2D;
59
import java.awt.image.BufferedImage;
60
import java.util.HashMap;
61
import java.util.Set;
62

    
63
import javax.swing.JComponent;
64
import javax.swing.Timer;
65

    
66
import org.cresques.cts.IProjection;
67
import org.gvsig.fmap.crs.CRSFactory;
68
import org.gvsig.fmap.mapcontext.MapContext;
69
import org.gvsig.fmap.mapcontext.ViewPort;
70
import org.gvsig.fmap.mapcontext.events.AtomicEvent;
71
import org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener;
72
import org.gvsig.fmap.mapcontext.layers.LayerCollectionEvent;
73
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
74
import org.gvsig.fmap.mapcontrol.tools.BehaviorException;
75
import org.gvsig.fmap.mapcontrol.tools.CompoundBehavior;
76
import org.gvsig.fmap.mapcontrol.tools.Behaibor.Behavior;
77

    
78
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
79
import com.iver.utiles.exceptionHandling.ExceptionListener;
80
import com.iver.utiles.swing.threads.Cancellable;
81

    
82

    
83
/**
84
 * <p>A component that includes a {@link MapContext MapContext} with support for use it as a particular {@link Behavior Behavior}.</p>
85
 *
86
 * <p>A developer can register a set of <code>Behavior</code>, but only one (that can be a composition of several) of them can be active. The active one
87
 *  defines the way to work and access with its <code>MapContext</code>'s layers. The active behavior, in combination with the appropriate
88
 *  {@link ToolListener ToolListener} will allow user work with a particular <i>tool</i>.</p>
89
 *
90
 * <p>All mouse events produced on this component will be delegated to the current active behavior, the <i>currentMapTool</i>.</p>
91
 *
92
 * <p><b>Drawing process:</b></p>
93
 *
94
 * <p>Uses a double buffer for the drawing process of <code>MapContext</code>'s information.</p>
95
 *
96
 * <p>If the double buffer wasn't created, creates a new one.</p>
97
 *
98
 * <p>Paints the component according the following algorithm:
99
 * <br>
100
 *  &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
101
 *  &nbsp &nbsp If there is a <i>double buffer</i>:<br>
102
 *  &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the <code>MapControl</code> instance, delegates
103
 *   the drawing process to that behavior, calling: <code><i>behavior_instance</i>.paintComponent(g)</code>.<br>
104
 *  &nbsp &nbsp &nbsp Else, repaints the current graphical information quickly calling: <code>g.drawImage(image,0,0,null)</code>.<br>
105
 *  &nbsp Else, (<i>status</i> is <i>OUTDATED</i>, or <i>ONLY_GRAPHICS</i>): executes a quickly repaint of the previous information calling <code>g.drawImage(image,0,0,null)</code>, and creates
106
 *   a <i>painting request</i> to delegate the heavy drawing process to the {@link Drawer2 Drawer2}'s worker thread, according the <i>SingleWorketThread</i> pattern, starting a timer to update
107
 *   (invoking <code>repaint()</code>) the view every delay of <code>1000 / drawFrameRate</code> ms. during that heavy drawing process, and if its enabled <code>drawAnimationEnabled</code>. The <i>painting request</i> once is being attended, invokes <code>MapContext</code> to
108
 *   draw the layers: <code>mapContext.draw(image, g, cancel,mapContext.getScaleView());</code>
109
 * <br>
110
 * <p>Some notes:
111
 *  <ul>
112
 *   <li>The painting process can be cancelled calling {@link #cancelDrawing() #cancelDrawing()}.</li>
113
 *   <li>At last resort, the particular implementation of each layer in a <code>MapControl</code>'s <code>MapContrext</code>
114
 *    will be that one which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</li>
115
 *   <li>It's possible to force repaint all layers, calling {@link #drawMap(boolean doClear) #drawMap(boolean)}.</li>
116
 *   <li>It's possible repaint only the dirty layers, calling {@link #rePaintDirtyLayers() #rePaintDirtyLayers()}.</li>
117
 *   <li>It's possible repaint only the {@link GraphicLayer GraphicLayer}, calling {@link #drawGraphics() #drawGraphics()}.</li>
118
 *  </ul>
119
 * </p>
120
 *
121
 * <p><b>Tools:</b></p>
122
 *
123
 * <p>A developer can:
124
 *   <ul>
125
 *    <li>Register each tool as:
126
 *     <ul>
127
 *      <li>A single behavior: {@link #addMapTool(String, Behavior) #addMapTool(String, Behavior)}.</li>
128
 *      <li>Or, a compound behavior: {@link #addMapTool(String, Behavior) #addMapTool(String, Behavior)}.</li>
129
 *     </ul>
130
 *    </li>
131
 *    <li>Get the current active tool: {@link #getCurrentMapTool() #getCurrentMapTool()}.</li>
132
 *    <li>Get the current active tool name: {@link #getCurrentTool() #getCurrentTool()}.</li>
133
 *    <li>Get a registered tool: {@link #getMapTool(String) #getMapTool(String)}.</li>
134
 *    <li>Get the name of all tools registered: {@link #getMapToolsKeySet() #getMapToolsKeySet()}.</li>
135
 *    <li>Get all tools registered, including the name they were registered: {@link #getNamesMapTools() #getNamesMapTools()}.</li>
136
 *    <li>Determine if has a tool registered: {@link #hasTool(String) #hasTool(String)}.</li>
137
 *    <li>Set as an active tool, one of the registered: {@link #setTool(String) #setTool(String)}.</li>
138
 *    <li>Set as active tool, the previous used: {@link #setPrevTool() #setPrevTool()}.</li>
139
 *    <li>Set the current tool: {@link #setCurrentMapTool(Behavior) #setCurrentMapTool(Behavior)}.</li>
140
 *    <li>Change the draw frame rate: {@link #setDrawFrameRate(int) #setDrawFrameRate(int)} and {@link #applyFrameRate() #applyFrameRate()}.</li>
141
 *    <li>Get the draw frame rate: {@link #getDrawFrameRate() #getDrawFrameRate()}.</li>
142
 *    <li>Determine if will repaint this component each time timer finishes: {@link #isDrawAnimationEnabled() #isDrawAnimationEnabled()}.</li>
143
 *    <li>Change if will repaint this component each time timer finishes: {@link #setDrawAnimationEnabled(boolean) #setDrawAnimationEnabled(boolean)}.</li>
144
 *    <li>Get the shared object that determines if a drawing process must be cancelled or can continue: {@link #getCanceldraw() #getCanceldraw()}.</li>
145
 *    <li>Get the combined tool: {@link #getCombinedTool() #getCombinedTool()}.</li>
146
 *    <li>Set a combined tool: {@link #setCombinedTool(Behavior) #setCombinedTool(Behavior)}.</li>
147
 *    <li>Remove the combined tool: {@link #removeCombinedTool() #removeCombinedTool()}.</li>
148
 *   </ul>
149
 * </p>
150
 *
151
 * <p><b>Exception listener:</b></p>
152
 *
153
 * <p> Adding an <code>ExceptionListener</code>, can get notification about any exception produced:
154
 *  <ul>
155
 *   <li>Attending a <i>painting request</i>.</li>
156
 *   <li>Working with the active tool.</li>
157
 *   <li>Applying a <i>zoom in</i> or <i>zoom out</i> operation.</li>
158
 *  </ul>
159
 * </p>
160
 *
161
 * <p><b>Other:</b></p>
162
 *
163
 * <p>Other useful capabilities of <code>MapControl</code>:
164
 *   <ul>
165
 *    <li>Cancel the current drawing process (notifying it also to the inner
166
 *     <code>MapContext</code> instance and its layers): {@link #cancelDrawing() #cancelDrawing()}.</li>
167
 *    <li>Applying a <i>zoom in</i> operation centered at mouse position (without a <code>ToolListener</code>): {@link #zoomIn() #zoomIn()}.</li>
168
 *    <li>Applying a <i>zoom out</i> operation centered at mouse position (without a <code>ToolListener</code>): {@link #zoomOut() #zoomOut()}.</li>
169
 *   </ul>
170
 * </p>
171
 *
172
 * @see CancelDraw
173
 * @see Drawer2
174
 * @see MapContextListener
175
 * @see MapToolListener
176
 *
177
 * @author Fernando Gonz?lez Cort?s
178
 * @author Pablo Piqueras Bartolom? (pablo.piqueras@iver.es)
179
 */
180
public class MapControl extends JComponent implements ComponentListener {
181
        /**
182
         * <p>One of the possible status of <code>MapControl</code>. Determines that all visible information has been
183
         * drawn and its updated.</p>
184
         */
185
        public static final int ACTUALIZADO = 0;
186

    
187
        /**
188
         * <p>One of the possible status of <code>MapControl</code>. Determines that not all visible information has been
189
         * drawn or isn't updated.</p>
190
         */
191
        public static final int DESACTUALIZADO = 1;
192

    
193
        /**
194
         * <p>One of the possible status of <code>MapControl</code>. Determines that only the graphical layer must
195
         * be drawn / updated.</p>
196
         */
197
        public static final int ONLY_GRAPHICS = 2;
198

    
199
        /**
200
         * <p>Determines the number of frames.</p>
201
         *
202
         * <p>Number of updates per second that the timer will invoke repaint this component.</p>
203
         */
204
    private static int drawFrameRate = 3;
205

    
206
    /**
207
     * <p>Determines if the drawer can update this <code>MapControl</code> instance when the timer launches an event.</p>
208
     */
209
    private static boolean drawAnimationEnabled = true;
210

    
211
    // public static final int FAST_PAINT = 3;
212
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
213

    
214
    /**
215
     * <p>Inner model with the layers, event support for drawing them, and the <code>ViewPort</code>
216
     *  with information to adapt to the bounds available in <i>image coordinates</i>.</p>
217
     *
218
     * @see #getMapContext()
219
     * @see #setMapContext(MapContext)
220
     */
221
    private MapContext mapContext = null;
222

    
223
    //private boolean drawerAlive = false;
224

    
225

    
226
        /**
227
         * <p>All registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
228
         *
229
         * <p>Only one of them can be active at a given moment.</p>
230
         *
231
         * @see #addMapTool(String, Behavior)
232
         * @see #addMapTool(String, Behavior[])
233
         * @see #getMapTool(String)
234
         * @see #getMapToolsKeySet()
235
         * @see #getNamesMapTools()
236
         */
237
    protected HashMap namesMapTools = new HashMap();
238

    
239
        /**
240
         * <p>Active {@link Behavior Behavior} that will generate events according a criterion, and then, with a {@link ToolListener ToolListener}
241
         *  associated, will simulate to user that works with this component as a particular tool.</p>
242
         *
243
         * @see #getCurrentMapTool()
244
         * @see #getCurrentTool()
245
         * @see #setTool(String)
246
         */
247
    protected Behavior currentMapTool = null;
248

    
249
        /**
250
         * <p>Determines which's the current drawn status of this component:
251
         * <ul>
252
         *  <li><b>OUTDATED</b>: all visible information has been drawn or isn't updated.</li>
253
         *  <li><b>UTDATED</b>: all visible information has been drawn and its updated.</li>
254
         *  <li><b>ONLY_GRAPHICS</b>: only the graphical layer must be drawn / updated.</li>
255
         * </ul>
256
         * </p>
257
         *
258
         * <p>The <code>MapControl</code> drawing process will consider the value of this parameter to decide which elements will
259
         *  be updated or drawn.</p>
260
         */
261
    private int status = DESACTUALIZADO;
262

    
263
        /**
264
         * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
265
         *
266
         * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
267
         * Meanwhile, the previous image can be kept showed.</p>
268
         *
269
         * @see BufferedImage
270
         *
271
         * @see #getImage()
272
         */
273
    private BufferedImage image = null;
274

    
275
        /**
276
         * <p>Name of the tool used currently to interact with this component.</p>
277
         *
278
         * @see #getCurrentTool()
279
         * @see #setTool(String)
280
         */
281
    protected String currentTool;
282

    
283
        /**
284
         * <p>Object to store the flag that notifies a drawing thread task and <code>MapContext</code>'s layers,
285
         * that must be canceled or can continue with the process.</p>
286
         *
287
         * @see #cancelDrawing()
288
         */
289
    private CancelDraw canceldraw;
290

    
291
    //private boolean isCancelled = true;
292

    
293
        /**
294
         * <p>Fires an action events after a specified delay.</p>
295
         *
296
         * <p><code>MapControl</code> will use the timer to update its visible graphical information during
297
         *  a drawing process, or allowing to cancel that process.</p>
298
         *
299
         * <p>This is very useful to pretend faster interactivity to user when <code>MapControl</code> has
300
         *  lots of layers, and / or layers with heavy graphical elements, that need a long time to finish
301
         *  drawing all its data.</p>
302
         */
303
    private Timer timer;
304

    
305
        /**
306
         * <p>Reference to the {@link ViewPort ViewPort} of the {@link MapContext MapContext} of this component.</p>
307
         *
308
         * <p>The view port once is created an instance of <code>MapControl</code>,
309
         *  is obtained from the <i>EPSG:23030</i> projection, that's the default projection for this component.</p>
310
         *
311
         * <p>After, the view port will change adapting itself according the current projection and the extent.</p>
312
         *
313
         * @see #getViewPort()
314
         *
315
         * @see ViewPort
316
         */
317
    protected ViewPort vp;
318

    
319
    //private Drawer drawer;
320

    
321
        /**
322
         * <p>Manager of all <code>MapControl</code> painting requests.</p>
323
         */
324
    private Drawer2 drawer2;
325

    
326
    // private boolean firstDraw = true;
327

    
328
        /**
329
         * <p>Listener of all kind of mouse events produced in this component.</p>
330
         *
331
         * <p>Delegates each mouse event to the current map tool.</p>
332
         *
333
         * @see #addMapTool(String, Behavior)
334
         * @see #addMapTool(String, Behavior[])
335
         * @see #getMapTool(String)
336
         * @see #getMapToolsKeySet()
337
         * @see #getNamesMapTools()
338
         * @see #setTool(String)
339
         */
340
    protected MapToolListener mapToolListener = new MapToolListener();
341

    
342
        /**
343
         * <p>Listener of all events produced in a this component's <code>MapContext</code>
344
         * object during an atomic period of time.</p>
345
         */
346
    private MapContextListener mapContextListener = new MapContextListener();
347

    
348
        /**
349
         * <p>Group of <code>ExceptionListener</code> that, in whatever moment could be notified a Throwable Java error or exception.</p>
350
         *
351
         * @see #addExceptionListener(ExceptionListener)
352
         * @see #removeExceptionListener(ExceptionListener)
353
         */
354
    private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
355

    
356
    /**
357
     * <p>Name of the previous tool used.</p>
358
     */
359
        protected String prevTool;
360

    
361
        /**
362
         * <p>Tool that will be used combined with the current tool of this <code>MapControl</code>.</p>
363
         */
364
        private Behavior combinedTool = null;
365

    
366
        /**
367
     * We need this to avoid not wanted refresh. REMEMBER TO SET TO TRUE!!
368
     */
369
    // private boolean paintEnabled = false;
370

    
371
        /**
372
         * <p>Creates a new <code>MapControl</code> instance with the following characteristics:
373
         * <ul>
374
         *  <li><i>Name</i>: MapControl .</li>
375
         *  <li>Disables the double buffer of <code>JComponent</code> .</li>
376
         *  <li>Sets opaque <i>(see {@link JComponent#setOpaque(boolean)} )</i>. </li>
377
         *  <li>Sets its status to <code>OUTDATED</code> .</li>
378
         *  <li>Creates a new {@link CancelDraw CancelDraw} object to notify <code>MapContext</code>'s layers if can continue processing the drawn or must cancel it.</li>
379
         *  <li>Creates a new {@link MapContext MapContext} with a new {@link ViewPort ViewPort} in the projection <i>"EPSG:23030"</i> .</li>
380
         *  <li>Creates a new {@link CommandListener CommandListener} for edition operations.</li>
381
         *  <li>Creates a new {@link MapToolListener MapToolListener}, and associates it as a listener of whatever kind of mouse events produced in this component.</li>
382
         *  <li>Creates a new {@link Drawer2 Drawer2} for managing the painting requests.</li>
383
         *  <li>Creates a new timer that will invoke refresh this component <code>drawFrameRate</code> per second, when is running a drawing process, and its enabled
384
         *   <code>drawAnimationEnabled</code>.</li>
385
         * </ul>
386
         * </p>
387
         */
388
        public MapControl() {
389
                this.setName("MapControl");
390
                setDoubleBuffered(false);
391
                setOpaque(true);
392
                status = DESACTUALIZADO;
393

    
394
                //Clase usada para cancelar el dibujado
395
                canceldraw = new CancelDraw();
396

    
397
                //Modelo de datos y ventana del mismo
398
                // TODO: Cuando creamos un mapControl, deber?amos asignar
399
                // la projecci?n por defecto con la que vayamos a trabajar.
400
                // 23030 es el c?digo EPSG del UTM30 elipsoide ED50
401
                vp = new ViewPort(CRSFactory.getCRS("EPSG:23030"));
402
                setMapContext(new MapContext(vp));
403

    
404
                //eventos
405
                this.addComponentListener(this);
406
                this.addMouseListener(mapToolListener);
407
                this.addMouseMotionListener(mapToolListener);
408
                this.addMouseWheelListener(mapToolListener);
409

    
410
        this.drawer2 = new Drawer2();
411
                //Timer para mostrar el redibujado mientras se dibuja
412
                timer = new Timer(1000/drawFrameRate,
413
                                new ActionListener() {
414
                                        public void actionPerformed(ActionEvent e) {
415

    
416
                                                if (drawAnimationEnabled) {
417
                                                        MapControl.this.repaint();
418
                                                }
419
                                        }
420
                                });
421
        }
422

    
423
        /**
424
         * <p>Sets a <code>MapContext</code> to this component.</p>
425
         *
426
         * <p>The <code>MapContext</code> has the <i>model</i>, and most of the <i>view</i>,
427
         * and <i>control</i> logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the
428
         * information to the projection, and to display it in the available area.</p>
429
         *
430
         * <p>If <code>model</code> hadn't a <code>ViewPort</code>, assigns the current one to it, otherwise, use its <code>ViewPort</code>.</p>
431
         *
432
         * <p>After assigning the <code>MapContext</code> and <code>ViewPort</code>, sets the same {@link MapContextListener MapContextListener}
433
         *  that was using, and changes the <i>status</i> to <code>OUTDATED</code>.</p>
434
         *
435
         * @param model this component's <code>MapContext</code>, that includes the <code>ViewPort</code>.
436
         *
437
         * @see MapContext
438
         *
439
         * @see #getMapContext()
440
         */
441
        public void setMapContext(MapContext model) {
442
                if (mapContext != null) {
443
                        mapContext.removeAtomicEventListener(mapContextListener);
444
                }
445

    
446
                mapContext = model;
447

    
448
                if (mapContext.getViewPort() == null) {
449
                        mapContext.setViewPort(vp);
450
                } else {
451
                        vp = mapContext.getViewPort();
452

    
453
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
454
                        //System.err.println("Viewport en setMapContext:" + vp);
455
                }
456

    
457
                mapContext.addAtomicEventListener(mapContextListener);
458

    
459
                status = DESACTUALIZADO;
460
        }
461

    
462
        /**
463
         * <p>Gets this component's {@link MapContext MapContext} projection.</p>
464
         *
465
         * @return this component's {@link MapContext MapContext} projection
466
         *
467
         * @see MapContext#getProjection()
468
         * @see MapControl#setProjection(IProjection)
469
         */
470
        public IProjection getProjection() {
471
                return getMapContext().getProjection();
472
        }
473

    
474
        /**
475
         * <p>Sets the projection to this component's {@link MapContext MapContext}.</p>
476
         *
477
         * @param proj the kind of projection to this component's {@link MapContext MapContext}
478
         *
479
         * @see MapContext#setProjection(IProjection)
480
         * @see MapControl#getProjection()
481
         */
482
        public void setProjection(IProjection proj) {
483
                getMapContext().setProjection(proj);
484
        }
485

    
486
        /**
487
         * <p>Gets this component's <code>MapContext</code>, with the <i>model</i>, and most of the <i>view</i>,
488
         * and <i>control</i> logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the
489
         * information to the projection, and display it in the available area.</p>
490
         *
491
         * @return this component's <code>MapContext</code>, that includes the <code>ViewPort</code> used to project the
492
         * graphical information, and display it in the available area
493
         *
494
         * @see MapContext
495
         *
496
         * @see MapControl#setMapContext(MapContext)
497
         */
498
        public MapContext getMapContext() {
499
                return mapContext;
500
        }
501

    
502
        /**
503
         * <p>Registers a new behavior to this component.</p>
504
         *
505
         * <p>According the nature of the {@link Behavior Behavior}, different events will be generated. Those
506
         *  events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this
507
         *  <code>MapControl</code> object as a <i>tool</i>.</p>
508
         *
509
         * @param name name to identify the behavior to add
510
         * @param tool the behavior to add
511
         *
512
         * @see #addMapTool(String, Behavior[])
513
         * @see #getNamesMapTools()
514
         * @see #getMapToolsKeySet()
515
         * @see #hasTool(String)
516
         */
517
        public void addMapTool(String name, Behavior tool) {
518
                namesMapTools.put(name, tool);
519
                tool.setMapControl(this);
520
        }
521

    
522
        /**
523
         * <p>Registers a new behavior to this component as a {@link CompoundBehavior CompoundBehavior} made up of <code>tools</code>.</p>
524
         *
525
         * <p>According the nature of the behaviors registered, different events will be generated. Those
526
         *  events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this
527
         *  <code>MapControl</code> object as a <i>tool</i>.</p>
528
         *
529
         * @param name name to identify the compound behavior to add
530
         * @param tools the compound behavior to add
531
         *
532
         * @see #addMapTool(String, Behavior)
533
         * @see #getNamesMapTools()
534
         * @see #getMapToolsKeySet()
535
         * @see #hasTool(String)
536
         */
537
        public void addMapTool(String name, Behavior[] tools){
538
                CompoundBehavior tool = new CompoundBehavior(tools);
539
                addMapTool(name, tool);
540
        }
541

    
542
        /**
543
         * <p>Gets the <code>Behavior</code> registered in this component, identified
544
         *  by <code>name</code>.</p>
545
         *
546
         * @param name name of a registered behavior
547
         *
548
         * @return tool the registered behavior in this component as <code>name</code>, or <code>null</code> if
549
         *  no one has that identifier
550
         *
551
         * @see #addMapTool(String, Behavior)
552
         * @see #addMapTool(String, Behavior[])
553
         * @see #hasTool(String)
554
         */
555
        public Behavior getMapTool(String name) {
556
                return (Behavior)namesMapTools.get(name);
557
        }
558

    
559
        /**
560
         * <p>Returns a set view of the keys that identified the tools
561
         *  registered.</p>
562
         *
563
         * @return a set view of the keys that identified the tools registered
564
         *
565
         * @see HashMap#keySet()
566
         *
567
         * @see #getNamesMapTools()
568
          * @see #addMapTool(String, Behavior)
569
          * @see #addMapTool(String, Behavior[])
570
         */
571
        public Set getMapToolsKeySet() {
572
                return namesMapTools.keySet();
573
        }
574

    
575
        /**
576
         * <p>Returns <code>true</code> if this component contains a tool identified by <code>toolName</code>.</p>
577
         *
578
         * @param toolName identifier of the tool
579
         *
580
         * @return <code>true</code> if this component contains a tool identified by <code>toolName</code>; otherwise <code>false</code>
581
         *
582
         * @see #addMapTool(String, Behavior)
583
         * @see #addMapTool(String, Behavior[])
584
         */
585
        public boolean hasTool(String toolName) {
586
                return namesMapTools.containsKey(toolName);
587
        }
588

    
589
        /**
590
         * <p>Sets as current active <code>Behavior</code> associated to this component, that one which
591
         *  is registered and identified by <code>toolName</code>.</p>
592
         *
593
         * <p>Changing the current active behavior for this <code>MapControl</code>, implies also updating the
594
         *  previous <i>behavior</i> tool, and the current cursor.</p>
595
         *
596
         * @param toolName name of a registered behavior
597
         *
598
         * @see #getCurrentMapTool()
599
         * @see #getCurrentTool()
600
         */
601
        public void setTool(String toolName) {
602
                prevTool=getCurrentTool();
603
                Behavior mapTool = (Behavior) namesMapTools.get(toolName);
604
                currentMapTool = mapTool;
605
                currentTool = toolName;
606

    
607
                if (combinedTool != null) {
608
                        if (mapTool instanceof CompoundBehavior) {
609
                                ((CompoundBehavior)mapTool).addMapBehavior(combinedTool, combinedTool.getListener().cancelDrawing());
610
                        }
611
                        else {
612
                                currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool, combinedTool});
613
                        }
614
                }
615

    
616
                this.setCursor(mapTool.getCursor());
617
        }
618

    
619
        /**
620
         * <p>Gets as current active <code>Behavior</code> associated to this component, that one which
621
         *  is registered and identified by <code>toolName</code>.</p>
622
         *
623
         * <p>Changing the current active behavior for this <code>MapControl</code>, implies also updating the
624
         *  previous <i>behavior</i> tool, and the current cursor.</p>
625
         *
626
         * @param toolName name of a registered behavior
627
         *
628
         * @see #getCurrentTool()
629
         * @see #setTool(String)
630
         */
631
        public Behavior getCurrentMapTool(){
632
                return currentMapTool;
633
        }
634

    
635
        /**
636
         * <p>Returns the name of the current selected tool on this MapControl</p>
637
         *
638
         * @return the name of the current's behavior tool associated to this component
639
         *
640
         * @see #getCurrentMapTool()
641
         * @see #setTool(String)
642
         */
643
        public String getCurrentTool() {
644
                return currentTool;
645
        }
646

    
647
        /**
648
         * <p>Determines that current drawing process of <code>MapControl</code>'s <code>MapContext</code>'s data must be canceled.</p>
649
         *
650
         * <p>It has no effects if now isn't drawing that graphical information.</p>
651
         *
652
         * <p>At last resort, the particular implementation of each layer in this <code>MapControl</code>'s <code>MapContrext</code>
653
     *   will be that one which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
654
         */
655
        public void cancelDrawing() {
656
                /* if (drawer != null) {
657
                        if (!drawer.isAlive()) {
658
                                return;
659
                        }
660
                }
661
                */
662
                canceldraw.setCanceled(true);
663

    
664
                /* while (!isCancelled) {
665
                        if (!drawer.isAlive()) {
666
                            // Si hemos llegado aqu? con un thread vivo, seguramente
667
                            // no estamos actualizados.
668

669
                                break;
670
                        }
671

672
                }
673
                canceldraw.setCancel(false);
674
                isCancelled = false;
675
        drawerAlive = false; */
676
        }
677

    
678
        /**
679
         * <p>Creates a {@link BufferedImage BufferedImage} image if there was no buffered image, or if
680
         *  its viewport's image height or width is different from this component's size. Once has created
681
         *  a double-buffer, fills it with the vieport's background color, or with <i>white</i> if it had no background color.</p>
682
         *
683
         * <p>If no double-buffered existed, creates a {@link BufferedImage BufferedImage} with the size of this component,
684
         * and as an image with 8-bit RGBA color components packed into integer pixels. That image has a <code>DirectColorModel</code> with alpha.
685
         * The color data in that image is considered not to be premultiplied with alpha.</p>
686
         *
687
         * <p>Once has created and filled the new inner <code>MapControl</code>'s double-buffer, changes the status to
688
         * <code>OUTDATED</code>.</p>
689
         *
690
         * @return <code>true</code> if has created and filled a new double-buffer for this <code>MapControl</code> instance; otherwise <code>false</code>
691
         */
692
    private boolean adaptToImageSize()
693
    {
694
        if ((image == null) || (vp.getImageWidth() != this.getWidth()) || (vp.getImageHeight() != this.getHeight()))
695
        {
696
            image = new BufferedImage(this.getWidth(), this.getHeight(),
697
                    BufferedImage.TYPE_INT_ARGB);
698
            // ESTILO MAC
699
//                image = GraphicsEnvironment.getLocalGraphicsEnvironment()
700
//                                .getDefaultScreenDevice().getDefaultConfiguration()
701
//                                .createCompatibleImage(this.getWidth(), this.getHeight());
702
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
703
            getMapContext().getViewPort().refreshExtent();
704

    
705

    
706
            Graphics gTemp = image.createGraphics();
707
            Color theBackColor = vp.getBackColor();
708
            if (theBackColor == null)
709
                gTemp.setColor(Color.WHITE);
710
            else
711
                gTemp.setColor(theBackColor);
712

    
713
            gTemp.fillRect(0,0,getWidth(), getHeight());
714
            gTemp.dispose();
715
            status = DESACTUALIZADO;
716
            // g.drawImage(image,0,0,null);
717
            return true;
718
        }
719
        return false;
720
    }
721

    
722
        /**
723
         * <p>Paints the graphical information of this component using a double buffer.</p>
724
         *
725
         * <p>If the double buffer wasn't created, creates a new one.</p>
726
         *
727
         * <p>Paints the component according the following algorithm:
728
         * <br>
729
         *  &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
730
         *  &nbsp &nbsp If there is no <i>double buffer</i>:<br>
731
         *  &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the <code>MapControl</code> instance, delegates
732
         *   the drawing process to that behavior, calling: <code><i>behavior_instance</i>.paintComponent(g)</code> &nbsp .<br>
733
         *  &nbsp &nbsp &nbsp Else, repaints the current graphical information quickly calling: <code>g.drawImage(image,0,0,null)</code> &nbsp .<br>
734
         *  &nbsp Else, (<i>status</i> is <i>OUTDATED</i>, or <i>ONLY_GRAPHICS</i>): executes a quickly repaint of the previous information calling <code>g.drawImage(image,0,0,null)</code>, and creates
735
         *   a <i>painting request</i> to delegate the heavy drawing process to the {@link Drawer2 Drawer2}'s worker thread, according the <i>SingleWorketThread</i> pattern, starting a timer to update
736
         *   (invoking <code>repaint()</code> that comprises invoke this method) the view every delay of 360 ms. during the the process drawing.</p>
737
         *
738
           * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
739
           * @see Drawer2
740
         */
741
        protected void paintComponent(Graphics g) {
742
        adaptToImageSize();
743
        /* if (status == FAST_PAINT) {
744
            System.out.println("FAST_PAINT");
745
            g.drawImage(image,0,0,null);
746
            status = ACTUALIZADO;
747
            return;
748
        } */
749
        // System.out.println("PINTANDO MAPCONTROL" + this);
750
                if (status == ACTUALIZADO) {
751
                        // LWS logger.debug("Dibujando la imagen obtenida");
752

    
753
                        /*
754
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
755
                         * en dicho behaviour
756
                         */
757
            if (image != null)
758
            {
759
                if (currentMapTool != null)
760
                    currentMapTool.paintComponent(g);
761
                else
762
                    g.drawImage(image,0,0,null);
763

    
764
                                // System.out.println("Pinto ACTUALIZADO");
765
                        }
766
                } else if ((status == DESACTUALIZADO)
767
                || (status == ONLY_GRAPHICS)) {
768
                        // LWS System.out.println("DESACTUALIZADO: Obteniendo la imagen de la cartograf?a");
769
                        /* if (isOpaque())
770
                        {
771
                            if (image==null)
772
                            {
773
                                g.setColor(vp.getBackColor());
774
                                g.fillRect(0,0,getWidth(), getHeight());
775
                            }
776
                            // else g.drawImage(image,0,0,null);
777
                        } */
778
            // cancelDrawing();
779
                        //Se crea la imagen con el color de fonde deseado
780
                        /* if (image == null)
781
                        {
782
                                image = new BufferedImage(this.getWidth(), this.getHeight(),
783
                                                BufferedImage.TYPE_INT_ARGB);
784
                                vp.setImageSize(new Dimension(getWidth(), getHeight()));
785
                                Graphics gTemp = image.createGraphics();
786
                            Color theBackColor = vp.getBackColor();
787
                            if (theBackColor == null)
788
                                gTemp.setColor(Color.WHITE);
789
                            else
790
                                gTemp.setColor(theBackColor);
791

792
                                gTemp.fillRect(0,0,getWidth(), getHeight());
793
                                gTemp.dispose();
794
                                // g.drawImage(image,0,0,null);
795
                                System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
796
                        } */
797
            // else
798
            // {
799

    
800

    
801
            // if (image != null)
802
            //  {
803
                g.drawImage(image,0,0,null);
804

    
805
                drawer2.put(new PaintingRequest());
806
                timer.start();
807
            /* }
808
            else
809
                return; */
810
            // }
811

    
812
            /* if (drawerAlive == false)
813
            {
814
                drawer = new Drawer(image, canceldraw);
815
                drawer.start();
816
                        //Se lanza el tread de dibujado
817
            } */
818

    
819
                        // status = ACTUALIZADO;
820
                }
821
        }
822

    
823
        /**
824
         * <p>Gets the {@link BufferedImage BufferedImage} used to accelerate the draw of new ''frames'' with changes,
825
         * or new graphical items in this component.</p>
826
         *
827
         * @return double buffered image used by this component to accelerate the draw of its graphical information, or
828
         * <code>null</code> if isn't already created
829
         *
830
         * @see BufferedImage
831
         */
832
        public BufferedImage getImage() {
833
                return image;
834
        }
835

    
836
        /**
837
         * <p>Forces repaint all visible graphical information in this component.</p>
838
         *
839
         * <p>If <code>doClear == true</code>, before repainting, clears the background color, with the
840
         *  inner viewport's background color.</p>
841
         *
842
         * @param doClear <code>true</code> if needs clearing the background color before drawing the map
843
         *
844
         * @see #cancelDrawing()
845
         * @see FLayers#setDirty(boolean)
846
         */
847
        public void drawMap(boolean doClear) {
848
                cancelDrawing();
849
                //System.out.println("drawMap con doClear=" + doClear);
850
        status = DESACTUALIZADO;
851
        getMapContext().getLayers().setDirty(true);
852
                if (doClear)
853
        {
854
            // image = null; // Se usa para el PAN
855
            if (image != null)
856
            {
857
                Graphics2D g = image.createGraphics();
858
                Color theBackColor = vp.getBackColor();
859
                if (theBackColor == null)
860
                    g.setColor(Color.WHITE);
861
                else
862
                    g.setColor(theBackColor);
863
                g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight());
864
                g.dispose();
865
            }
866
        }
867
                repaint();
868
        }
869

    
870

    
871
        /**
872
         * <p>Cancels any current drawing process, changing the status to <code>OUTDATED</code>, and forcing
873
         * repaint only the layers dirty.</p>
874
         *
875
         * @see #cancelDrawing()
876
         */
877
        public void rePaintDirtyLayers()
878
        {
879
                cancelDrawing();
880
        status = DESACTUALIZADO;
881
        repaint();
882
        }
883

    
884
        /**
885
         * <p>Cancels any current drawing process, changing the status to <code>ONLY_GRAPHICS</code>, and forcing
886
         * repaint only the graphical layer of the <code>MapContext</code>.</p>
887
         */
888
    public void drawGraphics() {
889
        status = ONLY_GRAPHICS;
890
        repaint();
891
    }
892

    
893
        /**
894
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
895
         */
896
        public void componentHidden(ComponentEvent e) {
897
        }
898

    
899
        /**
900
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
901
         */
902
        public void componentMoved(ComponentEvent e) {
903
        }
904

    
905
        /**
906
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
907
         */
908
        public void componentResized(ComponentEvent e) {
909
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
910
                                BufferedImage.TYPE_INT_ARGB);
911
                Graphics gTemp = image.createGraphics();
912
                gTemp.setColor(vp.getBackColor());
913
                gTemp.fillRect(0,0,getWidth(), getHeight());
914
        System.out.println("MapControl resized");
915
            // image = null;
916
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
917
                getMapContext().getViewPort().setScale(); */
918
                // drawMap(true);
919
        }
920

    
921
        /**
922
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
923
         */
924
        public void componentShown(ComponentEvent e) {
925
        }
926

    
927
        /**
928
         * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
929
         */
930
        public void addExceptionListener(ExceptionListener o) {
931
                exceptionHandlingSupport.addExceptionListener(o);
932
        }
933

    
934
        /**
935
         * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
936
         */
937
        public boolean removeExceptionListener(ExceptionListener o) {
938
                return exceptionHandlingSupport.removeExceptionListener(o);
939
        }
940

    
941
        /**
942
         * @see ExceptionHandlingSupport#throwException(Throwable)
943
         */
944
        protected void throwException(Throwable t) {
945
                exceptionHandlingSupport.throwException(t);
946
        }
947

    
948
        /**
949
         * <p>Represents each <code>MapControl</code>'s data painting request.</p>
950
         *
951
         * <p>The request will be attended by a <code>Drawer2</code>, which will hold it since the <code>Drawer2</code>'s worker
952
         *  takes it, or arrives a new painting request, which will replace it.</p>
953
         */
954
    private class PaintingRequest
955
    {
956
            /**
957
             * <p>Creates a new <code>PaintingRequest</p> instance.</p>
958
             */
959
        public PaintingRequest()
960
        {
961
        }
962

    
963
        /**
964
         * <p><code>MapControl</code> paint process:</p>
965
         *
966
         * <p>
967
         *  <ul>
968
         *   <li><i>1.- </i>Cancels all previous <code>MapControl</code>'s drawing processes.</li>
969
         *   <li><i>2.- </i>If <i>status</i> was OUTDATED:
970
         *    <ul>
971
         *     <li><i>2.1.- </i>Fills the background color with viewport's background color, or <i>white</i> if it was undefined.</li>
972
         *     <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>.</li>
973
         *     <li><i>2.3.- </i>If <code>canceldraw.isCanceled()</code>
974
         *      <ul>
975
         *       <li><i>2.3.1.- </i>Sets <i>status</i> to OUTDATED.</li>
976
         *       <li><i>2.3.2.- </i>Sets <i>dirty</i> all layers stored in <i>MapContext</i>.</li>
977
         *      </ul>
978
         *     </li>
979
         *     <li><i>2.4.- </i>Else, sets <i>status</i> to UPDATED.</li>
980
         *    </ul>
981
         *   </li>
982
         *   <li><i>3.- </i>Else, if <i>status</i> was ONLY_GRAPHICS:
983
         *    <ul>
984
         *     <li><i>3.1.- </i>Sets <i>status</i> to UPDATED.</li>
985
         *     <li><i>3.2.- </i>Notifies <i>MapContext</i> to be drawn invoking: <code>mapContext.drawGraphics(double-buffer, double-buffer's buffer, shared cancel-draw object, mapContext.getScaleView());</code>.</li>
986
         *    </ul>
987
         *   </li>
988
         *   <li><i>4.- </i>Stops the <i>timer</i>.</li>
989
         *   <li><i>5.- </i>Repaints this component invoking: <code>repaint();</code></li>
990
         *  </ul>
991
         * </p>
992
         *
993
         * @see #cancelDrawing()
994
         * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
995
         * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
996
         *
997
         * @see ViewPort
998
         */
999
        public void paint()
1000
        {
1001
            try
1002
            {
1003
                    canceldraw.setCanceled(false);
1004
                /* if (image == null)
1005
                {
1006
                    image = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
1007
                            BufferedImage.TYPE_INT_ARGB);
1008
                    Graphics gTemp = image.createGraphics();
1009
                    Color theBackColor = vp.getBackColor();
1010
                    if (theBackColor == null)
1011
                        gTemp.setColor(Color.WHITE);
1012
                    else
1013
                        gTemp.setColor(theBackColor);
1014

1015
                    gTemp.fillRect(0,0,getWidth(), getHeight());
1016
                    gTemp.dispose();
1017
                    // g.drawImage(image,0,0,null);
1018
                    System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
1019
                } */
1020
                Graphics2D g = image.createGraphics();
1021

    
1022
                ViewPort viewPort = mapContext.getViewPort();
1023

    
1024
                if (status == DESACTUALIZADO)
1025
                {
1026
                        Graphics2D gTemp = image.createGraphics();
1027
                    Color theBackColor = viewPort.getBackColor();
1028
                    if (theBackColor == null)
1029
                        gTemp.setColor(Color.WHITE);
1030
                    else
1031
                        gTemp.setColor(theBackColor);
1032
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1033
                    // ESTILO MAC
1034
//                  BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
1035
//                          BufferedImage.TYPE_INT_ARGB);
1036
          //
1037
//                  mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
1038
//                  g.drawImage(imgMac, 0, 0, null);
1039
                  // FIN ESTILO MAC
1040
                  // SIN MAC:
1041

    
1042
                  mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
1043
                  if (!canceldraw.isCanceled()){
1044
                          status=ACTUALIZADO;
1045
                 }else{
1046
                          status=DESACTUALIZADO;
1047
                          getMapContext().getLayers().setDirty(true);
1048
                  }
1049

    
1050
                }
1051
                else if (status == ONLY_GRAPHICS)
1052
                {
1053
                    status = ACTUALIZADO;
1054
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
1055

    
1056
                }
1057

    
1058

    
1059
                // status = FAST_PAINT;
1060
              //  drawerAlive = false;
1061
                timer.stop();
1062
                repaint();
1063

    
1064

    
1065
            } catch (Throwable e) {
1066
                timer.stop();
1067
              //  isCancelled = true;
1068
                e.printStackTrace();
1069
                throwException(e);
1070
            } finally {
1071
            }
1072
        }
1073
    }
1074

    
1075
    /**
1076
     * <p>An instance of <code>Drawer2</code> could manage all <code>MapControl</code> painting requests.</p>
1077
     *
1078
     * <p>Based on the <i>WorkerThread</i> software pattern, creates a worker thread that will attend sequentially
1079
     *  the current waiting painting request, after finishing the previous (that could be by a cancel action).</p>
1080
     *
1081
     * <p>All new {@link PaintingRequest PaintingRequest} generated will be stored as <i>waiting requests</i> since the worker
1082
     * attends it.</p>
1083
     *
1084
     * <p>If a worker finished and there was no <i>painting request</i>, the worker would be set to wait until any
1085
     *  <i>painting request</i> would be put.</p>
1086
     *
1087
     * @author fjp
1088
     */
1089
    public class Drawer2
1090
    {
1091
        // Una mini cola de 2. No acumulamos peticiones de dibujado
1092
        // dibujamos solo lo ?ltimo que nos han pedido.
1093

    
1094

    
1095
            /**
1096
             * <p>Painting request that's been attended by the <code>Drawer2</code>'s worker.</p>
1097
             *
1098
             * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1099
             * @see #take()
1100
             */
1101
            private PaintingRequest paintingRequest;
1102

    
1103
            /**
1104
             * <p>Painting request waiting to be attended by the <code>Drawer2</code>'s worker.</p>
1105
             *
1106
             * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1107
             * @see #take()
1108
             */
1109
            private PaintingRequest waitingRequest;
1110

    
1111
            /**
1112
             * <p>Determines that the <code>Drawer2</code>'s worker is busy attending a painting request.</p>
1113
              *
1114
             * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1115
             * @see #take()
1116
             */
1117
        private boolean waiting;
1118

    
1119
            /**
1120
             * <p>Notifies the <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1121
             *
1122
             * @see #setShutdown(boolean)
1123
             */
1124
        private boolean shutdown;
1125

    
1126
        /**
1127
         * <p>Sets this <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1128
         *
1129
         * @param isShutdown a boolean value
1130
         */
1131
        public void setShutdown(boolean isShutdown)
1132
        {
1133
            shutdown = isShutdown;
1134
        }
1135

    
1136
        /**
1137
         * <p>Creates a new drawer for managing all data painting requests in <code>MapControl</code>.</p>
1138
         *
1139
         * <p>Includes the following steps:
1140
         *  <ul>
1141
         *   <li>By default, there is no <i>current painting request</i>.</li>
1142
         *   <li>By default, there is no <i>waiting painting request</i>.</li>
1143
         *   <li>By default, the worker thread is waiting no <i>painting request</i>.</li>
1144
         *   <li>By default, the worker thread is running.</li>
1145
         *   <li>Creates and starts a worker thread for attending the <i>painting requests</i>.</li>
1146
         *  </ul>
1147
         * </p>
1148
         */
1149
        public Drawer2()
1150
        {
1151
            paintingRequest = null;
1152
            waitingRequest = null;
1153
            waiting = false;
1154
            shutdown = false;
1155
            new Thread(new Worker()).start();
1156
        }
1157

    
1158
        /**
1159
         * <p>Sets a <code>PaintingRequest</code> to be attended by the worker thread of this object. If
1160
         *  this one was waiting, wakes up.</p>
1161
         *
1162
         * <p>All waiting threads will be notified synchronized.</p>
1163
         *
1164
         * @param newPaintRequest
1165
         *
1166
         * @see #take()
1167
         */
1168
        public void put(PaintingRequest newPaintRequest)
1169
        {
1170
            waitingRequest = newPaintRequest;
1171
            if (waiting)
1172
            {
1173
                synchronized (this) {
1174
                    notifyAll();
1175
                }
1176
            }
1177
        }
1178

    
1179
        /**
1180
         * <p>Used by this object's worker, returns the current waiting drawing request, causing current thread
1181
         *  to wait until another thread invokes {@link #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest) #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)},
1182
         *  if there was no waiting request.</p>
1183
         *
1184
         * <p>All threads will access synchronized to the waiting request.</p>
1185
         *
1186
         * @return <code>PaintingRequest</code> that was waiting to be attended
1187
         *
1188
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1189
         */
1190
        public PaintingRequest take()
1191
        {
1192
            if (waitingRequest == null)
1193
            {
1194
                synchronized (this) {
1195
                    waiting = true;
1196
                    try {
1197
                        wait();
1198
                    }
1199
                    catch (InterruptedException ie)
1200
                    {
1201
                        waiting = false;
1202
                    }
1203
                }
1204
            }
1205
            paintingRequest = waitingRequest;
1206
            waitingRequest = null;
1207
            return paintingRequest;
1208
        }
1209

    
1210
        /**
1211
         * <p>Thread for attending painting requests.</p>
1212
         *
1213
         * <p>If there was no double buffer, sets the status to <code>OUTDATED</code> and finishes, otherwise
1214
         *  takes the painting request (it's probably that would wait some time), cancel the previous drawing
1215
         *  process, and starts processing the request.</p>
1216
         *
1217
         * @see Thread
1218
         */
1219
        private class Worker implements Runnable
1220
        {
1221
                /*
1222
                 * (non-Javadoc)
1223
                 * @see java.lang.Runnable#run()
1224
                 */
1225
                public void run()
1226
            {
1227
                while (!shutdown)
1228
                {
1229
                    PaintingRequest p = take();
1230
                    //System.out.println("Pintando");
1231
                    if (image != null){
1232
                            cancelDrawing();
1233
                        p.paint();
1234
                    } else{
1235
                        status = DESACTUALIZADO;
1236
                    }
1237
                }
1238
            }
1239
        }
1240
    }
1241

    
1242
        /**
1243
         * <p><code>Drawer</code> is implemented for drawing the layers of a <code>MapControl</code>'s <i>MapContext</i> instance
1244
         *  as a <i>thread</i> of execution.</p>
1245
         *
1246
         * <p>Draws <code>MapControl</code> according its <i>status</i>:
1247
         *  <ul>
1248
         *   <li><code><i>ONLY_GRAPHICS</i></code>: refreshes only the graphical layer, changing the status to <code><i>UPDATED</i></code>, via
1249
         *    {@linkplain MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double) MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)}.</li>
1250
         *   <li><code><i>OUTDATED</i></code>: refreshes all layers, changing the status to <code><i>UPDATED</i></code>, via
1251
         *    {@linkplain MapContext#draw(BufferedImage, Graphics2D, Cancellable, double) MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)}.</li>
1252
         *  <ul>
1253
         * </p>
1254
         *
1255
         * <p>This drawing process is accelerated by a <code>BufferedImage</code>, and can be canceled.</p>
1256
         *
1257
         * <p>Once the drawing process has finished, the timer stops and this component gets repainted.</p>
1258
         *
1259
         * @deprecated
1260
         * @author Vicente Caballero Navarro
1261
         */
1262
        public class Drawer extends Thread {
1263
                //private Graphics g;
1264

    
1265
                /**
1266
                 * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
1267
                 *
1268
                 * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
1269
                 * Meanwhile, the previous image can be kept showed.</p>
1270
                 *
1271
                 * @see BufferedImage
1272
                 */
1273
                private BufferedImage image = null;
1274

    
1275
                /**
1276
                 * <p>Object to store the flag that notifies the drawing must be canceled or can continue with the process.</p>
1277
                 *
1278
                 * <p>At last resort, the particular implementation of each layer in a <code>MapControl</code>'s <code>MapContrext</code>
1279
         *   will be which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
1280
                 */
1281
                private CancelDraw cancel;
1282
                //private boolean threadCancel = false;
1283

    
1284
                /**
1285
                 * <p>Creates a new <code>Drawer</code> instance.</p>
1286
                 */
1287
                public Drawer(BufferedImage image, CancelDraw cancel)
1288
        {
1289
                        this.image = image;
1290
                        this.cancel = cancel;
1291
         //   drawerAlive = true;
1292
                }
1293

    
1294
                /**
1295
                 * @see java.lang.Runnable#run()
1296
                 * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
1297
                 * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
1298
                 */
1299
                public void run() {
1300
                        try {
1301
                                // synchronized (Drawer.class) {
1302
                                    Graphics2D g = image.createGraphics();
1303

    
1304
                                    ViewPort viewPort = mapContext.getViewPort();
1305
                    if (status == DESACTUALIZADO)
1306
                    {
1307
                                        Color theBackColor = viewPort.getBackColor();
1308
                                        if (theBackColor == null)
1309
                                            g.setColor(Color.WHITE);
1310
                                        else
1311
                                            g.setColor(theBackColor);
1312
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1313
                        status = ACTUALIZADO;
1314
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
1315
                    }
1316
                    else if (status == ONLY_GRAPHICS)
1317
                    {
1318
                        status = ACTUALIZADO;
1319
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
1320
                    }
1321

    
1322
                                        timer.stop();
1323
                    // status = FAST_PAINT;
1324
                  //  drawerAlive = false;
1325
                                        repaint();
1326

    
1327

    
1328

    
1329
                                // }
1330
                        } catch (Throwable e) {
1331
                            timer.stop();
1332
                                //isCancelled = true;
1333
                e.printStackTrace();
1334
                                throwException(e);
1335
                        } finally {
1336
                        }
1337
                }
1338
        }
1339

    
1340
        /**
1341
         * <p>An instance of <code>CancelDraw</code> will be shared by all this <code>MapControl</code>'s <code>MapContext</code> layers,
1342
         *  allowing receive a notification that, when they're been drawn, to be cancelled.</p>
1343
         *
1344
         * @see Cancellable
1345
         *
1346
         * @author Fernando Gonz?lez Cort?s
1347
         */
1348
        public class CancelDraw implements Cancellable {
1349
                /**
1350
                 * <p>Determines if the drawing task must be canceled or not.</p>
1351
                 *
1352
                 * @see #isCanceled()
1353
                 * @see #setCanceled(boolean)
1354
                 */
1355
                private boolean cancel = false;
1356

    
1357
                /**
1358
                 * Creates a new <code>CancelDraw</code> object.
1359
                 */
1360
                public CancelDraw() {
1361
                }
1362

    
1363
                /*
1364
                 * (non-Javadoc)
1365
                 * @see com.iver.utiles.swing.threads.Cancellable#setCanceled(boolean)
1366
                 */
1367
                public void setCanceled(boolean b) {
1368
                        cancel = b;
1369
                }
1370

    
1371
                /*
1372
                 * (non-Javadoc)
1373
                 * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
1374
                 */
1375
                public boolean isCanceled() {
1376
                        return cancel;
1377
                }
1378
        }
1379

    
1380
        /**
1381
         * <p>Listens all kind of mouse events produced in {@link MapControl MapControl}, and invokes its current
1382
         *  map tool <i>({@link MapControl#getCurrentMapTool() MapControl#getCurrentMapTool()}</i> to simulate a behavior.</p>
1383
         *
1384
         * <p>Mouse wheel moved events produce a <i>zoom in</i> operation if wheel rotation is negative, or a <i>zoom out</i>
1385
         *  if its positive. Both will be centered in the position of the mouse, but, meanwhile <i>zoom in</i> operation
1386
         *  applies a factor of 0.9, <i>zoom out</i> operation applies a factor of 1.2</p>
1387
         *
1388
         * <p>Mouse wheel moved events can be produced as much frequently, that between each one, the drawing process could
1389
         *  hadn't finished. This is the reason that, in this situation, cancels always the previous drawing process before
1390
         *  applying a <i>zoom</i> operation, and ignores all new mouse positions that are produced before 1 second.</p>
1391
         *
1392
         * @author Fernando Gonz?lez Cort?s
1393
         */
1394
        public class MapToolListener implements MouseListener, MouseWheelListener,
1395
                MouseMotionListener {
1396

    
1397
                /**
1398
                 * <p>Used to avoid mouse wheel move events closed.</p>
1399
                 *
1400
                 * <p>If a mouse wheel move event is produced
1401
                 */
1402
                long t1;
1403

    
1404
                /**
1405
                 * <p>Position of the mouse, in map coordinates.</p>
1406
                 *
1407
                 * <p>This point coordinates will be used as center of the <i>zoom</i> operation.</p>
1408
                 */
1409
                Point2D pReal;
1410

    
1411
                /**
1412
                 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1413
                 * @see Behavior#mouseClicked(MouseEvent)
1414
                 */
1415
                public void mouseClicked(MouseEvent e) {
1416
                        try {
1417
                                if (currentMapTool != null)
1418
                                    currentMapTool.mouseClicked(e);
1419
                        } catch (BehaviorException t) {
1420
                                throwException(t);
1421
                        }
1422
                }
1423

    
1424
                /**
1425
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1426
                 * @see Behavior#mouseEntered(MouseEvent)
1427
                 */
1428
                public void mouseEntered(MouseEvent e) {
1429
                        try {
1430
                                if (currentMapTool != null)
1431
                                        currentMapTool.mouseEntered(e);
1432
                        } catch (BehaviorException t) {
1433
                                throwException(t);
1434
                        }
1435
                }
1436

    
1437
                /**
1438
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1439
                 * @see Behavior#mouseExited(MouseEvent)
1440
                 */
1441
                public void mouseExited(MouseEvent e) {
1442
                        try {
1443
                                if (currentMapTool != null)
1444
                                    currentMapTool.mouseExited(e);
1445
                        } catch (BehaviorException t) {
1446
                                throwException(t);
1447
                        }
1448
                }
1449

    
1450
                /**
1451
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1452
                 * @see Behavior#mousePressed(MouseEvent)
1453
                 */
1454
                public void mousePressed(MouseEvent e) {
1455
                        try {
1456
                                if (currentMapTool != null)
1457
                                        currentMapTool.mousePressed(e);
1458
                        } catch (BehaviorException t) {
1459
                                throwException(t);
1460
                        }
1461
                }
1462

    
1463
                /**
1464
                 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1465
                 * @see Behavior#mouseReleased(MouseEvent)
1466
                 */
1467
                public void mouseReleased(MouseEvent e) {
1468
                        try {
1469
                                if (currentMapTool != null)
1470
                                        currentMapTool.mouseReleased(e);
1471
                        } catch (BehaviorException t) {
1472
                                throwException(t);
1473
                        }
1474
                }
1475

    
1476
                /**
1477
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
1478
                 * @see Behavior#mouseWheelMoved(MouseWheelEvent)
1479
                 */
1480
                public void mouseWheelMoved(MouseWheelEvent e) {
1481
                        try {
1482
                                if (currentMapTool == null)
1483
                                        return;
1484

    
1485
                                currentMapTool.mouseWheelMoved(e);
1486

    
1487
                                // Si el tool actual no ha consumido el evento
1488
                                // entendemos que quiere el comportamiento por defecto.
1489
                                if (!e.isConsumed())
1490
                                {
1491
                                        // Para usar el primer punto sobre el que queremos centrar
1492
                                        // el mapa, dejamos pasar un segundo para considerar el siguiente
1493
                                        // punto como v?lido.
1494
                                        if (t1 == 0)
1495
                                        {
1496
                                                t1= System.currentTimeMillis();
1497
                                                pReal = vp.toMapPoint(e.getPoint());
1498
                                        }
1499
                                        else
1500
                                        {
1501
                                                long t2 = System.currentTimeMillis();
1502
                                                if ((t2-t1) > 1000)
1503
                                                        t1=0;
1504
                                        }
1505
                                        cancelDrawing();
1506
                                        ViewPort vp = getViewPort();
1507

    
1508

    
1509
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1510
                                                        vp.getAdjustedExtent().getCenterY()); */
1511
                                        int amount = e.getWheelRotation();
1512
                                        double nuevoX;
1513
                                        double nuevoY;
1514
                                        double factor;
1515

    
1516
                                        if (amount < 0) // nos acercamos
1517
                                        {
1518
                                                factor = 0.9;
1519
                                        } else // nos alejamos
1520
                                        {
1521
                                                factor = 1.2;
1522
                                        }
1523
                                        Rectangle2D.Double r = new Rectangle2D.Double();
1524
                                        if (vp.getExtent() != null) {
1525
                                                nuevoX = pReal.getX()
1526
                                                                - ((vp.getExtent().getWidth() * factor) / 2.0);
1527
                                                nuevoY = pReal.getY()
1528
                                                                - ((vp.getExtent().getHeight() * factor) / 2.0);
1529
                                                r.x = nuevoX;
1530
                                                r.y = nuevoY;
1531
                                                r.width = vp.getExtent().getWidth() * factor;
1532
                                                r.height = vp.getExtent().getHeight() * factor;
1533

    
1534
                                                vp.setExtent(r);
1535
                                        }
1536

    
1537

    
1538
                                }
1539
                        } catch (BehaviorException t) {
1540
                                throwException(t);
1541
                        }
1542
                }
1543

    
1544
                /**
1545
                 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1546
                 * @see Behavior#mouseDragged(MouseEvent)
1547
                 */
1548
                public void mouseDragged(MouseEvent e) {
1549
                        try {
1550
                                if (currentMapTool != null)
1551
                                        currentMapTool.mouseDragged(e);
1552
                        } catch (BehaviorException t) {
1553
                                throwException(t);
1554
                        }
1555
                }
1556

    
1557
                /**
1558
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
1559
                 * @see Behavior#mouseMoved(MouseEvent)
1560
                 */
1561
                public void mouseMoved(MouseEvent e) {
1562
                        try {
1563
                                if (currentMapTool != null)
1564
                                        currentMapTool.mouseMoved(e);
1565
                        } catch (BehaviorException t) {
1566
                                throwException(t);
1567
                        }
1568
                }
1569
        }
1570

    
1571
        /**
1572
         * <p<code>MapContextListener</code> listens all events produced in a <code>MapControl</code>'s <code>MapContext</code>
1573
         * object during an atomic period of time, and sets it to dirty, <i>executing <code>drawMap(false)</code>, if any of the
1574
         * following conditions is accomplished</i>:
1575
         * <ul>
1576
         *  <li>Any of the <code>LayerEvent</code> in the <code>AtomicEvent</code> parameter notifies a <i>visibility change</i>.</li>
1577
         *  <li>There is at least one <code>ColorEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1578
         *  <li>There is at least one <code>ExtentEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1579
         *  <li>Any of the <code>LayerCollectionEvent</code> in the <code>AtomicEvent</code> parameter notifies that a driver's layer has reloaded it successfully.</li>
1580
         *  <li>There is at least one <code>LegendEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1581
         *  <li>There is at least one <code>SelectionEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1582
         * </ul>
1583
         * </p>
1584
         *
1585
         * @author Fernando Gonz?lez Cort?s
1586
         */
1587
        public class MapContextListener implements AtomicEventListener {
1588
                /**
1589
                 * @see org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener#atomicEvent(org.gvsig.fmap.mapcontext.events.AtomicEvent)
1590
                 */
1591
                public void atomicEvent(AtomicEvent e) {
1592
                        boolean redraw = false;
1593
                        LayerEvent[] layerEvents = e.getLayerEvents();
1594

    
1595
                        for (int i = 0; i < layerEvents.length; i++) {
1596
                                if (layerEvents[i].getProperty().equals("visible")) {
1597
                                        redraw = true;
1598
                                }
1599
                        }
1600

    
1601
                        if (e.getColorEvents().length > 0) {
1602
                                redraw = true;
1603
                        }
1604

    
1605
                        if (e.getExtentEvents().length > 0) {
1606
                                redraw = true;
1607
                        }
1608

    
1609
                        if (e.getProjectionEvents().length > 0) {
1610
                                //redraw = true;
1611
                        }
1612

    
1613

    
1614
                        LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1615
                        if (aux.length > 0) {
1616
                                for (int i=0; i < aux.length; i++)
1617
                                {
1618
                                        if (aux[i].getAffectedLayer().getFLayerStatus().isDriverLoaded())
1619
                                        {
1620
                                                redraw = true;
1621
                                                break;
1622
                                        }
1623
                                }
1624

    
1625
                        }
1626

    
1627
                        if (e.getLegendEvents().length > 0) {
1628
                                redraw = true;
1629
                        }
1630

    
1631
                        if (e.getSelectionEvents().length > 0) {
1632
                                redraw = true;
1633
                        }
1634

    
1635
                        if (redraw) {
1636
                //System.out.println("MapContextListener redraw");
1637
                                MapControl.this.drawMap(false);
1638
                        }
1639
                }
1640
        }
1641

    
1642
        /**
1643
         * <p>Gets the <code>ViewPort</code> of this component's {@link MapContext MapContext} .</p>
1644
         *
1645
         * @see MapContext#getViewPort()
1646
         */
1647
        public ViewPort getViewPort() {
1648
                return vp;
1649
        }
1650

    
1651
        /**
1652
         * <p>Returns all registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
1653
         *
1654
         * @return registered <code>Behavior</code> to this <code>MapControl</code>
1655
         *
1656
         * @see #addMapTool(String, Behavior)
1657
         * @see #addMapTool(String, Behavior[])
1658
         * @see #getMapToolsKeySet()
1659
         * @see #hasTool(String)
1660
         */
1661
        public HashMap getNamesMapTools() {
1662
                return namesMapTools;
1663
        }
1664

    
1665
        /*
1666
         * (non-Javadoc)
1667
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
1668
         */
1669
        public void commandRepaint() {
1670
                drawMap(false);
1671
        }
1672

    
1673
        /*
1674
         * (non-Javadoc)
1675
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
1676
         */
1677
        public void commandRefresh() {
1678
                // TODO Auto-generated method stub
1679
        }
1680

    
1681
        /**
1682
         * <p>Equivalent operation to <i>undo</i>.</p>
1683
         *
1684
         * <p>Exchanges the previous tool with the current one.</p>
1685
         *
1686
         * @see #addMapTool(String, Behavior)
1687
         * @see #addMapTool(String, Behavior[])
1688
         * @see #setTool(String)
1689
         */
1690
        public void setPrevTool() {
1691
                setTool(prevTool);
1692
        }
1693

    
1694
        /**
1695
         * <p>Executes a <i>zoom in</i> operation centered at the center of the extent.</p>
1696
         *
1697
         * <p>This implementation is designed for being invoked outside a <code>Behavior</code>, for example
1698
         *  by an action of pressing a button; and simulates that the event has been produced by
1699
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1700
         *  <code>MapControl</code> object that's responsible for the <i>zoom in</i> operation.</p>
1701
         *
1702
         * @see #zoomOut()
1703
         */
1704
        public void zoomIn() {
1705
                getMapContext().clearAllCachingImageDrawnLayers();
1706
                Behavior mapTool = (Behavior) namesMapTools.get("zoomIn");
1707
                ViewPort vp=getViewPort();
1708
                Rectangle2D r=getViewPort().getAdjustedExtent();
1709
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1710
                MouseEvent e=new MouseEvent((Component)this,MouseEvent.MOUSE_RELEASED,MouseEvent.ACTION_EVENT_MASK,MouseEvent.BUTTON1,(int)pCenter.getX(),(int)pCenter.getY(),1,true,MouseEvent.BUTTON1);
1711
                try {
1712
                        mapTool.mousePressed(e);
1713
                        mapTool.mouseReleased(e);
1714
                } catch (BehaviorException t) {
1715
                        throwException(t);
1716
                }
1717
        }
1718

    
1719
        /**
1720
         * <p>Executes a <i>zoom out</i> operation centered at the center of the extent.</p>
1721
         *
1722
         * <p>This implementation is thought for being invoked outside a <code>Behavior</code>, for example
1723
         *  by an action of pressing a button, and simulates that the event has been produced by
1724
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1725
         *  <code>MapControl</code> object that's responsible for the <i>zoom out</i> operation.</p>
1726
         *
1727
         * @see #zoomIn()
1728
         */
1729
        public void zoomOut() {
1730
                getMapContext().clearAllCachingImageDrawnLayers();
1731
                Behavior mapTool = (Behavior) namesMapTools.get("zoomOut");
1732
                ViewPort vp=getViewPort();
1733
                Rectangle2D r=getViewPort().getAdjustedExtent();
1734
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1735
                MouseEvent e=new MouseEvent((Component)this,MouseEvent.MOUSE_RELEASED,MouseEvent.ACTION_EVENT_MASK,MouseEvent.BUTTON1,(int)pCenter.getX(),(int)pCenter.getY(),1,true,MouseEvent.BUTTON1);
1736
                try {
1737
                        mapTool.mousePressed(e);
1738
                        mapTool.mouseReleased(e);
1739
                } catch (BehaviorException t) {
1740
                        throwException(t);
1741
                }
1742
        }
1743

    
1744
        /**
1745
         * <p>Returns the listener used to catch all mouse events produced in this <code>MapControl</code> instance
1746
         *  and that redirects the calls to the current map tool.</p>
1747
         *
1748
         * @return the map tool listener used
1749
         */
1750
        public MapToolListener getMapToolListener() {
1751
                return mapToolListener;
1752
        }
1753

    
1754
//         mapTool can be null, for instance, in 3D's navigation tools
1755
        /**
1756
         * <p>Sets <code>mapTool</code> as this <code>MapControl</code>'s current map tool.
1757
         *
1758
         * @param mapTool a map tool, or <code>null</code> to disable the interaction with the user
1759
         *
1760
         * @see #getCurrentMapTool()
1761
         * @see #getCurrentTool()
1762
         * @see #setTool(String)
1763
         * @see #setPrevTool()
1764
         * @see #addMapTool(String, Behavior)
1765
         * @see #addMapTool(String, Behavior[])
1766
         */
1767
        public void setCurrentMapTool(Behavior mapTool ){
1768
                currentMapTool = mapTool;
1769
        }
1770

    
1771
        /**
1772
         * <p>Sets the delay to the timer that refreshes this <code>MapControl</code> instance.</p>
1773
         *
1774
         * <p><code>Delay (in ms) = 1000 / getDrawFrameRate()</code></p>
1775
         *
1776
         * @see #getDrawFrameRate()
1777
         * @see #setDrawFrameRate(int)
1778
         */
1779
        public void applyFrameRate() {
1780
                if (getDrawFrameRate()>0) {
1781
                        timer.setDelay(1000/getDrawFrameRate());
1782
                }
1783
        }
1784

    
1785
        /**
1786
         * <p>Returns the draw frame rate.</p>
1787
         *
1788
         * <p>Draw frame rate is the number of repaints of this <code>MapControl</code> instance that timer invokes per second.</p>
1789
         *
1790
         * @return number of repaints of this <code>MapControl</code> instance that timer invokes per second
1791
         *
1792
         * @see #applyFrameRate()
1793
         * @see #setDrawFrameRate(int)
1794
         */
1795
        public static int getDrawFrameRate() {
1796
                return drawFrameRate;
1797
        }
1798

    
1799
        /**
1800
         * <p>Sets the draw frame rate.</p>
1801
         *
1802
         * <p>Draw frame rate is the number of repaints of this <code>MapControl</code> instance that timer invokes per second.</p>
1803
         *
1804
         * @param drawFrameRate number of repaints of this <code>MapControl</code> instance that timer invokes per second
1805
         *
1806
         * @see #applyFrameRate()
1807
         * @see #getDrawFrameRate()
1808
         */
1809
        public static void setDrawFrameRate(int drawFrameRate) {
1810
                MapControl.drawFrameRate = drawFrameRate;
1811
        }
1812

    
1813
        /**
1814
         * <p>Determines if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1815
         *
1816
         * @return <code>true</code> if its enabled; otherwise <code>false</code>
1817
         */
1818
        public static boolean isDrawAnimationEnabled() {
1819
                return drawAnimationEnabled;
1820
        }
1821

    
1822
        /**
1823
         * <p>Sets if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1824
         *
1825
         * @param drawAnimationEnabled <code>true</code> to enable the mode; otherwise <code>false</code>
1826
         */
1827
        public static void setDrawAnimationEnabled(boolean drawAnimationEnabled) {
1828
                MapControl.drawAnimationEnabled = drawAnimationEnabled;
1829
        }
1830

    
1831
        /**
1832
         * <p>Gets the shared object that determines if a drawing process must be cancelled or can continue.</p>
1833
         *
1834
         * @return the shared object that determines if a drawing process must be cancelled or can continue
1835
         */
1836
        public CancelDraw getCanceldraw() {
1837
                return canceldraw;
1838
        }
1839

    
1840
        /**
1841
         * <p>Gets the tool used in combination with the current tool of this <code>MapControl</code>.</p>
1842
         *
1843
         * @return the tool used in combination with the <code>currentMapTool</code>; <code>null</code> if there is
1844
         *  no combined tool
1845
         */
1846
        public Behavior getCombinedTool() {
1847
                return combinedTool;
1848
        }
1849

    
1850
        /**
1851
         * <p>Sets a tool to be used in combination with the current tool of this <code>MapControl</code>.</p>
1852
         *
1853
         * @param combinedTool a tool to be used in combination with the current tool of <code>MapControl</code>
1854
         */
1855
        public void setCombinedTool(Behavior combinedTool) {
1856
                this.combinedTool = combinedTool;
1857

    
1858
                if (currentMapTool == null)
1859
                        return;
1860

    
1861
                if ((currentMapTool != null) && (currentMapTool instanceof CompoundBehavior)) {
1862
                        ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, combinedTool.getListener().cancelDrawing());
1863
                }
1864
                else {
1865
                        currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool, combinedTool});
1866
                }
1867

    
1868
        }
1869

    
1870
        /**
1871
         * <p>Removes the tool used in combination with the current tool of this <code>MapControl</code>.</p>
1872
         */
1873
        public void removeCombinedTool() {
1874
                if ((currentMapTool != null) && (currentMapTool instanceof CompoundBehavior)) {
1875
                                ((CompoundBehavior)currentMapTool).removeMapBehavior(combinedTool);
1876
                }
1877

    
1878
                combinedTool = null;
1879
        }
1880
}