Statistics
| Revision:

svn-gvsig-desktop / branches / v10 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / MapControl.java @ 20100

History | View | Annotate | Download (56.4 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.Date;
61
import java.util.HashMap;
62
import java.util.Set;
63

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

    
67
import org.cresques.cts.IProjection;
68

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

    
80

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

    
175
        /**
176
         * <p>One of the possible status of <code>MapControl</code>. Determines that not all visible information has been
177
         * drawn or isn't updated.</p> 
178
         */
179
        public static final int DESACTUALIZADO = 1;
180
        
181
        /**
182
         * <p>One of the possible status of <code>MapControl</code>. Determines that only the graphical layer must
183
         * be drawn / updated.</p> 
184
         */
185
        public static final int ONLY_GRAPHICS = 2;
186

    
187
    // public static final int FAST_PAINT = 3;
188
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
189

    
190
    /**
191
     * <p>Inner model with the layers, event support for drawing them, and the <code>ViewPort</code>
192
     *  with information to adapt to the bounds available in <i>image coordinates</i>.</p>
193
     *  
194
     * @see #getMapContext()
195
     * @see #setMapContext(MapContext) 
196
     */
197
        private MapContext mapContext = null;
198

    
199
        //private boolean drawerAlive = false;
200

    
201
        /**
202
         * <p>All registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
203
         * 
204
         * <p>Only one of them can be active at a given moment.</p>
205
         * 
206
         * @see #addMapTool(String, Behavior)
207
         * @see #addMapTool(String, Behavior[])
208
         * @see #getMapTool(String)
209
         * @see #getMapToolsKeySet() 
210
         * @see #getNamesMapTools()
211
         */
212
        private HashMap namesMapTools = new HashMap();
213

    
214
        /**
215
         * <p>Active {@link Behavior Behavior} that will generate events according a criterion, and then, with a {@link ToolListener ToolListener}
216
         *  associated, will simulate to user that works with this component as a particular tool.</p>
217
         *  
218
         * @see #getCurrentMapTool()
219
         * @see #getCurrentTool()
220
         * @see #setTool(String) 
221
         */
222
        private Behavior currentMapTool = null;
223

    
224
        /**
225
         * <p>Determines which's the current drawn status of this component:
226
         * <ul>
227
         *  <li><b>OUTDATED</b>: all visible information has been drawn or isn't updated.</li>
228
         *  <li><b>UTDATED</b>: all visible information has been drawn and its updated.</li>
229
         *  <li><b>ONLY_GRAPHICS</b>: only the graphical layer must be drawn / updated.</li>
230
         * </ul>
231
         * </p>
232
         * 
233
         * <p>The <code>MapControl</code> drawing process will consider the value of this parameter to decide which elements will
234
         *  be updated or drawn.</p>
235
         */
236
        private int status = DESACTUALIZADO;
237

    
238
        /**
239
         * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
240
         * 
241
         * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
242
         * Meanwhile, the previous image can be kept showed.</p>
243
         * 
244
         * @see BufferedImage
245
         * 
246
         * @see #getImage()
247
         */
248
        private BufferedImage image = null;
249

    
250
        /**
251
         * <p>Name of the tool used currently to interact with this component.</p>
252
         * 
253
         * @see #getCurrentTool()
254
         * @see #setTool(String) 
255
         */
256
        private String currentTool;
257

    
258
        /**
259
         * <p>Object to store the flag that notifies a drawing thread task and <code>MapContext</code>'s layers,
260
         * that must be canceled or can continue with the process.</p>
261
         * 
262
         * @see #cancelDrawing()
263
         */
264
        private CancelDraw canceldraw;
265

    
266
        //private boolean isCancelled = true;
267

    
268
        /**
269
         * <p>Fires an action events after a specified delay.</p>
270
         * 
271
         * <p><code>MapControl</code> will use the timer to update its visible graphical information during
272
         *  a drawing process, or allowing to cancel that process.</p>
273
         * 
274
         * <p>This is very useful to pretend faster interactivity to user when <code>MapControl</code> has
275
         *  lots of layers, and / or layers with heavy graphical elements, that need a long time to finish
276
         *  drawing all its data.</p> 
277
         */
278
        private Timer timer;
279

    
280
        /**
281
         * <p>Reference to the {@link ViewPort ViewPort} of the {@link MapContext MapContext} of this component.</p>
282
         * 
283
         * <p>The view port once is created an instance of <code>MapControl</code>,
284
         *  is obtained from the <i>EPSG:23030</i> projection, that's the default projection for this component.</p>
285
         *  
286
         * <p>After, the view port will change adapting itself according the current projection and the extent.</p>
287
         * 
288
         * @see #getViewPort()
289
         * 
290
         * @see ViewPort
291
         */
292
        protected ViewPort vp;
293

    
294
        //private Drawer drawer;
295

    
296
        /**
297
         * <p>Manager of all <code>MapControl</code> painting requests.</p>
298
         */
299
        private Drawer2 drawer2;
300

    
301
        // private boolean firstDraw = true;
302

    
303
        /**
304
         * <p>Listener of all kind of mouse events produced in this component.</p>
305
         * 
306
         * <p>Delegates each mouse event to the current map tool.</p>
307
         * 
308
         * @see #addMapTool(String, Behavior)
309
         * @see #addMapTool(String, Behavior[])
310
         * @see #getMapTool(String)
311
         * @see #getMapToolsKeySet()
312
         * @see #getNamesMapTools()
313
         * @see #setTool(String)
314
         */
315
        protected MapToolListener mapToolListener = new MapToolListener();
316

    
317
        /**
318
         * <p>Listener of all events produced in a this component's <code>MapContext</code>
319
         * object during an atomic period of time.</p>
320
         */
321
        private MapContextListener mapContextListener = new MapContextListener();
322

    
323
        /**
324
         * <p>Group of <code>ExceptionListener</code> that, in whatever moment could be notified a Throwable Java error or exception.</p>
325
         * 
326
         * @see #addExceptionListener(ExceptionListener)
327
         * @see #removeExceptionListener(ExceptionListener)
328
         */
329
        private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
330

    
331
        /**
332
         * <p>Name of the previous tool used to interact with this component.</p>
333
         * 
334
         * @see #setPrevTool()
335
         */
336
        private String prevTool;
337

    
338
        /**
339
     * We need this to avoid not wanted refresh. REMEMBER TO SET TO TRUE!!
340
     */
341
    // private boolean paintEnabled = false;
342

    
343
        /**
344
         * <p>Creates a new <code>MapControl</code> instance with the following characteristics:
345
         * <ul>
346
         *  <li><i>Name</i>: MapControl .</li>
347
         *  <li>Disables the double buffer of <code>JComponent</code> .</li>
348
         *  <li>Sets opaque <i>(see {@link JComponent#setOpaque(boolean)} )</i>. </li>
349
         *  <li>Sets its status to <code>OUTDATED</code> .</li>
350
         *  <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>
351
         *  <li>Creates a new {@link MapContext MapContext} with a new {@link ViewPort ViewPort} in the projection <i>"EPSG:23030"</i> .</li>
352
         *  <li>Creates a new {@link CommandListener CommandListener} for edition operations.</li>
353
         *  <li>Creates a new {@link MapToolListener MapToolListener}, and associates it as a listener of whatever kind of mouse events produced in this component.</li>
354
         *  <li>Creates a new {@link Drawer2 Drawer2} for managing the painting requests.</li>
355
         *  <li>Creates a new timer that will refresh each 360 milliseconds the visible graphical information, when is running a drawing process.</li>
356
         * </ul>
357
         * </p>
358
         */
359
        public MapControl() {
360
                this.setName("MapControl");
361
                setDoubleBuffered(false);
362
                setOpaque(true);
363
                status = DESACTUALIZADO;
364

    
365
                //Clase usada para cancelar el dibujado
366
                canceldraw = new CancelDraw();
367

    
368
                //Modelo de datos y ventana del mismo
369
                // TODO: Cuando creamos un mapControl, deber?amos asignar
370
                // la projecci?n por defecto con la que vayamos a trabajar.
371
                // 23030 es el c?digo EPSG del UTM30 elipsoide ED50
372
                vp = new ViewPort(CRSFactory.getCRS("EPSG:23030"));
373
                setMapContext(new MapContext(vp));
374

    
375
                //eventos
376
                this.addComponentListener(this);
377
                this.addMouseListener(mapToolListener);
378
                this.addMouseMotionListener(mapToolListener);
379
                this.addMouseWheelListener(mapToolListener);
380

    
381
        this.drawer2 = new Drawer2();
382
                //Timer para mostrar el redibujado mientras se dibuja
383
                timer = new Timer(360,
384
                                new ActionListener() {
385
                                        public void actionPerformed(ActionEvent e) {
386
                                                MapControl.this.repaint();
387
                                        }
388
                                });
389
        }
390

    
391
        /**
392
         * <p>Sets a <code>MapContext</code> to this component.</p>
393
         * 
394
         * <p>The <code>MapContext</code> has the <i>model</i>, and most of the <i>view</i>,
395
         * and <i>control</i> logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the
396
         * information to the projection, and to display it in the available area.</p>
397
         * 
398
         * <p>If <code>model</code> hadn't a <code>ViewPort</code>, assigns the current one to it, otherwise, use its <code>ViewPort</code>.</p>
399
         * 
400
         * <p>After assigning the <code>MapContext</code> and <code>ViewPort</code>, sets the same {@link MapContextListener MapContextListener}
401
         *  that was using, and changes the <i>status</i> to <code>OUTDATED</code>.</p>
402
         * 
403
         * @param model this component's <code>MapContext</code>, that includes the <code>ViewPort</code>.
404
         * 
405
         * @see MapContext
406
         * 
407
         * @see #getMapContext()
408
         */
409
        public void setMapContext(MapContext model) {
410
                if (mapContext != null) {
411
                        mapContext.removeAtomicEventListener(mapContextListener);
412
                }
413

    
414
                mapContext = model;
415

    
416
                if (mapContext.getViewPort() == null) {
417
                        mapContext.setViewPort(vp);
418
                } else {
419
                        vp = mapContext.getViewPort();
420

    
421
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
422
                        //System.err.println("Viewport en setMapContext:" + vp);
423
                }
424

    
425
                mapContext.addAtomicEventListener(mapContextListener);
426

    
427
                status = DESACTUALIZADO;
428
        }
429

    
430
        /**
431
         * <p>Gets this component's {@link MapContext MapContext} projection.</p>
432
         *
433
         * @return this component's {@link MapContext MapContext} projection
434
         * 
435
         * @see MapContext#getProjection()
436
         * @see MapControl#setProjection(IProjection)
437
         */
438
        public IProjection getProjection() {
439
                return getMapContext().getProjection();
440
        }
441

    
442
        /**
443
         * <p>Sets the projection to this component's {@link MapContext MapContext}.</p>
444
         *
445
         * @param proj the kind of projection to this component's {@link MapContext MapContext}
446
         * 
447
         * @see MapContext#setProjection(IProjection)
448
         * @see MapControl#getProjection()
449
         */
450
        public void setProjection(IProjection proj) {
451
                getMapContext().setProjection(proj);
452
        }
453

    
454
        /**
455
         * <p>Gets this component's <code>MapContext</code>, with the <i>model</i>, and most of the <i>view</i>,
456
         * and <i>control</i> logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the
457
         * information to the projection, and display it in the available area.</p>
458
         * 
459
         * @return this component's <code>MapContext</code>, that includes the <code>ViewPort</code> used to project the
460
         * graphical information, and display it in the available area
461
         * 
462
         * @see MapContext
463
         * 
464
         * @see MapControl#setMapContext(MapContext)
465
         */
466
        public MapContext getMapContext() {
467
                return mapContext;
468
        }
469

    
470
        /**
471
         * <p>Registers a new behavior to this component.</p>
472
         * 
473
         * <p>According the nature of the {@link Behavior Behavior}, different events will be generated. Those
474
         *  events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this
475
         *  <code>MapControl</code> object as a <i>tool</i>.</p>
476
         *
477
         * @param name name to identify the behavior to add
478
         * @param tool the behavior to add
479
         * 
480
         * @see #addMapTool(String, Behavior[])
481
         * @see #getNamesMapTools()
482
         * @see #getMapToolsKeySet()
483
         * @see #hasTool(String)
484
         */
485
        public void addMapTool(String name, Behavior tool) {
486
                namesMapTools.put(name, tool);
487
                tool.setMapControl(this);
488
        }
489

    
490
        /**
491
         * <p>Registers a new behavior to this component as a {@link CompoundBehavior CompoundBehavior} made up of <code>tools</code>.</p>
492
         * 
493
         * <p>According the nature of the behaviors registered, different events will be generated. Those
494
         *  events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this
495
         *  <code>MapControl</code> object as a <i>tool</i>.</p>
496
         *
497
         * @param name name to identify the compound behavior to add
498
         * @param tools the compound behavior to add
499
         * 
500
         * @see #addMapTool(String, Behavior)
501
         * @see #getNamesMapTools()
502
         * @see #getMapToolsKeySet()
503
         * @see #hasTool(String)
504
         */
505
        public void addMapTool(String name, Behavior[] tools){
506
                CompoundBehavior tool = new CompoundBehavior(tools);
507
                addMapTool(name, tool);
508
        }
509

    
510
        /**
511
         * <p>Gets the <code>Behavior</code> registered in this component, identified
512
         *  by <code>name</code>.</p>
513
         *
514
         * @param name name of a registered behavior
515
         * 
516
         * @return tool the registered behavior in this component as <code>name</code>, or <code>null</code> if
517
         *  no one has that identifier
518
         *  
519
         * @see #addMapTool(String, Behavior)
520
         * @see #addMapTool(String, Behavior[])
521
         * @see #hasTool(String)
522
         */
523
        public Behavior getMapTool(String name) {
524
                return (Behavior)namesMapTools.get(name);
525
        }
526

    
527
        /**
528
         * <p>Returns a set view of the keys that identified the tools
529
         *  registered.</p>
530
         *
531
         * @return a set view of the keys that identified the tools registered
532
         * 
533
         * @see HashMap#keySet()
534
         * 
535
         * @see #getNamesMapTools()
536
          * @see #addMapTool(String, Behavior)
537
          * @see #addMapTool(String, Behavior[])
538
         */
539
        public Set getMapToolsKeySet() {
540
                return namesMapTools.keySet();
541
        }
542

    
543
        /**
544
         * <p>Returns <code>true</code> if this component contains a tool identified by <code>toolName</code>.</p>
545
         * 
546
         * @param toolName identifier of the tool
547
         * 
548
         * @return <code>true</code> if this component contains a tool identified by <code>toolName</code>; otherwise <code>false</code>
549
         * 
550
         * @see #addMapTool(String, Behavior)
551
         * @see #addMapTool(String, Behavior[])
552
         */
553
        public boolean hasTool(String toolName) {
554
                return namesMapTools.containsKey(toolName);
555
        }
556

    
557
        /**
558
         * <p>Sets as current active <code>Behavior</code> associated to this component, that one which
559
         *  is registered and identified by <code>toolName</code>.</p>
560
         * 
561
         * <p>Changing the current active behavior for this <code>MapControl</code>, implies also updating the
562
         *  previous <i>behavior</i> tool, and the current cursor.</p>
563
         * 
564
         * @param toolName name of a registered behavior
565
         * 
566
         * @see #getCurrentMapTool()
567
         * @see #getCurrentTool()
568
         */
569
        public void setTool(String toolName) {
570
                prevTool=getCurrentTool();
571
                Behavior mapTool = (Behavior) namesMapTools.get(toolName);
572
                currentMapTool = mapTool;
573
                currentTool = toolName;
574
                this.setCursor(mapTool.getCursor());
575
        }
576

    
577
        /**
578
         * <p>Gets as current active <code>Behavior</code> associated to this component, that one which
579
         *  is registered and identified by <code>toolName</code>.</p>
580
         * 
581
         * <p>Changing the current active behavior for this <code>MapControl</code>, implies also updating the
582
         *  previous <i>behavior</i> tool, and the current cursor.</p>
583
         * 
584
         * @param toolName name of a registered behavior
585
         * 
586
         * @see #getCurrentTool()
587
         * @see #setTool(String)
588
         */
589
        public Behavior getCurrentMapTool(){
590
                return currentMapTool;
591
        }
592

    
593
        /**
594
         * <p>Returns the name of the current selected tool on this MapControl</p>
595
         *
596
         * @return the name of the current's behavior tool associated to this component
597
         * 
598
         * @see #getCurrentMapTool()
599
         * @see #setTool(String)
600
         */
601
        public String getCurrentTool() {
602
                return currentTool;
603
        }
604

    
605
        /**
606
         * <p>Determines that current drawing process of <code>MapControl</code>'s <code>MapContext</code>'s data must be canceled.</p>
607
         * 
608
         * <p>It has no effects if now isn't drawing that graphical information.</p>
609
         *  
610
         * <p>At last resort, the particular implementation of each layer in this <code>MapControl</code>'s <code>MapContrext</code>
611
     *   will be that one which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
612
         */
613
        public void cancelDrawing() {
614
                /* if (drawer != null) {
615
                        if (!drawer.isAlive()) {
616
                                return;
617
                        }
618
                }
619
                */
620
                canceldraw.setCanceled(true);
621

    
622
                /* while (!isCancelled) {
623
                        if (!drawer.isAlive()) {
624
                            // Si hemos llegado aqu? con un thread vivo, seguramente
625
                            // no estamos actualizados.
626

627
                                break;
628
                        }
629

630
                }
631
                canceldraw.setCancel(false);
632
                isCancelled = false;
633
        drawerAlive = false; */
634
        }
635

    
636
        /**
637
         * <p>Creates a {@link BufferedImage BufferedImage} image if there was no buffered image, or if
638
         *  its viewport's image height or width is different from this component's size. Once has created
639
         *  a double-buffer, fills it with the vieport's background color, or with <i>white</i> if it had no background color.</p>
640
         * 
641
         * <p>If no double-buffered existed, creates a {@link BufferedImage BufferedImage} with the size of this component,
642
         * and as an image with 8-bit RGBA color components packed into integer pixels. That image has a <code>DirectColorModel</code> with alpha.
643
         * The color data in that image is considered not to be premultiplied with alpha.</p> 
644
         * 
645
         * <p>Once has created and filled the new inner <code>MapControl</code>'s double-buffer, changes the status to
646
         * <code>OUTDATED</code>.</p>
647
         * 
648
         * @return <code>true</code> if has created and filled a new double-buffer for this <code>MapControl</code> instance; otherwise <code>false</code>
649
         */
650
    private boolean adaptToImageSize()
651
    {
652
        if ((image == null) || (vp.getImageWidth() != this.getWidth()) || (vp.getImageHeight() != this.getHeight()))
653
        {
654
            image = new BufferedImage(this.getWidth(), this.getHeight(),
655
                    BufferedImage.TYPE_INT_ARGB);
656
            // ESTILO MAC
657
//                image = GraphicsEnvironment.getLocalGraphicsEnvironment()
658
//                                .getDefaultScreenDevice().getDefaultConfiguration()
659
//                                .createCompatibleImage(this.getWidth(), this.getHeight());
660
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
661
            getMapContext().getViewPort().refreshExtent();
662

    
663

    
664
            Graphics gTemp = image.createGraphics();
665
            Color theBackColor = vp.getBackColor();
666
            if (theBackColor == null)
667
                gTemp.setColor(Color.WHITE);
668
            else
669
                gTemp.setColor(theBackColor);
670

    
671
            gTemp.fillRect(0,0,getWidth(), getHeight());
672
            gTemp.dispose();
673
            status = DESACTUALIZADO;
674
            // g.drawImage(image,0,0,null);
675
            return true;
676
        }
677
        return false;
678
    }
679

    
680
        /**
681
         * <p>Paints the graphical information of this component using a double buffer.</p>
682
         * 
683
         * <p>If the double buffer wasn't created, creates a new one.</p>
684
         * 
685
         * <p>Paints the component according the following algorithm:
686
         * <br>
687
         *  &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
688
         *  &nbsp &nbsp If there is no <i>double buffer</i>:<br>
689
         *  &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the <code>MapControl</code> instance, delegates
690
         *   the drawing process to that behavior, calling: <code><i>behavior_instance</i>.paintComponent(g)</code> &nbsp .<br>
691
         *  &nbsp &nbsp &nbsp Else, repaints the current graphical information quickly calling: <code>g.drawImage(image,0,0,null)</code> &nbsp .<br>
692
         *  &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
693
         *   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
694
         *   (invoking <code>repaint()</code> that comprises invoke this method) the view every delay of 360 ms. during the the process drawing.</p>
695
         * 
696
           * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
697
           * @see Drawer2
698
         */
699
        protected void paintComponent(Graphics g) {
700
        adaptToImageSize();
701
              if (status == ACTUALIZADO) {
702
                        /*
703
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
704
                         * en dicho behaviour
705
                         */
706
            if (image != null)
707
            {
708
                if (currentMapTool != null)
709
                    currentMapTool.paintComponent(g);
710
                else
711
                    g.drawImage(image,0,0,null);
712
                        }
713
                } else if ((status == DESACTUALIZADO)
714
                || (status == ONLY_GRAPHICS)) {
715

    
716
                g.drawImage(image,0,0,null);
717

    
718
                drawer2.put(new PaintingRequest());
719
                timer.start();
720
       }
721
        }
722

    
723
        /**
724
         * <p>Gets the {@link BufferedImage BufferedImage} used to accelerate the draw of new ''frames'' with changes, 
725
         * or new graphical items in this component.</p>
726
         * 
727
         * @return double buffered image used by this component to accelerate the draw of its graphical information, or
728
         * <code>null</code> if isn't already created
729
         * 
730
         * @see BufferedImage 
731
         */
732
        public BufferedImage getImage() {
733
                return image;
734
        }
735

    
736
        /**
737
         * <p>Forces repaint all visible graphical information in this component.</p>
738
         * 
739
         * <p>If <code>doClear == true</code>, before repainting, clears the background color, with the
740
         *  inner viewport's background color.</p>
741
         *
742
         * @param doClear <code>true</code> if needs clearing the background color before drawing the map
743
         * 
744
         * @see #cancelDrawing()
745
         * @see FLayers#setDirty(boolean)
746
         */
747
        public void drawMap(boolean doClear) {
748
                cancelDrawing();
749
                status = DESACTUALIZADO;
750
        getMapContext().getLayers().setDirty(true);
751
                if (doClear)
752
        {
753
            // image = null; // Se usa para el PAN
754
            if (image != null)
755
            {
756
                Graphics2D g = image.createGraphics();
757
                Color theBackColor = vp.getBackColor();
758
                if (theBackColor == null)
759
                    g.setColor(Color.WHITE);
760
                else
761
                    g.setColor(theBackColor);
762
                g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight());
763
                g.dispose();
764
            }
765
        }
766
                repaint();
767
        }
768

    
769
        /**
770
         * <p>Cancels any current drawing process, changing the status to <code>OUTDATED</code>, and forcing
771
         * repaint only the layers dirty.</p>
772
         * 
773
         * @see #cancelDrawing()
774
         */
775
        public void rePaintDirtyLayers()
776
        {
777
                cancelDrawing();
778
        status = DESACTUALIZADO;
779
        repaint();
780
        }
781

    
782
        /**
783
         * <p>Cancels any current drawing process, changing the status to <code>ONLY_GRAPHICS</code>, and forcing
784
         * repaint only the graphical layer of the <code>MapContext</code>.</p>
785
         */
786
    public void drawGraphics() {
787
        status = ONLY_GRAPHICS;
788
        repaint();
789
    }
790

    
791
        /**
792
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
793
         */
794
        public void componentHidden(ComponentEvent e) {
795
        }
796

    
797
        /**
798
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
799
         */
800
        public void componentMoved(ComponentEvent e) {
801
        }
802

    
803
        /**
804
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
805
         */
806
        public void componentResized(ComponentEvent e) {
807
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
808
                                BufferedImage.TYPE_INT_ARGB);
809
                Graphics gTemp = image.createGraphics();
810
                gTemp.setColor(vp.getBackColor());
811
                gTemp.fillRect(0,0,getWidth(), getHeight());
812
        System.out.println("MapControl resized");
813
            // image = null;
814
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
815
                getMapContext().getViewPort().setScale(); */
816
                // drawMap(true);
817
        }
818

    
819
        /**
820
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
821
         */
822
        public void componentShown(ComponentEvent e) {
823
        }
824

    
825
        /**
826
         * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
827
         */
828
        public void addExceptionListener(ExceptionListener o) {
829
                exceptionHandlingSupport.addExceptionListener(o);
830
        }
831

    
832
        /**
833
         * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
834
         */
835
        public boolean removeExceptionListener(ExceptionListener o) {
836
                return exceptionHandlingSupport.removeExceptionListener(o);
837
        }
838

    
839
        /**
840
         * @see ExceptionHandlingSupport#throwException(Throwable)
841
         */
842
        protected void throwException(Throwable t) {
843
                exceptionHandlingSupport.throwException(t);
844
        }
845

    
846
        /**
847
         * <p>Represents each <code>MapControl</code>'s data painting request.</p>
848
         * 
849
         * <p>The request will be attended by a <code>Drawer2</code>, which will hold it since the <code>Drawer2</code>'s worker
850
         *  takes it, or arrives a new painting request, which will replace it.</p> 
851
         */
852
    private class PaintingRequest
853
    {
854
            /**
855
             * <p>Creates a new <code>PaintingRequest</p> instance.</p>
856
             */
857
        public PaintingRequest()
858
        {
859
        }
860

    
861
        /**
862
         * <p><code>MapControl</code> paint process:</p>
863
         * 
864
         * <p>
865
         *  <ul>
866
         *   <li><i>1.- </i>Cancels all previous <code>MapControl</code>'s drawing processes.</li>
867
         *   <li><i>2.- </i>If <i>status</i> was OUTDATED:
868
         *    <ul>
869
         *     <li><i>2.1.- </i>Fills the background color with viewport's background color, or <i>white</i> if it was undefined.</li>
870
         *     <li><i>2.2.- </i>Sets <i>status</i> to UPDATED.</li>
871
         *     <li><i>2.3.- </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>
872
         *    </ul>
873
         *   </li>
874
         *   <li><i>3.- </i>Else, if <i>status</i> was ONLY_GRAPHICS:
875
         *    <ul>
876
         *     <li><i>3.1.- </i>Sets <i>status</i> to UPDATED.</li>
877
         *     <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>
878
         *    </ul>
879
         *   </li>
880
         *   <li><i>4.- </i>Stops the <i>timer</i>.</li>
881
         *   <li><i>5.- </i>Repaints this component invoking: <code>repaint();</code></li>
882
         *  </ul>
883
         * </p>
884
         * 
885
         * @see #cancelDrawing()
886
         * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
887
         * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
888
         * 
889
         * @see ViewPort
890
         */
891
        public void paint()
892
        {
893
            try
894
            {
895
                    canceldraw.setCanceled(false);
896
                /* if (image == null)
897
                {
898
                    image = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
899
                            BufferedImage.TYPE_INT_ARGB);
900
                    Graphics gTemp = image.createGraphics();
901
                    Color theBackColor = vp.getBackColor();
902
                    if (theBackColor == null)
903
                        gTemp.setColor(Color.WHITE);
904
                    else
905
                        gTemp.setColor(theBackColor);
906

907
                    gTemp.fillRect(0,0,getWidth(), getHeight());
908
                    gTemp.dispose();
909
                    // g.drawImage(image,0,0,null);
910
                    System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
911
                } */
912
                Graphics2D g = image.createGraphics();
913

    
914
                ViewPort viewPort = mapContext.getViewPort();
915

    
916
                if (status == DESACTUALIZADO)
917
                {
918
                        Graphics2D gTemp = image.createGraphics();
919
                    Color theBackColor = viewPort.getBackColor();
920
                    if (theBackColor == null)
921
                        gTemp.setColor(Color.WHITE);
922
                    else
923
                        gTemp.setColor(theBackColor);
924
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
925
                    status = ACTUALIZADO;
926
                    // ESTILO MAC
927
//                    BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
928
//                            BufferedImage.TYPE_INT_ARGB);
929
//
930
//                    mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
931
//                    g.drawImage(imgMac, 0, 0, null);
932
                    // FIN ESTILO MAC
933
                    // SIN MAC:
934
                    mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
935

    
936
                }
937
                else if (status == ONLY_GRAPHICS)
938
                {
939
                    status = ACTUALIZADO;
940
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
941

    
942
                }
943

    
944

    
945
                // status = FAST_PAINT;
946
              //  drawerAlive = false;
947
                timer.stop();
948
                repaint();
949

    
950

    
951
            } catch (Throwable e) {
952
                timer.stop();
953
              //  isCancelled = true;
954
                e.printStackTrace();
955
                throwException(e);
956
            } finally {
957
            }
958

    
959
        }
960

    
961
    }
962

    
963

    
964
    /**
965
     * <p>An instance of <code>Drawer2</code> could manage all <code>MapControl</code> painting requests.</p>
966
     * 
967
     * <p>Based on the <i>WorkerThread</i> software pattern, creates a worker thread that will attend sequentially
968
     *  the current waiting painting request, after finishing the previous (that could be by a cancel action).</p>
969
     * 
970
     * <p>All new {@link PaintingRequest PaintingRequest} generated will be stored as <i>waiting requests</i> since the worker
971
     * attends it.</p>
972
     * 
973
     * <p>If a worker finished and there was no <i>painting request</i>, the worker would be set to wait until any
974
     *  <i>painting request</i> would be put.</p>
975
     * 
976
     * @author fjp
977
     */
978
    public class Drawer2
979
    {
980
        // Una mini cola de 2. No acumulamos peticiones de dibujado
981
        // dibujamos solo lo ?ltimo que nos han pedido.
982

    
983
            /**
984
             * <p>Painting request that's been attended by the <code>Drawer2</code>'s worker.</p>
985
             * 
986
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
987
             * @see #take()
988
             */
989
            private PaintingRequest paintingRequest;
990

    
991
            /**
992
             * <p>Painting request waiting to be attended by the <code>Drawer2</code>'s worker.</p>
993
             * 
994
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
995
             * @see #take()
996
             */
997
            private PaintingRequest waitingRequest;
998

    
999
            /**
1000
             * <p>Determines that the <code>Drawer2</code>'s worker is busy attending a painting request.</p> 
1001
              * 
1002
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1003
             * @see #take()
1004
             */
1005
        private boolean waiting;
1006

    
1007
            /**
1008
             * <p>Notifies the <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1009
             * 
1010
             * @see #setShutdown(boolean)
1011
             */
1012
        private boolean shutdown;
1013

    
1014
        /**
1015
         * <p>Sets this <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1016
         * 
1017
         * @param isShutdown a boolean value
1018
         */
1019
        public void setShutdown(boolean isShutdown)
1020
        {
1021
            shutdown = isShutdown;
1022
        }
1023

    
1024
        /**
1025
         * <p>Creates a new drawer for managing all data painting requests in <code>MapControl</code>.</p>
1026
         * 
1027
         * <p>Includes the following steps:
1028
         *  <ul>
1029
         *   <li>By default, there is no <i>current painting request</i>.</li>
1030
         *   <li>By default, there is no <i>waiting painting request</i>.</li>
1031
         *   <li>By default, the worker thread is waiting no <i>painting request</i>.</li>
1032
         *   <li>By default, the worker thread is running.</li>
1033
         *   <li>Creates and starts a worker thread for attending the <i>painting requests</i>.</li>
1034
         *  </ul>
1035
         * </p>
1036
         */
1037
        public Drawer2()
1038
        {
1039
            paintingRequest = null;
1040
            waitingRequest = null;
1041
            waiting = false;
1042
            shutdown = false;
1043
            new Thread(new Worker()).start();
1044
        }
1045

    
1046
        /**
1047
         * <p>Sets a <code>PaintingRequest</code> to be attended by the worker thread of this object. If 
1048
         *  this one was waiting, wakes up.</p>
1049
         * 
1050
         * <p>All waiting threads will be notified synchronized.</p>
1051
         * 
1052
         * @param newPaintRequest
1053
         * 
1054
         * @see #take()
1055
         */
1056
        public void put(PaintingRequest newPaintRequest)
1057
        {
1058
            waitingRequest = newPaintRequest;
1059
            if (waiting)
1060
            {
1061
                synchronized (this) {
1062
                    notifyAll();
1063
                }
1064
            }
1065
        }
1066

    
1067
        /**
1068
         * <p>Used by this object's worker, returns the current waiting drawing request, causing current thread
1069
         *  to wait until another thread invokes {@link #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest) #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)},
1070
         *  if there was no waiting request.</p>
1071
         * 
1072
         * <p>All threads will access synchronized to the waiting request.</p>
1073
         * 
1074
         * @return <code>PaintingRequest</code> that was waiting to be attended
1075
         * 
1076
         * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1077
         */
1078
        public PaintingRequest take()
1079
        {
1080
            if (waitingRequest == null)
1081
            {
1082
                synchronized (this) {
1083
                    waiting = true;
1084
                    try {
1085
                        wait();
1086
                    }
1087
                    catch (InterruptedException ie)
1088
                    {
1089
                        waiting = false;
1090
                    }
1091
                }
1092
            }
1093
            paintingRequest = waitingRequest;
1094
            waitingRequest = null;
1095
            return paintingRequest;
1096
        }
1097

    
1098
        /**
1099
         * <p>Thread for attending painting requests.</p>
1100
         * 
1101
         * <p>If there was no double buffer, sets the status to <code>OUTDATED</code> and finishes, otherwise
1102
         *  takes the painting request (it's probably that would wait some time), cancel the previous drawing
1103
         *  process, and starts processing the request.</p>
1104
         * 
1105
         * @see Thread
1106
         */
1107
        private class Worker implements Runnable
1108
        {
1109
                /*
1110
                 * (non-Javadoc)
1111
                 * @see java.lang.Runnable#run()
1112
                 */
1113
                public void run()
1114
            {
1115
                while (!shutdown)
1116
                {
1117
                    PaintingRequest p = take();
1118
                    System.out.println("Pintando");
1119
                    if (image != null){
1120
                            cancelDrawing();
1121
                        p.paint();
1122
                    } else
1123
                        status = DESACTUALIZADO;
1124
                }
1125
            }
1126
        }
1127
    }
1128

    
1129
        /**
1130
         * <p><code>Drawer</code> is implemented for drawing the layers of a <code>MapControl</code>'s <i>MapContext</i> instance
1131
         *  as a <i>thread</i> of execution.</p>
1132
         *  
1133
         * <p>Draws <code>MapControl</code> according its <i>status</i>:
1134
         *  <ul>
1135
         *   <li><code><i>ONLY_GRAPHICS</i></code>: refreshes only the graphical layer, changing the status to <code><i>UPDATED</i></code>, via
1136
         *    {@linkplain MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double) MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)}.</li>
1137
         *   <li><code><i>OUTDATED</i></code>: refreshes all layers, changing the status to <code><i>UPDATED</i></code>, via
1138
         *    {@linkplain MapContext#draw(BufferedImage, Graphics2D, Cancellable, double) MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)}.</li>
1139
         *  <ul>
1140
         * </p>
1141
         * 
1142
         * <p>This drawing process is accelerated by a <code>BufferedImage</code>, and can be canceled.</p>
1143
         * 
1144
         * <p>Once the drawing process has finished, the timer stops and this component gets repainted.</p> 
1145
         *
1146
         * @deprecated
1147
         * @author Vicente Caballero Navarro
1148
         */
1149
        public class Drawer extends Thread {
1150
                //private Graphics g;
1151
                
1152
                /**
1153
                 * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
1154
                 * 
1155
                 * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
1156
                 * Meanwhile, the previous image can be kept showed.</p>
1157
                 * 
1158
                 * @see BufferedImage
1159
                 */
1160
                private BufferedImage image = null;
1161

    
1162
                /**
1163
                 * <p>Object to store the flag that notifies the drawing must be canceled or can continue with the process.</p>
1164
                 * 
1165
                 * <p>At last resort, the particular implementation of each layer in a <code>MapControl</code>'s <code>MapContrext</code>
1166
         *   will be which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
1167
                 */
1168
                private CancelDraw cancel;
1169
                //private boolean threadCancel = false;
1170

    
1171

    
1172
                /**
1173
                 * <p>Creates a new <code>Drawer</code> instance.</p>
1174
                 */
1175
                public Drawer(BufferedImage image, CancelDraw cancel)
1176
        {
1177
                        this.image = image;
1178
                        this.cancel = cancel;
1179
         //   drawerAlive = true;
1180
                }
1181

    
1182
                /**
1183
                 * @see java.lang.Runnable#run()
1184
                 * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
1185
                 * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
1186
                 */
1187
                public void run() {
1188
                        try {
1189
                                // synchronized (Drawer.class) {
1190
                                    Graphics2D g = image.createGraphics();
1191

    
1192
                                    ViewPort viewPort = mapContext.getViewPort();
1193
                    if (status == DESACTUALIZADO)
1194
                    {
1195
                                        Color theBackColor = viewPort.getBackColor();
1196
                                        if (theBackColor == null)
1197
                                            g.setColor(Color.WHITE);
1198
                                        else
1199
                                            g.setColor(theBackColor);
1200
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1201
                        status = ACTUALIZADO;
1202
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
1203
                    }
1204
                    else if (status == ONLY_GRAPHICS)
1205
                    {
1206
                        status = ACTUALIZADO;
1207
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
1208
                    }
1209

    
1210
                                        timer.stop();
1211
                    // status = FAST_PAINT;
1212
                  //  drawerAlive = false;
1213
                                        repaint();
1214

    
1215

    
1216

    
1217
                                // }
1218
                        } catch (Throwable e) {
1219
                            timer.stop();
1220
                                //isCancelled = true;
1221
                e.printStackTrace();
1222
                                throwException(e);
1223
                        } finally {
1224
                        }
1225
                }
1226
        }
1227

    
1228
        /**
1229
         * <p>An instance of <code>CancelDraw</code> will be shared by all this <code>MapControl</code>'s <code>MapContext</code> layers,
1230
         *  allowing receive a notification that, when they're been drawn, to be cancelled.</p>
1231
         *
1232
         * @see Cancellable
1233
         *
1234
         * @author Fernando Gonz?lez Cort?s
1235
         */
1236
        public class CancelDraw implements Cancellable {
1237
                /**
1238
                 * <p>Determines if the drawing task must be canceled or not.</p>
1239
                 * 
1240
                 * @see #isCanceled()
1241
                 * @see #setCanceled(boolean)
1242
                 */
1243
                private boolean cancel = false;
1244

    
1245
                /**
1246
                 * Creates a new <code>CancelDraw</code> object.
1247
                 */
1248
                public CancelDraw() {
1249
                }
1250

    
1251
                /*
1252
                 * (non-Javadoc)
1253
                 * @see com.iver.utiles.swing.threads.Cancellable#setCanceled(boolean)
1254
                 */
1255
                public void setCanceled(boolean b) {
1256
                        cancel = b;
1257
                }
1258

    
1259
                /*
1260
                 * (non-Javadoc)
1261
                 * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
1262
                 */
1263
                public boolean isCanceled() {
1264
                        return cancel;
1265
                }
1266
        }
1267

    
1268
        /**
1269
         * <p>Listens all kind of mouse events produced in {@link MapControl MapControl}, and invokes its current
1270
         *  map tool <i>({@link MapControl#getCurrentMapTool() MapControl#getCurrentMapTool()}</i> to simulate a behavior.</p>
1271
         *  
1272
         * <p>Mouse wheel moved events produce a <i>zoom in</i> operation if wheel rotation is negative, or a <i>zoom out</i>
1273
         *  if its positive. Both will be centered in the position of the mouse, but, meanwhile <i>zoom in</i> operation
1274
         *  applies a factor of 0.9, <i>zoom out</i> operation applies a factor of 1.2</p>
1275
         *  
1276
         * <p>Mouse wheel moved events can be produced as much frequently, that between each one, the drawing process could
1277
         *  hadn't finished. This is the reason that, in this situation, cancels always the previous drawing process before
1278
         *  applying a <i>zoom</i> operation, and ignores all new mouse positions that are produced before 1 second.</p>
1279
         *
1280
         * @author Fernando Gonz?lez Cort?s
1281
         */
1282
        public class MapToolListener implements MouseListener, MouseWheelListener,
1283
                MouseMotionListener {
1284

    
1285
                /**
1286
                 * <p>Used to avoid mouse wheel move events closed.</p>
1287
                 * 
1288
                 * <p>If a mouse wheel move event is produced 
1289
                 */
1290
                long t1;
1291

    
1292
                /**
1293
                 * <p>Position of the mouse, in map coordinates.</p>
1294
                 * 
1295
                 * <p>This point coordinates will be used as center of the <i>zoom</i> operation.</p>
1296
                 */
1297
                Point2D pReal;
1298

    
1299
                /**
1300
                 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1301
                 * @see Behavior#mouseClicked(MouseEvent)
1302
                 */
1303
                public void mouseClicked(MouseEvent e) {
1304
                        try {
1305
                                currentMapTool.mouseClicked(e);
1306
                        } catch (BehaviorException t) {
1307
                                throwException(t);
1308
                        }
1309
                }
1310

    
1311
                /**
1312
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1313
                 * @see Behavior#mouseEntered(MouseEvent)
1314
                 */
1315
                public void mouseEntered(MouseEvent e) {
1316
                        try {
1317
                                currentMapTool.mouseEntered(e);
1318
                        } catch (BehaviorException t) {
1319
                                throwException(t);
1320
                        }
1321
                }
1322

    
1323
                /**
1324
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1325
                 * @see Behavior#mouseExited(MouseEvent)
1326
                 */
1327
                public void mouseExited(MouseEvent e) {
1328
                        try {
1329
                                currentMapTool.mouseExited(e);
1330
                        } catch (BehaviorException t) {
1331
                                throwException(t);
1332
                        }
1333
                }
1334

    
1335
                /**
1336
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1337
                 * @see Behavior#mousePressed(MouseEvent)
1338
                 */
1339
                public void mousePressed(MouseEvent e) {
1340
                        try {
1341
                                currentMapTool.mousePressed(e);
1342
                        } catch (BehaviorException t) {
1343
                                throwException(t);
1344
                        }
1345
                }
1346

    
1347
                /**
1348
                 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1349
                 * @see Behavior#mouseReleased(MouseEvent)
1350
                 */
1351
                public void mouseReleased(MouseEvent e) {
1352
                        try {
1353
                                currentMapTool.mouseReleased(e);
1354
                        } catch (BehaviorException t) {
1355
                                throwException(t);
1356
                        }
1357
                }
1358

    
1359
                /**
1360
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
1361
                 * @see Behavior#mouseWheelMoved(MouseWheelEvent)
1362
                 */
1363
                public void mouseWheelMoved(MouseWheelEvent e) {
1364
                        try {
1365
                                currentMapTool.mouseWheelMoved(e);
1366

    
1367
                                // Si el tool actual no ha consumido el evento
1368
                                // entendemos que quiere el comportamiento por defecto.
1369
                                if (!e.isConsumed())
1370
                                {
1371
                                        // Para usar el primer punto sobre el que queremos centrar
1372
                                        // el mapa, dejamos pasar un segundo para considerar el siguiente
1373
                                        // punto como v?lido.
1374
                                        if (t1 == 0)
1375
                                        {
1376
                                                t1= System.currentTimeMillis();
1377
                                                pReal = vp.toMapPoint(e.getPoint());
1378
                                        }
1379
                                        else
1380
                                        {
1381
                                                long t2 = System.currentTimeMillis();
1382
                                                if ((t2-t1) > 1000)
1383
                                                        t1=0;
1384
                                        }
1385
                                        cancelDrawing();
1386
                                        ViewPort vp = getViewPort();
1387

    
1388

    
1389
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1390
                                                        vp.getAdjustedExtent().getCenterY()); */
1391
                                        int amount = e.getWheelRotation();
1392
                                        double nuevoX;
1393
                                        double nuevoY;
1394
                                        double factor;
1395

    
1396
                                        if (amount < 0) // nos acercamos
1397
                                        {
1398
                                                factor = 0.9;
1399
                                        } else // nos alejamos
1400
                                        {
1401
                                                factor = 1.2;
1402
                                        }
1403
                                        Rectangle2D.Double r = new Rectangle2D.Double();
1404
                                        if (vp.getExtent() != null) {
1405
                                                nuevoX = pReal.getX()
1406
                                                                - ((vp.getExtent().getWidth() * factor) / 2.0);
1407
                                                nuevoY = pReal.getY()
1408
                                                                - ((vp.getExtent().getHeight() * factor) / 2.0);
1409
                                                r.x = nuevoX;
1410
                                                r.y = nuevoY;
1411
                                                r.width = vp.getExtent().getWidth() * factor;
1412
                                                r.height = vp.getExtent().getHeight() * factor;
1413

    
1414
                                                vp.setExtent(r);
1415
                                        }
1416

    
1417

    
1418
                                }
1419
                        } catch (BehaviorException t) {
1420
                                throwException(t);
1421
                        }
1422
                }
1423

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

    
1436
                /**
1437
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
1438
                 * @see Behavior#mouseMoved(MouseEvent)
1439
                 */
1440
                public void mouseMoved(MouseEvent e) {
1441
                        try {
1442
                                currentMapTool.mouseMoved(e);
1443
                        } catch (BehaviorException t) {
1444
                                throwException(t);
1445
                        }
1446
                }
1447
        }
1448

    
1449
        /**
1450
         * <p<code>MapContextListener</code> listens all events produced in a <code>MapControl</code>'s <code>MapContext</code>
1451
         * object during an atomic period of time, and sets it to dirty, <i>executing <code>drawMap(false)</code>, if any of the
1452
         * following conditions is accomplished</i>:
1453
         * <ul>
1454
         *  <li>Any of the <code>LayerEvent</code> in the <code>AtomicEvent</code> parameter notifies a <i>visibility change</i>.</li>
1455
         *  <li>There is at least one <code>ColorEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1456
         *  <li>There is at least one <code>ExtentEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1457
         *  <li>Any of the <code>LayerCollectionEvent</code> in the <code>AtomicEvent</code> parameter notifies that a driver's layer has reloaded it successfully.</li>
1458
         *  <li>There is at least one <code>LegendEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1459
         *  <li>There is at least one <code>SelectionEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1460
         * </ul>
1461
         * </p>
1462
         *
1463
         * @author Fernando Gonz?lez Cort?s
1464
         */
1465
        public class MapContextListener implements AtomicEventListener {
1466
                /**
1467
                 * @see com.iver.cit.gvsig.fmap.AtomicEventListener#atomicEvent(com.iver.cit.gvsig.fmap.AtomicEvent)
1468
                 */
1469
                public void atomicEvent(AtomicEvent e) {
1470
                        boolean redraw = false;
1471
                        LayerEvent[] layerEvents = e.getLayerEvents();
1472

    
1473
                        for (int i = 0; i < layerEvents.length; i++) {
1474
                                if (layerEvents[i].getProperty().equals("visible")) {
1475
                                        redraw = true;
1476
                                }
1477
                        }
1478

    
1479
                        if (e.getColorEvents().length > 0) {
1480
                                redraw = true;
1481
                        }
1482

    
1483
                        if (e.getExtentEvents().length > 0) {
1484
                                redraw = true;
1485
                        }
1486

    
1487
                        if (e.getProjectionEvents().length > 0) {
1488
                                //redraw = true;
1489
                        }
1490

    
1491

    
1492
                        LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1493
                        if (aux.length > 0) {
1494
                                for (int i=0; i < aux.length; i++)
1495
                                {
1496
                                        if (aux[i].getAffectedLayer().getFLayerStatus().isDriverLoaded())
1497
                                        {
1498
                                                redraw = true;
1499
                                                break;
1500
                                        }
1501
                                }
1502

    
1503
                        }
1504

    
1505
                        if (e.getLegendEvents().length > 0) {
1506
                                redraw = true;
1507
                        }
1508

    
1509
                        if (e.getSelectionEvents().length > 0) {
1510
                                redraw = true;
1511
                        }
1512

    
1513
                        if (redraw) {
1514
                System.out.println("MapContextListener redraw");
1515
                                MapControl.this.drawMap(false);
1516
                        }
1517
                }
1518
        }
1519

    
1520
        /**
1521
         * <p>Gets the <code>ViewPort</code> of this component's {@link MapContext MapContext} .</p>
1522
         * 
1523
         * @see MapContext#getViewPort()
1524
         */
1525
        public ViewPort getViewPort() {
1526
                return vp;
1527
        }
1528

    
1529
        /**
1530
         * <p>Returns all registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
1531
         * 
1532
         * @return registered <code>Behavior</code> to this <code>MapControl</code>
1533
         * 
1534
         * @see #addMapTool(String, Behavior)
1535
         * @see #addMapTool(String, Behavior[])
1536
         * @see #getMapToolsKeySet()
1537
         * @see #hasTool(String)
1538
         */
1539
        public HashMap getNamesMapTools() {
1540
                return namesMapTools;
1541
        }
1542

    
1543
        /*
1544
         * (non-Javadoc)
1545
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
1546
         */
1547
        public void commandRepaint() {
1548
                drawMap(false);
1549
        }
1550

    
1551
        /*
1552
         * (non-Javadoc)
1553
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
1554
         */
1555
        public void commandRefresh() {
1556
                // TODO Auto-generated method stub
1557
        }
1558

    
1559
        /**
1560
         * <p>Equivalent operation to <i>undo</i>.</p>
1561
         * 
1562
         * <p>Exchanges the previous tool with the current one.</p>
1563
         * 
1564
         * @see #addMapTool(String, Behavior)
1565
         * @see #addMapTool(String, Behavior[])
1566
         * @see #setTool(String)
1567
         */
1568
        public void setPrevTool() {
1569
                setTool(prevTool);
1570
        }
1571

    
1572
        /**
1573
         * <p>Executes a <i>zoom in</i> operation centered at the center of the extent.</p>
1574
         * 
1575
         * <p>This implementation is designed for being invoked outside a <code>Behavior</code>, for example
1576
         *  by an action of pressing a button; and simulates that the event has been produced by 
1577
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1578
         *  <code>MapControl</code> object that's responsible for the <i>zoom in</i> operation.</p>
1579
         *  
1580
         * @see #zoomOut()
1581
         */
1582
        public void zoomIn() {
1583
                getMapContext().clearAllCachingImageDrawnLayers();
1584
                Behavior mapTool = (Behavior) namesMapTools.get("zoomIn");
1585
                ViewPort vp=getViewPort();
1586
                Rectangle2D r=getViewPort().getAdjustedExtent();
1587
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1588
                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);
1589
                try {
1590
                        mapTool.mousePressed(e);
1591
                        mapTool.mouseReleased(e);
1592
                } catch (BehaviorException t) {
1593
                        throwException(t);
1594
                }
1595
        }
1596
        
1597
        /**
1598
         * <p>Executes a <i>zoom out</i> operation centered at the center of the extent.</p>
1599
         * 
1600
         * <p>This implementation is thought for being invoked outside a <code>Behavior</code>, for example
1601
         *  by an action of pressing a button, and simulates that the event has been produced by 
1602
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1603
         *  <code>MapControl</code> object that's responsible for the <i>zoom out</i> operation.</p>
1604
         * 
1605
         * @see #zoomIn()
1606
         */
1607
        public void zoomOut() {
1608
                getMapContext().clearAllCachingImageDrawnLayers();
1609
                Behavior mapTool = (Behavior) namesMapTools.get("zoomOut");
1610
                ViewPort vp=getViewPort();
1611
                Rectangle2D r=getViewPort().getAdjustedExtent();
1612
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1613
                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);
1614
                try {
1615
                        mapTool.mousePressed(e);
1616
                        mapTool.mouseReleased(e);
1617
                } catch (BehaviorException t) {
1618
                        throwException(t);
1619
                }
1620
        }
1621

    
1622
        /**
1623
         * <p>Returns the shared <code>CancelDraw</code> object used by this component and its layers drawing processes, that determines
1624
         *  if the drawing process must be cancelled or can continue running.</p>
1625
         * 
1626
         * @return shared object that determines if the layers drawing process of this component can continue or must be cancelled
1627
         */
1628
        public CancelDraw getCanceldraw() {
1629
                return canceldraw;
1630
        }
1631
}