Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / MapControl.java @ 22363

History | View | Annotate | Download (64.7 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 com.iver.cit.gvsig.fmap;
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

    
68
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
69
import com.iver.cit.gvsig.fmap.edition.commands.CommandListener;
70
import com.iver.cit.gvsig.fmap.layers.LayerCollectionEvent;
71
import com.iver.cit.gvsig.fmap.layers.LayerEvent;
72
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
73
import com.iver.cit.gvsig.fmap.tools.CompoundBehavior;
74
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
75
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
76
import com.iver.utiles.exceptionHandling.ExceptionListener;
77
import com.iver.utiles.swing.threads.Cancellable;
78

    
79

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

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

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

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

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

    
208
    // public static final int FAST_PAINT = 3;
209
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
210

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

    
220
    //private boolean drawerAlive = false;
221

    
222

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

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

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

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

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

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

    
288
    //private boolean isCancelled = true;
289

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

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

    
316
    //private Drawer drawer;
317

    
318
        /**
319
         * <p>Manager of all <code>MapControl</code> painting requests.</p>
320
         */
321
    private Drawer2 drawer2;
322

    
323
    // private boolean firstDraw = true;
324

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

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

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

    
353
    /**
354
     * <p>Name of the previous tool used.</p>
355
     */
356
        protected String prevTool;
357

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

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

    
368
        /**
369
         * <p>Creates a new <code>MapControl</code> instance with the following characteristics:
370
         * <ul>
371
         *  <li><i>Name</i>: MapControl .</li>
372
         *  <li>Disables the double buffer of <code>JComponent</code> .</li>
373
         *  <li>Sets opaque <i>(see {@link JComponent#setOpaque(boolean)} )</i>. </li>
374
         *  <li>Sets its status to <code>OUTDATED</code> .</li>
375
         *  <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>
376
         *  <li>Creates a new {@link MapContext MapContext} with a new {@link ViewPort ViewPort} in the projection <i>"EPSG:23030"</i> .</li>
377
         *  <li>Creates a new {@link CommandListener CommandListener} for edition operations.</li>
378
         *  <li>Creates a new {@link MapToolListener MapToolListener}, and associates it as a listener of whatever kind of mouse events produced in this component.</li>
379
         *  <li>Creates a new {@link Drawer2 Drawer2} for managing the painting requests.</li>
380
         *  <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
381
         *   <code>drawAnimationEnabled</code>.</li>
382
         * </ul>
383
         * </p>
384
         */
385
        public MapControl() {
386
                this.setName("MapControl");
387
                setDoubleBuffered(false);
388
                setOpaque(true);
389
                status = DESACTUALIZADO;
390

    
391
                //Clase usada para cancelar el dibujado
392
                canceldraw = new CancelDraw();
393

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

    
401
                //eventos
402
                this.addComponentListener(this);
403
                this.addMouseListener(mapToolListener);
404
                this.addMouseMotionListener(mapToolListener);
405
                this.addMouseWheelListener(mapToolListener);
406

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

    
413
                                                if (drawAnimationEnabled) {
414
                                                        MapControl.this.repaint();
415
                                                }
416
                                        }
417
                                });
418
        }
419

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

    
443
                mapContext = model;
444

    
445
                if (mapContext.getViewPort() == null) {
446
                        mapContext.setViewPort(vp);
447
                } else {
448
                        vp = mapContext.getViewPort();
449

    
450
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
451
                        //System.err.println("Viewport en setMapContext:" + vp);
452
                }
453

    
454
                mapContext.addAtomicEventListener(mapContextListener);
455

    
456
                status = DESACTUALIZADO;
457
        }
458

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

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

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

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

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

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

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

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

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

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

    
613
                this.setCursor(mapTool.getCursor());
614
        }
615

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

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

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

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

666
                                break;
667
                        }
668

669
                }
670
                canceldraw.setCancel(false);
671
                isCancelled = false;
672
        drawerAlive = false; */
673
        }
674

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

    
702

    
703
            Graphics gTemp = image.createGraphics();
704
            Color theBackColor = vp.getBackColor();
705
            if (theBackColor == null)
706
                gTemp.setColor(Color.WHITE);
707
            else
708
                gTemp.setColor(theBackColor);
709

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

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

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

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

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

    
797

    
798
            // if (image != null)
799
            //  {
800
                g.drawImage(image,0,0,null);
801

    
802
                drawer2.put(new PaintingRequest());
803
                timer.start();
804
            /* }
805
            else
806
                return; */
807
            // }
808

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

    
816
                        // status = ACTUALIZADO;
817
                }
818
        }
819

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

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

    
867

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

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

    
890
        /**
891
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
892
         */
893
        public void componentHidden(ComponentEvent e) {
894
        }
895

    
896
        /**
897
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
898
         */
899
        public void componentMoved(ComponentEvent e) {
900
        }
901

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

    
918
        /**
919
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
920
         */
921
        public void componentShown(ComponentEvent e) {
922
        }
923

    
924
        /**
925
         * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
926
         */
927
        public void addExceptionListener(ExceptionListener o) {
928
                exceptionHandlingSupport.addExceptionListener(o);
929
        }
930

    
931
        /**
932
         * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
933
         */
934
        public boolean removeExceptionListener(ExceptionListener o) {
935
                return exceptionHandlingSupport.removeExceptionListener(o);
936
        }
937

    
938
        /**
939
         * @see ExceptionHandlingSupport#throwException(Throwable)
940
         */
941
        protected void throwException(Throwable t) {
942
                exceptionHandlingSupport.throwException(t);
943
        }
944

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

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

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

    
1019
                ViewPort viewPort = mapContext.getViewPort();
1020

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

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

    
1047
                }
1048
                else if (status == ONLY_GRAPHICS)
1049
                {
1050
                    status = ACTUALIZADO;
1051
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
1052

    
1053
                }
1054

    
1055

    
1056
                // status = FAST_PAINT;
1057
              //  drawerAlive = false;
1058
                timer.stop();
1059
                repaint();
1060

    
1061

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

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

    
1091

    
1092
            /**
1093
             * <p>Painting request that's been attended by the <code>Drawer2</code>'s worker.</p>
1094
             *
1095
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1096
             * @see #take()
1097
             */
1098
            private PaintingRequest paintingRequest;
1099

    
1100
            /**
1101
             * <p>Painting request waiting to be attended by the <code>Drawer2</code>'s worker.</p>
1102
             *
1103
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1104
             * @see #take()
1105
             */
1106
            private PaintingRequest waitingRequest;
1107

    
1108
            /**
1109
             * <p>Determines that the <code>Drawer2</code>'s worker is busy attending a painting request.</p>
1110
              *
1111
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1112
             * @see #take()
1113
             */
1114
        private boolean waiting;
1115

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

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

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

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

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

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

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

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

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

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

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

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

    
1319
                                        timer.stop();
1320
                    // status = FAST_PAINT;
1321
                  //  drawerAlive = false;
1322
                                        repaint();
1323

    
1324

    
1325

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

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

    
1354
                /**
1355
                 * Creates a new <code>CancelDraw</code> object.
1356
                 */
1357
                public CancelDraw() {
1358
                }
1359

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

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

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

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

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

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

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

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

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

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

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

    
1482
                                currentMapTool.mouseWheelMoved(e);
1483

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

    
1505

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

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

    
1531
                                                vp.setExtent(r);
1532
                                        }
1533

    
1534

    
1535
                                }
1536
                        } catch (BehaviorException t) {
1537
                                throwException(t);
1538
                        }
1539
                }
1540

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

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

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

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

    
1598
                        if (e.getColorEvents().length > 0) {
1599
                                redraw = true;
1600
                        }
1601

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

    
1606
                        if (e.getProjectionEvents().length > 0) {
1607
                                //redraw = true;
1608
                        }
1609

    
1610

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

    
1622
                        }
1623

    
1624
                        if (e.getLegendEvents().length > 0) {
1625
                                redraw = true;
1626
                        }
1627

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

    
1632
                        if (redraw) {
1633
                //System.out.println("MapContextListener redraw");
1634
                                MapControl.this.drawMap(false);
1635
                        }
1636
                }
1637
        }
1638

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1865
        }
1866

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