Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / MapControl.java @ 39079

History | View | Annotate | Download (67.6 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.FLayers;
71
import com.iver.cit.gvsig.fmap.layers.GraphicLayer;
72
import com.iver.cit.gvsig.fmap.layers.LayerCollectionEvent;
73
import com.iver.cit.gvsig.fmap.layers.LayerEvent;
74
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
75
import com.iver.cit.gvsig.fmap.tools.CompoundBehavior;
76
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
77
import com.iver.cit.gvsig.fmap.tools.Listeners.ToolListener;
78
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
79
import com.iver.utiles.exceptionHandling.ExceptionListener;
80
import com.iver.utiles.swing.threads.Cancellable;
81

    
82

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

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

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

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

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

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

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

    
223
    //private boolean drawerAlive = false;
224

    
225

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

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

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

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

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

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

    
291
    //private boolean isCancelled = true;
292

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

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

    
319
    //private Drawer drawer;
320

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

    
326
    // private boolean firstDraw = true;
327

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

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

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

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

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

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

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

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

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

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

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

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

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

    
446
                mapContext = model;
447

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

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

    
457
                mapContext.addAtomicEventListener(mapContextListener);
458

    
459
                status = DESACTUALIZADO;
460
        }
461

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

670
                                break;
671
                        }
672

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

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

    
706

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

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

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

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

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

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

    
801

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

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

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

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

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

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

    
871

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

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

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

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

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

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

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

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

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

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

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

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

    
1023
                ViewPort viewPort = mapContext.getViewPort();
1024

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

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

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

    
1057
                }
1058

    
1059

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

    
1065

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

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

    
1095

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1328

    
1329

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1488
                                currentMapTool.mouseWheelMoved(e);
1489

    
1490
                                // Si el tool actual no ha consumido el evento
1491
                                // entendemos que quiere el comportamiento por defecto.
1492
                                if (!e.isConsumed())
1493
                                {
1494
                                        // Para usar el primer punto sobre el que queremos centrar
1495
                                        // el mapa, dejamos pasar un segundo para considerar el siguiente
1496
                                        // punto como v?lido.
1497
                                        // CAMBIO: DESPISTA MUCHO USAR ESE PUNTO, ES MEJOR USAR EL CENTRO
1498
                                        ViewPort vp = getMapContext().getViewPort();
1499
                                        if (vp == null) return;
1500
                                        if (vp.getAdjustedExtent() == null) return;
1501
//                                        if (t1 == 0)
1502
//                                        {
1503
//                                                t1= System.currentTimeMillis();
1504
//                                                //pReal = vp.toMapPoint(e.getPoint());
1505
//                                                // NO usar pReal, se cambia en otros tools
1506
//                                                
1507
//                                                pAux = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1508
//                                                                vp.getAdjustedExtent().getCenterY()); 
1509
//                                        }
1510
//                                        else
1511
//                                        {
1512
//                                                long t2 = System.currentTimeMillis();
1513
//                                                if ((t2-t1) > 1000)
1514
//                                                        t1=0;
1515
//                                        }
1516
                                        cancelDrawing();
1517
                                        
1518

    
1519

    
1520
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1521
                                                        vp.getAdjustedExtent().getCenterY()); */
1522
                                        int amount = e.getWheelRotation();
1523
                                        double nuevoX;
1524
                                        double nuevoY;
1525
                                        double factor;
1526

    
1527
                                        if (amount < 0) // nos acercamos
1528
                                        {
1529
                                                factor = 0.85;
1530
                                        } else // nos alejamos
1531
                                        {
1532
                                                factor = 1.25;
1533
                                        }
1534
                                        Rectangle2D r = vp.getAdjustedExtent();
1535
                                        pAux = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1536
                                                        vp.getAdjustedExtent().getCenterY()); 
1537
                                        
1538
                                        double w = r.getWidth();
1539
                                        double h = r.getHeight();
1540
                                        double cornerX = pAux.getX()
1541
                                                        - ((w * factor) / 2.0);
1542
                                        double cornerY = pAux.getY()
1543
                                                        - ((h * factor) / 2.0);
1544
                                        r = new Rectangle2D.Double();
1545
                                        r.setFrameFromCenter(pAux.getX(), pAux.getY(), cornerX, cornerY);
1546
                                        vp.setExtent(r);
1547

    
1548

    
1549
                                }
1550
                        } catch (BehaviorException t) {
1551
                                throwException(t);
1552
                        }
1553
                }
1554

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

    
1568
                /**
1569
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
1570
                 * @see Behavior#mouseMoved(MouseEvent)
1571
                 */
1572
                public void mouseMoved(MouseEvent e) {
1573
                        try {
1574
                                if (currentMapTool != null)
1575
                                        currentMapTool.mouseMoved(e);
1576
                        } catch (BehaviorException t) {
1577
                                throwException(t);
1578
                        }
1579
                }
1580
        }
1581

    
1582
        /**
1583
         * <p<code>MapContextListener</code> listens all events produced in a <code>MapControl</code>'s <code>MapContext</code>
1584
         * object during an atomic period of time, and sets it to dirty, <i>executing <code>drawMap(false)</code>, if any of the
1585
         * following conditions is accomplished</i>:
1586
         * <ul>
1587
         *  <li>Any of the <code>LayerEvent</code> in the <code>AtomicEvent</code> parameter notifies a <i>visibility change</i>.</li>
1588
         *  <li>There is at least one <code>ColorEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1589
         *  <li>There is at least one <code>ExtentEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1590
         *  <li>Any of the <code>LayerCollectionEvent</code> in the <code>AtomicEvent</code> parameter notifies that a driver's layer has reloaded it successfully.</li>
1591
         *  <li>There is at least one <code>LegendEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1592
         *  <li>There is at least one <code>SelectionEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1593
         * </ul>
1594
         * </p>
1595
         *
1596
         * @author Fernando Gonz?lez Cort?s
1597
         */
1598
        public class MapContextListener implements AtomicEventListener {
1599
                /**
1600
                 * @see com.iver.cit.gvsig.fmap.AtomicEventListener#atomicEvent(com.iver.cit.gvsig.fmap.AtomicEvent)
1601
                 */
1602
                public void atomicEvent(AtomicEvent e) {
1603
                        LayerEvent[] layerEvents = e.getLayerEvents();
1604

    
1605
                        int eType;
1606
                        for (int i = 0; i < layerEvents.length; i++) {
1607
                                eType=layerEvents[i].getEventType();
1608
//                                if (eType == LayerEvent.DRAW_VALUES_CHANGED || eType == LayerEvent.VISIBILITY_CHANGED) {
1609
//                                        MapControl.this.drawMap(false);
1610
//                                        return;
1611
//                                }
1612
                                if (layerEvents[i].getProperty().equals("visible")) {
1613
                                        MapControl.this.drawMap(false);
1614
                                        return;
1615
                                } else if (layerEvents[i].getEventType() == LayerEvent.EDITION_CHANGED){
1616
                                        MapControl.this.drawMap(false);
1617
                                        return;
1618
                                }
1619

    
1620
                        }
1621

    
1622
                        if (e.getColorEvents().length > 0) {
1623
                                MapControl.this.drawMap(false);
1624
                                return;
1625
                        }
1626

    
1627
                        if (e.getExtentEvents().length > 0) {
1628
                                MapControl.this.drawMap(false);
1629
                                return;
1630
                        }
1631

    
1632
                        if (e.getProjectionEvents().length > 0) {
1633
                                //redraw = true;
1634
                        }
1635

    
1636

    
1637
                        LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1638
                        if (aux.length > 0) {
1639
                                boolean bNeedRepaint = false;
1640
                                for (int i=0; i < aux.length; i++)
1641
                                {
1642
                                        if (aux[i].getAffectedLayer().getFLayerStatus().isDriverLoaded())
1643
                                        {
1644
                                                bNeedRepaint = true;
1645
                                                break;
1646
                                        }
1647
                                }
1648
                                if (bNeedRepaint) {
1649
                                        // If a layer has been added or removed, we redraw the whole map
1650
                                        // but once only.
1651
                                        MapControl.this.drawMap(false);
1652
                                        return;
1653
                                }
1654
                        }
1655

    
1656
                        if (e.getLegendEvents().length > 0) {
1657
                                MapControl.this.drawMap(false);
1658
                                return;
1659
                        }
1660

    
1661
                        if (e.getSelectionEvents().length > 0) {
1662
                                MapControl.this.drawMap(false);
1663
                                return;
1664
                        }
1665
                }
1666
        }
1667

    
1668
        /**
1669
         * <p>Gets the <code>ViewPort</code> of this component's {@link MapContext MapContext} .</p>
1670
         *
1671
         * @see MapContext#getViewPort()
1672
         */
1673
        public ViewPort getViewPort() {
1674
                return vp;
1675
        }
1676

    
1677
        /**
1678
         * <p>Returns all registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
1679
         *
1680
         * @return registered <code>Behavior</code> to this <code>MapControl</code>
1681
         *
1682
         * @see #addMapTool(String, Behavior)
1683
         * @see #addMapTool(String, Behavior[])
1684
         * @see #getMapToolsKeySet()
1685
         * @see #hasTool(String)
1686
         */
1687
        public HashMap getNamesMapTools() {
1688
                return namesMapTools;
1689
        }
1690

    
1691
        /*
1692
         * (non-Javadoc)
1693
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
1694
         */
1695
        public void commandRepaint() {
1696
                drawMap(false);
1697
        }
1698

    
1699
        /*
1700
         * (non-Javadoc)
1701
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
1702
         */
1703
        public void commandRefresh() {
1704
                // TODO Auto-generated method stub
1705
        }
1706

    
1707
        /**
1708
         * <p>Equivalent operation to <i>undo</i>.</p>
1709
         *
1710
         * <p>Exchanges the previous tool with the current one.</p>
1711
         *
1712
         * @see #addMapTool(String, Behavior)
1713
         * @see #addMapTool(String, Behavior[])
1714
         * @see #setTool(String)
1715
         */
1716
        public void setPrevTool() {
1717
                setTool(prevTool);
1718
        }
1719

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

    
1745
        /**
1746
         * <p>Executes a <i>zoom out</i> operation centered at the center of the extent.</p>
1747
         *
1748
         * <p>This implementation is thought for being invoked outside a <code>Behavior</code>, for example
1749
         *  by an action of pressing a button, and simulates that the event has been produced by
1750
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1751
         *  <code>MapControl</code> object that's responsible for the <i>zoom out</i> operation.</p>
1752
         *
1753
         * @see #zoomIn()
1754
         */
1755
        public void zoomOut() {
1756
//                getMapContext().clearAllCachingImageDrawnLayers();
1757
                Behavior mapTool = (Behavior) namesMapTools.get("zoomOut");
1758
                ViewPort vp=getViewPort();
1759
                Rectangle2D r=getViewPort().getAdjustedExtent();
1760
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1761
                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);
1762
                try {
1763
                        mapTool.mousePressed(e);
1764
                        mapTool.mouseReleased(e);
1765
                } catch (BehaviorException t) {
1766
                        throwException(t);
1767
                }
1768
        }
1769

    
1770
        /**
1771
         * <p>Returns the listener used to catch all mouse events produced in this <code>MapControl</code> instance
1772
         *  and that redirects the calls to the current map tool.</p>
1773
         *
1774
         * @return the map tool listener used
1775
         */
1776
        public MapToolListener getMapToolListener() {
1777
                return mapToolListener;
1778
        }
1779

    
1780
//         mapTool can be null, for instance, in 3D's navigation tools
1781
        /**
1782
         * <p>Sets <code>mapTool</code> as this <code>MapControl</code>'s current map tool.
1783
         *
1784
         * @param mapTool a map tool, or <code>null</code> to disable the interaction with the user
1785
         *
1786
         * @see #getCurrentMapTool()
1787
         * @see #getCurrentTool()
1788
         * @see #setTool(String)
1789
         * @see #setPrevTool()
1790
         * @see #addMapTool(String, Behavior)
1791
         * @see #addMapTool(String, Behavior[])
1792
         */
1793
        public void setCurrentMapTool(Behavior mapTool ){
1794
                currentMapTool = mapTool;
1795
        }
1796

    
1797
        /**
1798
         * <p>Sets the delay to the timer that refreshes this <code>MapControl</code> instance.</p>
1799
         *
1800
         * <p><code>Delay (in ms) = 1000 / getDrawFrameRate()</code></p>
1801
         *
1802
         * @see #getDrawFrameRate()
1803
         * @see #setDrawFrameRate(int)
1804
         */
1805
        public void applyFrameRate() {
1806
                if (getDrawFrameRate()>0) {
1807
                        timer.setDelay(1000/getDrawFrameRate());
1808
                }
1809
        }
1810

    
1811
        /**
1812
         * <p>Returns the draw frame rate.</p>
1813
         *
1814
         * <p>Draw frame rate is the number of repaints of this <code>MapControl</code> instance that timer invokes per second.</p>
1815
         *
1816
         * @return number of repaints of this <code>MapControl</code> instance that timer invokes per second
1817
         *
1818
         * @see #applyFrameRate()
1819
         * @see #setDrawFrameRate(int)
1820
         */
1821
        public static int getDrawFrameRate() {
1822
                return drawFrameRate;
1823
        }
1824

    
1825
        /**
1826
         * <p>Sets the draw frame rate.</p>
1827
         *
1828
         * <p>Draw frame rate is the number of repaints of this <code>MapControl</code> instance that timer invokes per second.</p>
1829
         *
1830
         * @param drawFrameRate number of repaints of this <code>MapControl</code> instance that timer invokes per second
1831
         *
1832
         * @see #applyFrameRate()
1833
         * @see #getDrawFrameRate()
1834
         */
1835
        public static void setDrawFrameRate(int drawFrameRate) {
1836
                MapControl.drawFrameRate = drawFrameRate;
1837
        }
1838

    
1839
        /**
1840
         * <p>Determines if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1841
         *
1842
         * @return <code>true</code> if its enabled; otherwise <code>false</code>
1843
         */
1844
        public static boolean isDrawAnimationEnabled() {
1845
                return drawAnimationEnabled;
1846
        }
1847

    
1848
        /**
1849
         * <p>Sets if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1850
         *
1851
         * @param drawAnimationEnabled <code>true</code> to enable the mode; otherwise <code>false</code>
1852
         */
1853
        public static void setDrawAnimationEnabled(boolean drawAnimationEnabled) {
1854
                MapControl.drawAnimationEnabled = drawAnimationEnabled;
1855
        }
1856

    
1857
        /**
1858
         * <p>Gets the shared object that determines if a drawing process must be cancelled or can continue.</p>
1859
         *
1860
         * @return the shared object that determines if a drawing process must be cancelled or can continue
1861
         */
1862
        public CancelDraw getCanceldraw() {
1863
                return canceldraw;
1864
        }
1865

    
1866
        /**
1867
         * <p>Adds a new tool as combined tool.</p>
1868
         * <p>The new tool will be stored with the previous combined tools, and will be combined with
1869
         *  the current tool.</p>
1870
         * <p>If <code>tool</code> was already stored as a combined tool, doesn't adds it.</p>
1871
         *
1872
         * @param tool a new tool to be used combined with the current tool
1873
         */
1874
        public void addCombinedTool(Behavior tool) {
1875
                if (combinedTool == null) {
1876
                        combinedTool = tool;
1877
                }
1878
                else {
1879
                        if (combinedTool instanceof CompoundBehavior) {
1880
                                if (((CompoundBehavior)combinedTool).containsBehavior(tool))
1881
                                        return;
1882

    
1883
                                ((CompoundBehavior)combinedTool).addMapBehavior(tool, true);
1884
                        }
1885
                        else {
1886
                                if (combinedTool.equals(tool))
1887
                                        return;
1888

    
1889
                                combinedTool = new CompoundBehavior(new Behavior[] {combinedTool});
1890
                                ((CompoundBehavior)combinedTool).addMapBehavior(tool, true);
1891
                        }
1892
                }
1893

    
1894
                if (currentMapTool == null)
1895
                        return;
1896

    
1897
                if (currentMapTool instanceof CompoundBehavior) {
1898
                        ((CompoundBehavior)currentMapTool).addMapBehavior(tool, true);
1899
                }
1900
                else {
1901
                        currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool});
1902
                        ((CompoundBehavior)currentMapTool).addMapBehavior(tool, true);
1903
                }
1904
        }
1905

    
1906
        /**
1907
         * <p>Gets the tool used in combination with the current tool of this <code>MapControl</code>.</p>
1908
         *
1909
         * @return the tool used in combination with the <code>currentMapTool</code>; <code>null</code> if there is
1910
         *  no combined tool
1911
         */
1912
        public Behavior getCombinedTool() {
1913
                return combinedTool;
1914
        }
1915

    
1916
        /**
1917
         * <p>Sets a tool to be used in combination with the current tool of this <code>MapControl</code>.</p>
1918
         *
1919
         * @param combinedTool a tool to be used in combination with the current tool of <code>MapControl</code>
1920
         */
1921
        public void setCombinedTool(Behavior combinedTool) {
1922
                this.combinedTool = combinedTool;
1923

    
1924
                if (currentMapTool == null)
1925
                        return;
1926

    
1927
                if (currentMapTool instanceof CompoundBehavior) {
1928
                        ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true);
1929
                }
1930
                else {
1931
                        currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool});
1932
                        ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true);
1933
                }
1934
        }
1935

    
1936
        /**
1937
         * <p>Removes the tool used in combination with the current tool of this <code>MapControl</code>.</p>
1938
         */
1939
        public void removeCombinedTool() {
1940
                if ((currentMapTool != null) && (currentMapTool instanceof CompoundBehavior)) {
1941
                                ((CompoundBehavior)currentMapTool).removeMapBehavior(combinedTool);
1942
                }
1943

    
1944
                combinedTool = null;
1945
        }
1946

    
1947
        /**
1948
         * <p>Removes the tool <code>tool</code> used in combination with the current tool of this <code>MapControl</code>.</p>
1949
         */
1950
        public void removeCombinedTool(Behavior tool) {
1951
                if ((currentMapTool != null) && (currentMapTool instanceof CompoundBehavior)) {
1952
                                ((CompoundBehavior)currentMapTool).removeMapBehavior(tool);
1953
                }
1954

    
1955
                if (combinedTool == null)
1956
                        return;
1957

    
1958
                if (combinedTool instanceof CompoundBehavior) {
1959
                        ((CompoundBehavior)combinedTool).removeMapBehavior(tool);
1960
                }
1961
                else {
1962
                        combinedTool = null;
1963
                }
1964
        }
1965
}