Statistics
| Revision:

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

History | View | Annotate | Download (64.7 KB)

1 1223 fernando
/* 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 1282 fjp
import java.awt.Color;
44 6266 fjp
import java.awt.Component;
45 1223 fernando
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 5874 fjp
import java.awt.geom.Point2D;
58
import java.awt.geom.Rectangle2D;
59 1223 fernando
import java.awt.image.BufferedImage;
60
import java.util.HashMap;
61 6777 jmvivo
import java.util.Set;
62 1223 fernando
63
import javax.swing.JComponent;
64
import javax.swing.Timer;
65
66
import org.cresques.cts.IProjection;
67
68 6164 luisw2
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
69 4120 caballero
import com.iver.cit.gvsig.fmap.edition.commands.CommandListener;
70 14573 vcaballero
import com.iver.cit.gvsig.fmap.layers.LayerCollectionEvent;
71 1223 fernando
import com.iver.cit.gvsig.fmap.layers.LayerEvent;
72
import com.iver.cit.gvsig.fmap.tools.BehaviorException;
73
import com.iver.cit.gvsig.fmap.tools.CompoundBehavior;
74
import com.iver.cit.gvsig.fmap.tools.Behavior.Behavior;
75
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
76
import com.iver.utiles.exceptionHandling.ExceptionListener;
77 5317 fjp
import com.iver.utiles.swing.threads.Cancellable;
78 1223 fernando
79
80
/**
81 20098 jmvivo
 * <p>A component that includes a {@link MapContext MapContext} with support for use it as a particular {@link Behavior Behavior}.</p>
82 1223 fernando
 *
83 20098 jmvivo
 * <p>A developer can register a set of <code>Behavior</code>, but only one (that can be a composition of several) of them can be active. The active one
84
 *  defines the way to work and access with its <code>MapContext</code>'s layers. The active behavior, in combination with the appropriate
85
 *  {@link ToolListener ToolListener} will allow user work with a particular <i>tool</i>.</p>
86
 *
87
 * <p>All mouse events produced on this component will be delegated to the current active behavior, the <i>currentMapTool</i>.</p>
88 20397 vcaballero
 *
89 20098 jmvivo
 * <p><b>Drawing process:</b></p>
90 20397 vcaballero
 *
91 20098 jmvivo
 * <p>Uses a double buffer for the drawing process of <code>MapContext</code>'s information.</p>
92 20397 vcaballero
 *
93 20098 jmvivo
 * <p>If the double buffer wasn't created, creates a new one.</p>
94 20397 vcaballero
 *
95 20098 jmvivo
 * <p>Paints the component according the following algorithm:
96
 * <br>
97
 *  &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
98
 *  &nbsp &nbsp If there is a <i>double buffer</i>:<br>
99
 *  &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the <code>MapControl</code> instance, delegates
100
 *   the drawing process to that behavior, calling: <code><i>behavior_instance</i>.paintComponent(g)</code>.<br>
101
 *  &nbsp &nbsp &nbsp Else, repaints the current graphical information quickly calling: <code>g.drawImage(image,0,0,null)</code>.<br>
102
 *  &nbsp Else, (<i>status</i> is <i>OUTDATED</i>, or <i>ONLY_GRAPHICS</i>): executes a quickly repaint of the previous information calling <code>g.drawImage(image,0,0,null)</code>, and creates
103
 *   a <i>painting request</i> to delegate the heavy drawing process to the {@link Drawer2 Drawer2}'s worker thread, according the <i>SingleWorketThread</i> pattern, starting a timer to update
104
 *   (invoking <code>repaint()</code>) the view every delay of <code>1000 / drawFrameRate</code> ms. during that heavy drawing process, and if its enabled <code>drawAnimationEnabled</code>. The <i>painting request</i> once is being attended, invokes <code>MapContext</code> to
105 20397 vcaballero
 *   draw the layers: <code>mapContext.draw(image, g, cancel,mapContext.getScaleView());</code>
106 20098 jmvivo
 * <br>
107
 * <p>Some notes:
108
 *  <ul>
109
 *   <li>The painting process can be cancelled calling {@link #cancelDrawing() #cancelDrawing()}.</li>
110
 *   <li>At last resort, the particular implementation of each layer in a <code>MapControl</code>'s <code>MapContrext</code>
111
 *    will be that one which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</li>
112
 *   <li>It's possible to force repaint all layers, calling {@link #drawMap(boolean doClear) #drawMap(boolean)}.</li>
113
 *   <li>It's possible repaint only the dirty layers, calling {@link #rePaintDirtyLayers() #rePaintDirtyLayers()}.</li>
114
 *   <li>It's possible repaint only the {@link GraphicLayer GraphicLayer}, calling {@link #drawGraphics() #drawGraphics()}.</li>
115 20397 vcaballero
 *  </ul>
116 20098 jmvivo
 * </p>
117 20397 vcaballero
 *
118 20098 jmvivo
 * <p><b>Tools:</b></p>
119 20397 vcaballero
 *
120 20098 jmvivo
 * <p>A developer can:
121
 *   <ul>
122
 *    <li>Register each tool as:
123
 *     <ul>
124
 *      <li>A single behavior: {@link #addMapTool(String, Behavior) #addMapTool(String, Behavior)}.</li>
125
 *      <li>Or, a compound behavior: {@link #addMapTool(String, Behavior) #addMapTool(String, Behavior)}.</li>
126
 *     </ul>
127
 *    </li>
128
 *    <li>Get the current active tool: {@link #getCurrentMapTool() #getCurrentMapTool()}.</li>
129
 *    <li>Get the current active tool name: {@link #getCurrentTool() #getCurrentTool()}.</li>
130
 *    <li>Get a registered tool: {@link #getMapTool(String) #getMapTool(String)}.</li>
131
 *    <li>Get the name of all tools registered: {@link #getMapToolsKeySet() #getMapToolsKeySet()}.</li>
132
 *    <li>Get all tools registered, including the name they were registered: {@link #getNamesMapTools() #getNamesMapTools()}.</li>
133
 *    <li>Determine if has a tool registered: {@link #hasTool(String) #hasTool(String)}.</li>
134
 *    <li>Set as an active tool, one of the registered: {@link #setTool(String) #setTool(String)}.</li>
135
 *    <li>Set as active tool, the previous used: {@link #setPrevTool() #setPrevTool()}.</li>
136
 *    <li>Set the current tool: {@link #setCurrentMapTool(Behavior) #setCurrentMapTool(Behavior)}.</li>
137
 *    <li>Change the draw frame rate: {@link #setDrawFrameRate(int) #setDrawFrameRate(int)} and {@link #applyFrameRate() #applyFrameRate()}.</li>
138
 *    <li>Get the draw frame rate: {@link #getDrawFrameRate() #getDrawFrameRate()}.</li>
139
 *    <li>Determine if will repaint this component each time timer finishes: {@link #isDrawAnimationEnabled() #isDrawAnimationEnabled()}.</li>
140
 *    <li>Change if will repaint this component each time timer finishes: {@link #setDrawAnimationEnabled(boolean) #setDrawAnimationEnabled(boolean)}.</li>
141
 *    <li>Get the shared object that determines if a drawing process must be cancelled or can continue: {@link #getCanceldraw() #getCanceldraw()}.</li>
142 20358 vcaballero
 *    <li>Get the combined tool: {@link #getCombinedTool() #getCombinedTool()}.</li>
143
 *    <li>Set a combined tool: {@link #setCombinedTool(Behavior) #setCombinedTool(Behavior)}.</li>
144
 *    <li>Remove the combined tool: {@link #removeCombinedTool() #removeCombinedTool()}.</li>
145 20098 jmvivo
 *   </ul>
146
 * </p>
147
 *
148
 * <p><b>Exception listener:</b></p>
149 20397 vcaballero
 *
150
 * <p> Adding an <code>ExceptionListener</code>, can get notification about any exception produced:
151 20098 jmvivo
 *  <ul>
152
 *   <li>Attending a <i>painting request</i>.</li>
153
 *   <li>Working with the active tool.</li>
154
 *   <li>Applying a <i>zoom in</i> or <i>zoom out</i> operation.</li>
155
 *  </ul>
156
 * </p>
157 20397 vcaballero
 *
158 20098 jmvivo
 * <p><b>Other:</b></p>
159 20397 vcaballero
 *
160 20098 jmvivo
 * <p>Other useful capabilities of <code>MapControl</code>:
161
 *   <ul>
162
 *    <li>Cancel the current drawing process (notifying it also to the inner
163
 *     <code>MapContext</code> instance and its layers): {@link #cancelDrawing() #cancelDrawing()}.</li>
164
 *    <li>Applying a <i>zoom in</i> operation centered at mouse position (without a <code>ToolListener</code>): {@link #zoomIn() #zoomIn()}.</li>
165
 *    <li>Applying a <i>zoom out</i> operation centered at mouse position (without a <code>ToolListener</code>): {@link #zoomOut() #zoomOut()}.</li>
166
 *   </ul>
167
 * </p>
168 20397 vcaballero
 *
169 20098 jmvivo
 * @see CancelDraw
170
 * @see Drawer2
171
 * @see MapContextListener
172
 * @see MapToolListener
173 20397 vcaballero
 *
174 1223 fernando
 * @author Fernando Gonz?lez Cort?s
175 20358 vcaballero
 * @author Pablo Piqueras Bartolom? (pablo.piqueras@iver.es)
176 1223 fernando
 */
177 20098 jmvivo
public class MapControl extends JComponent implements ComponentListener, CommandListener {
178
        /**
179
         * <p>One of the possible status of <code>MapControl</code>. Determines that all visible information has been
180 20397 vcaballero
         * drawn and its updated.</p>
181 20098 jmvivo
         */
182 1223 fernando
        public static final int ACTUALIZADO = 0;
183
184 20098 jmvivo
        /**
185
         * <p>One of the possible status of <code>MapControl</code>. Determines that not all visible information has been
186 20397 vcaballero
         * drawn or isn't updated.</p>
187 20098 jmvivo
         */
188 1223 fernando
        public static final int DESACTUALIZADO = 1;
189 20397 vcaballero
190 20098 jmvivo
        /**
191
         * <p>One of the possible status of <code>MapControl</code>. Determines that only the graphical layer must
192 20397 vcaballero
         * be drawn / updated.</p>
193 20098 jmvivo
         */
194
        public static final int ONLY_GRAPHICS = 2;
195
196
        /**
197
         * <p>Determines the number of frames.</p>
198
         *
199
         * <p>Number of updates per second that the timer will invoke repaint this component.</p>
200
         */
201 13733 jaume
    private static int drawFrameRate = 3;
202 20098 jmvivo
203
    /**
204
     * <p>Determines if the drawer can update this <code>MapControl</code> instance when the timer launches an event.</p>
205
     */
206 13733 jaume
    private static boolean drawAnimationEnabled = true;
207
208 3346 fjp
    // public static final int FAST_PAINT = 3;
209 2531 caballero
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
210 20098 jmvivo
211
    /**
212
     * <p>Inner model with the layers, event support for drawing them, and the <code>ViewPort</code>
213
     *  with information to adapt to the bounds available in <i>image coordinates</i>.</p>
214 20397 vcaballero
     *
215 20098 jmvivo
     * @see #getMapContext()
216 20397 vcaballero
     * @see #setMapContext(MapContext)
217 20098 jmvivo
     */
218
    private MapContext mapContext = null;
219
220 3719 caballero
    //private boolean drawerAlive = false;
221 20098 jmvivo
222
223
        /**
224
         * <p>All registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
225 20397 vcaballero
         *
226 20098 jmvivo
         * <p>Only one of them can be active at a given moment.</p>
227 20397 vcaballero
         *
228 20098 jmvivo
         * @see #addMapTool(String, Behavior)
229
         * @see #addMapTool(String, Behavior[])
230
         * @see #getMapTool(String)
231 20397 vcaballero
         * @see #getMapToolsKeySet()
232 20098 jmvivo
         * @see #getNamesMapTools()
233
         */
234
    protected HashMap namesMapTools = new HashMap();
235
236
        /**
237
         * <p>Active {@link Behavior Behavior} that will generate events according a criterion, and then, with a {@link ToolListener ToolListener}
238
         *  associated, will simulate to user that works with this component as a particular tool.</p>
239 20397 vcaballero
         *
240 20098 jmvivo
         * @see #getCurrentMapTool()
241
         * @see #getCurrentTool()
242 20397 vcaballero
         * @see #setTool(String)
243 20098 jmvivo
         */
244
    protected Behavior currentMapTool = null;
245
246
        /**
247
         * <p>Determines which's the current drawn status of this component:
248
         * <ul>
249
         *  <li><b>OUTDATED</b>: all visible information has been drawn or isn't updated.</li>
250
         *  <li><b>UTDATED</b>: all visible information has been drawn and its updated.</li>
251
         *  <li><b>ONLY_GRAPHICS</b>: only the graphical layer must be drawn / updated.</li>
252
         * </ul>
253
         * </p>
254 20397 vcaballero
         *
255 20098 jmvivo
         * <p>The <code>MapControl</code> drawing process will consider the value of this parameter to decide which elements will
256
         *  be updated or drawn.</p>
257
         */
258
    private int status = DESACTUALIZADO;
259
260
        /**
261
         * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
262 20397 vcaballero
         *
263 20098 jmvivo
         * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
264
         * Meanwhile, the previous image can be kept showed.</p>
265 20397 vcaballero
         *
266 20098 jmvivo
         * @see BufferedImage
267 20397 vcaballero
         *
268 20098 jmvivo
         * @see #getImage()
269
         */
270
    private BufferedImage image = null;
271
272
        /**
273
         * <p>Name of the tool used currently to interact with this component.</p>
274 20397 vcaballero
         *
275 20098 jmvivo
         * @see #getCurrentTool()
276 20397 vcaballero
         * @see #setTool(String)
277 20098 jmvivo
         */
278
    protected String currentTool;
279
280
        /**
281
         * <p>Object to store the flag that notifies a drawing thread task and <code>MapContext</code>'s layers,
282
         * that must be canceled or can continue with the process.</p>
283 20397 vcaballero
         *
284 20098 jmvivo
         * @see #cancelDrawing()
285
         */
286
    private CancelDraw canceldraw;
287
288
    //private boolean isCancelled = true;
289
290
        /**
291
         * <p>Fires an action events after a specified delay.</p>
292 20397 vcaballero
         *
293 20098 jmvivo
         * <p><code>MapControl</code> will use the timer to update its visible graphical information during
294
         *  a drawing process, or allowing to cancel that process.</p>
295 20397 vcaballero
         *
296 20098 jmvivo
         * <p>This is very useful to pretend faster interactivity to user when <code>MapControl</code> has
297
         *  lots of layers, and / or layers with heavy graphical elements, that need a long time to finish
298 20397 vcaballero
         *  drawing all its data.</p>
299 20098 jmvivo
         */
300
    private Timer timer;
301
302
        /**
303
         * <p>Reference to the {@link ViewPort ViewPort} of the {@link MapContext MapContext} of this component.</p>
304 20397 vcaballero
         *
305 20098 jmvivo
         * <p>The view port once is created an instance of <code>MapControl</code>,
306
         *  is obtained from the <i>EPSG:23030</i> projection, that's the default projection for this component.</p>
307 20397 vcaballero
         *
308 20098 jmvivo
         * <p>After, the view port will change adapting itself according the current projection and the extent.</p>
309 20397 vcaballero
         *
310 20098 jmvivo
         * @see #getViewPort()
311 20397 vcaballero
         *
312 20098 jmvivo
         * @see ViewPort
313
         */
314
    protected ViewPort vp;
315
316
    //private Drawer drawer;
317
318
        /**
319
         * <p>Manager of all <code>MapControl</code> painting requests.</p>
320
         */
321 3368 fjp
    private Drawer2 drawer2;
322 20098 jmvivo
323 3372 fjp
    // private boolean firstDraw = true;
324 4619 caballero
325 20098 jmvivo
        /**
326
         * <p>Listener of all kind of mouse events produced in this component.</p>
327 20397 vcaballero
         *
328 20098 jmvivo
         * <p>Delegates each mouse event to the current map tool.</p>
329 20397 vcaballero
         *
330 20098 jmvivo
         * @see #addMapTool(String, Behavior)
331
         * @see #addMapTool(String, Behavior[])
332
         * @see #getMapTool(String)
333
         * @see #getMapToolsKeySet()
334
         * @see #getNamesMapTools()
335
         * @see #setTool(String)
336
         */
337
    protected MapToolListener mapToolListener = new MapToolListener();
338
339
        /**
340
         * <p>Listener of all events produced in a this component's <code>MapContext</code>
341
         * object during an atomic period of time.</p>
342
         */
343
    private MapContextListener mapContextListener = new MapContextListener();
344
345
        /**
346
         * <p>Group of <code>ExceptionListener</code> that, in whatever moment could be notified a Throwable Java error or exception.</p>
347 20397 vcaballero
         *
348 20098 jmvivo
         * @see #addExceptionListener(ExceptionListener)
349
         * @see #removeExceptionListener(ExceptionListener)
350
         */
351
    private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
352
353
    /**
354
     * <p>Name of the previous tool used.</p>
355
     */
356 12208 jcampos
        protected String prevTool;
357 4888 caballero
358 3719 caballero
        /**
359 20358 vcaballero
         * <p>Tool that will be used combined with the current tool of this <code>MapControl</code>.</p>
360
         */
361
        private Behavior combinedTool = null;
362
363
        /**
364 3331 fjp
     * We need this to avoid not wanted refresh. REMEMBER TO SET TO TRUE!!
365
     */
366
    // private boolean paintEnabled = false;
367 1223 fernando
368
        /**
369 20098 jmvivo
         * <p>Creates a new <code>MapControl</code> instance with the following characteristics:
370
         * <ul>
371
         *  <li><i>Name</i>: MapControl .</li>
372
         *  <li>Disables the double buffer of <code>JComponent</code> .</li>
373
         *  <li>Sets opaque <i>(see {@link JComponent#setOpaque(boolean)} )</i>. </li>
374
         *  <li>Sets its status to <code>OUTDATED</code> .</li>
375
         *  <li>Creates a new {@link CancelDraw CancelDraw} object to notify <code>MapContext</code>'s layers if can continue processing the drawn or must cancel it.</li>
376
         *  <li>Creates a new {@link MapContext MapContext} with a new {@link ViewPort ViewPort} in the projection <i>"EPSG:23030"</i> .</li>
377
         *  <li>Creates a new {@link CommandListener CommandListener} for edition operations.</li>
378
         *  <li>Creates a new {@link MapToolListener MapToolListener}, and associates it as a listener of whatever kind of mouse events produced in this component.</li>
379
         *  <li>Creates a new {@link Drawer2 Drawer2} for managing the painting requests.</li>
380
         *  <li>Creates a new timer that will invoke refresh this component <code>drawFrameRate</code> per second, when is running a drawing process, and its enabled
381
         *   <code>drawAnimationEnabled</code>.</li>
382
         * </ul>
383
         * </p>
384 1223 fernando
         */
385
        public MapControl() {
386 5787 jaume
                this.setName("MapControl");
387 1223 fernando
                setDoubleBuffered(false);
388
                setOpaque(true);
389
                status = DESACTUALIZADO;
390
391
                //Clase usada para cancelar el dibujado
392
                canceldraw = new CancelDraw();
393
394
                //Modelo de datos y ventana del mismo
395
                // TODO: Cuando creamos un mapControl, deber?amos asignar
396
                // la projecci?n por defecto con la que vayamos a trabajar.
397
                // 23030 es el c?digo EPSG del UTM30 elipsoide ED50
398 6164 luisw2
                vp = new ViewPort(CRSFactory.getCRS("EPSG:23030"));
399 6878 cesar
                setMapContext(new MapContext(vp));
400 3719 caballero
401 1223 fernando
                //eventos
402
                this.addComponentListener(this);
403
                this.addMouseListener(mapToolListener);
404
                this.addMouseMotionListener(mapToolListener);
405
                this.addMouseWheelListener(mapToolListener);
406
407 3368 fjp
        this.drawer2 = new Drawer2();
408 1223 fernando
                //Timer para mostrar el redibujado mientras se dibuja
409 13733 jaume
                timer = new Timer(1000/drawFrameRate,
410 1223 fernando
                                new ActionListener() {
411
                                        public void actionPerformed(ActionEvent e) {
412 14410 vcaballero
413 13733 jaume
                                                if (drawAnimationEnabled) {
414
                                                        MapControl.this.repaint();
415
                                                }
416 1223 fernando
                                        }
417
                                });
418
        }
419
420
        /**
421 20098 jmvivo
         * <p>Sets a <code>MapContext</code> to this component.</p>
422 20397 vcaballero
         *
423 20098 jmvivo
         * <p>The <code>MapContext</code> has the <i>model</i>, and most of the <i>view</i>,
424
         * and <i>control</i> logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the
425
         * information to the projection, and to display it in the available area.</p>
426 20397 vcaballero
         *
427 20098 jmvivo
         * <p>If <code>model</code> hadn't a <code>ViewPort</code>, assigns the current one to it, otherwise, use its <code>ViewPort</code>.</p>
428 20397 vcaballero
         *
429 20098 jmvivo
         * <p>After assigning the <code>MapContext</code> and <code>ViewPort</code>, sets the same {@link MapContextListener MapContextListener}
430
         *  that was using, and changes the <i>status</i> to <code>OUTDATED</code>.</p>
431 20397 vcaballero
         *
432 20098 jmvivo
         * @param model this component's <code>MapContext</code>, that includes the <code>ViewPort</code>.
433 20397 vcaballero
         *
434 20098 jmvivo
         * @see MapContext
435 20397 vcaballero
         *
436 20098 jmvivo
         * @see #getMapContext()
437 1223 fernando
         */
438 6878 cesar
        public void setMapContext(MapContext model) {
439 1223 fernando
                if (mapContext != null) {
440
                        mapContext.removeAtomicEventListener(mapContextListener);
441
                }
442
443
                mapContext = model;
444
445
                if (mapContext.getViewPort() == null) {
446
                        mapContext.setViewPort(vp);
447
                } else {
448
                        vp = mapContext.getViewPort();
449
450
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
451
                        //System.err.println("Viewport en setMapContext:" + vp);
452
                }
453
454
                mapContext.addAtomicEventListener(mapContextListener);
455
456
                status = DESACTUALIZADO;
457
        }
458
459
        /**
460 20098 jmvivo
         * <p>Gets this component's {@link MapContext MapContext} projection.</p>
461 1223 fernando
         *
462 20098 jmvivo
         * @return this component's {@link MapContext MapContext} projection
463 20397 vcaballero
         *
464 20098 jmvivo
         * @see MapContext#getProjection()
465
         * @see MapControl#setProjection(IProjection)
466 1223 fernando
         */
467
        public IProjection getProjection() {
468
                return getMapContext().getProjection();
469
        }
470
471
        /**
472 20098 jmvivo
         * <p>Sets the projection to this component's {@link MapContext MapContext}.</p>
473 1223 fernando
         *
474 20098 jmvivo
         * @param proj the kind of projection to this component's {@link MapContext MapContext}
475 20397 vcaballero
         *
476 20098 jmvivo
         * @see MapContext#setProjection(IProjection)
477
         * @see MapControl#getProjection()
478 1223 fernando
         */
479
        public void setProjection(IProjection proj) {
480
                getMapContext().setProjection(proj);
481
        }
482
483
        /**
484 20098 jmvivo
         * <p>Gets this component's <code>MapContext</code>, with the <i>model</i>, and most of the <i>view</i>,
485
         * and <i>control</i> logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the
486
         * information to the projection, and display it in the available area.</p>
487 20397 vcaballero
         *
488 20098 jmvivo
         * @return this component's <code>MapContext</code>, that includes the <code>ViewPort</code> used to project the
489
         * graphical information, and display it in the available area
490 20397 vcaballero
         *
491 20098 jmvivo
         * @see MapContext
492 20397 vcaballero
         *
493 20098 jmvivo
         * @see MapControl#setMapContext(MapContext)
494 1223 fernando
         */
495 6878 cesar
        public MapContext getMapContext() {
496 1223 fernando
                return mapContext;
497
        }
498
499
        /**
500 20098 jmvivo
         * <p>Registers a new behavior to this component.</p>
501 20397 vcaballero
         *
502 20098 jmvivo
         * <p>According the nature of the {@link Behavior Behavior}, different events will be generated. Those
503
         *  events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this
504
         *  <code>MapControl</code> object as a <i>tool</i>.</p>
505 1223 fernando
         *
506 20098 jmvivo
         * @param name name to identify the behavior to add
507
         * @param tool the behavior to add
508 20397 vcaballero
         *
509 20098 jmvivo
         * @see #addMapTool(String, Behavior[])
510
         * @see #getNamesMapTools()
511
         * @see #getMapToolsKeySet()
512
         * @see #hasTool(String)
513 1223 fernando
         */
514
        public void addMapTool(String name, Behavior tool) {
515
                namesMapTools.put(name, tool);
516
                tool.setMapControl(this);
517
        }
518
519 20098 jmvivo
        /**
520
         * <p>Registers a new behavior to this component as a {@link CompoundBehavior CompoundBehavior} made up of <code>tools</code>.</p>
521 20397 vcaballero
         *
522 20098 jmvivo
         * <p>According the nature of the behaviors registered, different events will be generated. Those
523
         *  events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this
524
         *  <code>MapControl</code> object as a <i>tool</i>.</p>
525
         *
526
         * @param name name to identify the compound behavior to add
527
         * @param tools the compound behavior to add
528 20397 vcaballero
         *
529 20098 jmvivo
         * @see #addMapTool(String, Behavior)
530
         * @see #getNamesMapTools()
531
         * @see #getMapToolsKeySet()
532
         * @see #hasTool(String)
533
         */
534 1223 fernando
        public void addMapTool(String name, Behavior[] tools){
535
                CompoundBehavior tool = new CompoundBehavior(tools);
536
                addMapTool(name, tool);
537
        }
538 10837 caballero
539 6777 jmvivo
        /**
540 20098 jmvivo
         * <p>Gets the <code>Behavior</code> registered in this component, identified
541
         *  by <code>name</code>.</p>
542 6777 jmvivo
         *
543 20098 jmvivo
         * @param name name of a registered behavior
544 20397 vcaballero
         *
545 20098 jmvivo
         * @return tool the registered behavior in this component as <code>name</code>, or <code>null</code> if
546
         *  no one has that identifier
547 20397 vcaballero
         *
548 20098 jmvivo
         * @see #addMapTool(String, Behavior)
549
         * @see #addMapTool(String, Behavior[])
550
         * @see #hasTool(String)
551 6777 jmvivo
         */
552
        public Behavior getMapTool(String name) {
553
                return (Behavior)namesMapTools.get(name);
554
        }
555 3719 caballero
556 1223 fernando
        /**
557 20098 jmvivo
         * <p>Returns a set view of the keys that identified the tools
558
         *  registered.</p>
559 10837 caballero
         *
560 20098 jmvivo
         * @return a set view of the keys that identified the tools registered
561 20397 vcaballero
         *
562 20098 jmvivo
         * @see HashMap#keySet()
563 20397 vcaballero
         *
564 20098 jmvivo
         * @see #getNamesMapTools()
565
          * @see #addMapTool(String, Behavior)
566
          * @see #addMapTool(String, Behavior[])
567 6777 jmvivo
         */
568
        public Set getMapToolsKeySet() {
569
                return namesMapTools.keySet();
570
        }
571
572
        /**
573 20098 jmvivo
         * <p>Returns <code>true</code> if this component contains a tool identified by <code>toolName</code>.</p>
574 20397 vcaballero
         *
575 20098 jmvivo
         * @param toolName identifier of the tool
576 20397 vcaballero
         *
577 20098 jmvivo
         * @return <code>true</code> if this component contains a tool identified by <code>toolName</code>; otherwise <code>false</code>
578 20397 vcaballero
         *
579 20098 jmvivo
         * @see #addMapTool(String, Behavior)
580
         * @see #addMapTool(String, Behavior[])
581 6378 jaume
         */
582
        public boolean hasTool(String toolName) {
583
                return namesMapTools.containsKey(toolName);
584
        }
585 20098 jmvivo
586 6378 jaume
        /**
587 20098 jmvivo
         * <p>Sets as current active <code>Behavior</code> associated to this component, that one which
588
         *  is registered and identified by <code>toolName</code>.</p>
589 20397 vcaballero
         *
590 20098 jmvivo
         * <p>Changing the current active behavior for this <code>MapControl</code>, implies also updating the
591
         *  previous <i>behavior</i> tool, and the current cursor.</p>
592 20397 vcaballero
         *
593 20098 jmvivo
         * @param toolName name of a registered behavior
594 20397 vcaballero
         *
595 20098 jmvivo
         * @see #getCurrentMapTool()
596
         * @see #getCurrentTool()
597 1223 fernando
         */
598
        public void setTool(String toolName) {
599 6378 jaume
                prevTool=getCurrentTool();
600 1223 fernando
                Behavior mapTool = (Behavior) namesMapTools.get(toolName);
601
                currentMapTool = mapTool;
602
                currentTool = toolName;
603 20358 vcaballero
604
                if (combinedTool != null) {
605
                        if (mapTool instanceof CompoundBehavior) {
606
                                ((CompoundBehavior)mapTool).addMapBehavior(combinedTool, combinedTool.getListener().cancelDrawing());
607
                        }
608
                        else {
609
                                currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool, combinedTool});
610
                        }
611
                }
612
613 1223 fernando
                this.setCursor(mapTool.getCursor());
614
        }
615 20098 jmvivo
616
        /**
617
         * <p>Gets as current active <code>Behavior</code> associated to this component, that one which
618
         *  is registered and identified by <code>toolName</code>.</p>
619 20397 vcaballero
         *
620 20098 jmvivo
         * <p>Changing the current active behavior for this <code>MapControl</code>, implies also updating the
621
         *  previous <i>behavior</i> tool, and the current cursor.</p>
622 20397 vcaballero
         *
623 20098 jmvivo
         * @param toolName name of a registered behavior
624 20397 vcaballero
         *
625 20098 jmvivo
         * @see #getCurrentTool()
626
         * @see #setTool(String)
627
         */
628 3719 caballero
        public Behavior getCurrentMapTool(){
629
                return currentMapTool;
630
        }
631 20098 jmvivo
632 1223 fernando
        /**
633 20098 jmvivo
         * <p>Returns the name of the current selected tool on this MapControl</p>
634 1223 fernando
         *
635 20098 jmvivo
         * @return the name of the current's behavior tool associated to this component
636 20397 vcaballero
         *
637 20098 jmvivo
         * @see #getCurrentMapTool()
638
         * @see #setTool(String)
639 1223 fernando
         */
640 6378 jaume
        public String getCurrentTool() {
641 1223 fernando
                return currentTool;
642
        }
643
644
        /**
645 20098 jmvivo
         * <p>Determines that current drawing process of <code>MapControl</code>'s <code>MapContext</code>'s data must be canceled.</p>
646 20397 vcaballero
         *
647 20098 jmvivo
         * <p>It has no effects if now isn't drawing that graphical information.</p>
648 20397 vcaballero
         *
649 20098 jmvivo
         * <p>At last resort, the particular implementation of each layer in this <code>MapControl</code>'s <code>MapContrext</code>
650
     *   will be that one which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
651 1223 fernando
         */
652
        public void cancelDrawing() {
653 3368 fjp
                /* if (drawer != null) {
654 1223 fernando
                        if (!drawer.isAlive()) {
655
                                return;
656
                        }
657
                }
658 3368 fjp
                */
659 4832 fjp
                canceldraw.setCanceled(true);
660 1223 fernando
661 3368 fjp
                /* while (!isCancelled) {
662 1243 fjp
                        if (!drawer.isAlive()) {
663 1327 fjp
                            // Si hemos llegado aqu? con un thread vivo, seguramente
664
                            // no estamos actualizados.
665

666
                                break;
667 1243 fjp
                        }
668 3719 caballero

669 1223 fernando
                }
670
                canceldraw.setCancel(false);
671
                isCancelled = false;
672 3368 fjp
        drawerAlive = false; */
673 1223 fernando
        }
674 3719 caballero
675 20098 jmvivo
        /**
676
         * <p>Creates a {@link BufferedImage BufferedImage} image if there was no buffered image, or if
677
         *  its viewport's image height or width is different from this component's size. Once has created
678
         *  a double-buffer, fills it with the vieport's background color, or with <i>white</i> if it had no background color.</p>
679 20397 vcaballero
         *
680 20098 jmvivo
         * <p>If no double-buffered existed, creates a {@link BufferedImage BufferedImage} with the size of this component,
681
         * and as an image with 8-bit RGBA color components packed into integer pixels. That image has a <code>DirectColorModel</code> with alpha.
682 20397 vcaballero
         * The color data in that image is considered not to be premultiplied with alpha.</p>
683
         *
684 20098 jmvivo
         * <p>Once has created and filled the new inner <code>MapControl</code>'s double-buffer, changes the status to
685
         * <code>OUTDATED</code>.</p>
686 20397 vcaballero
         *
687 20098 jmvivo
         * @return <code>true</code> if has created and filled a new double-buffer for this <code>MapControl</code> instance; otherwise <code>false</code>
688
         */
689 3375 fjp
    private boolean adaptToImageSize()
690
    {
691
        if ((image == null) || (vp.getImageWidth() != this.getWidth()) || (vp.getImageHeight() != this.getHeight()))
692
        {
693
            image = new BufferedImage(this.getWidth(), this.getHeight(),
694
                    BufferedImage.TYPE_INT_ARGB);
695 6212 fjp
            // ESTILO MAC
696
//                image = GraphicsEnvironment.getLocalGraphicsEnvironment()
697
//                                .getDefaultScreenDevice().getDefaultConfiguration()
698
//                                .createCompatibleImage(this.getWidth(), this.getHeight());
699 3375 fjp
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
700 6630 caballero
            getMapContext().getViewPort().refreshExtent();
701 3719 caballero
702
703 3375 fjp
            Graphics gTemp = image.createGraphics();
704
            Color theBackColor = vp.getBackColor();
705
            if (theBackColor == null)
706
                gTemp.setColor(Color.WHITE);
707
            else
708
                gTemp.setColor(theBackColor);
709 3719 caballero
710 3375 fjp
            gTemp.fillRect(0,0,getWidth(), getHeight());
711
            gTemp.dispose();
712
            status = DESACTUALIZADO;
713
            // g.drawImage(image,0,0,null);
714
            return true;
715
        }
716
        return false;
717
    }
718 1223 fernando
719 20098 jmvivo
        /**
720
         * <p>Paints the graphical information of this component using a double buffer.</p>
721 20397 vcaballero
         *
722 20098 jmvivo
         * <p>If the double buffer wasn't created, creates a new one.</p>
723 20397 vcaballero
         *
724 20098 jmvivo
         * <p>Paints the component according the following algorithm:
725
         * <br>
726
         *  &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
727
         *  &nbsp &nbsp If there is no <i>double buffer</i>:<br>
728
         *  &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the <code>MapControl</code> instance, delegates
729
         *   the drawing process to that behavior, calling: <code><i>behavior_instance</i>.paintComponent(g)</code> &nbsp .<br>
730
         *  &nbsp &nbsp &nbsp Else, repaints the current graphical information quickly calling: <code>g.drawImage(image,0,0,null)</code> &nbsp .<br>
731
         *  &nbsp Else, (<i>status</i> is <i>OUTDATED</i>, or <i>ONLY_GRAPHICS</i>): executes a quickly repaint of the previous information calling <code>g.drawImage(image,0,0,null)</code>, and creates
732
         *   a <i>painting request</i> to delegate the heavy drawing process to the {@link Drawer2 Drawer2}'s worker thread, according the <i>SingleWorketThread</i> pattern, starting a timer to update
733
         *   (invoking <code>repaint()</code> that comprises invoke this method) the view every delay of 360 ms. during the the process drawing.</p>
734 20397 vcaballero
         *
735 20098 jmvivo
           * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
736
           * @see Drawer2
737 1223 fernando
         */
738
        protected void paintComponent(Graphics g) {
739 3375 fjp
        adaptToImageSize();
740 3346 fjp
        /* if (status == FAST_PAINT) {
741 3331 fjp
            System.out.println("FAST_PAINT");
742
            g.drawImage(image,0,0,null);
743
            status = ACTUALIZADO;
744
            return;
745 3346 fjp
        } */
746 4568 fjp
        // System.out.println("PINTANDO MAPCONTROL" + this);
747 1223 fernando
                if (status == ACTUALIZADO) {
748 1680 luisw
                        // LWS logger.debug("Dibujando la imagen obtenida");
749 1223 fernando
750
                        /*
751
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
752
                         * en dicho behaviour
753
                         */
754 3372 fjp
            if (image != null)
755
            {
756
                if (currentMapTool != null)
757
                    currentMapTool.paintComponent(g);
758
                else
759
                    g.drawImage(image,0,0,null);
760 3719 caballero
761 3372 fjp
                                // System.out.println("Pinto ACTUALIZADO");
762 1223 fernando
                        }
763 3719 caballero
                } else if ((status == DESACTUALIZADO)
764 2946 fjp
                || (status == ONLY_GRAPHICS)) {
765 1680 luisw
                        // LWS System.out.println("DESACTUALIZADO: Obteniendo la imagen de la cartograf?a");
766 1223 fernando
                        /* if (isOpaque())
767
                        {
768
                            if (image==null)
769
                            {
770
                                g.setColor(vp.getBackColor());
771 3719 caballero
                                g.fillRect(0,0,getWidth(), getHeight());
772
                            }
773 1223 fernando
                            // else g.drawImage(image,0,0,null);
774
                        } */
775 3368 fjp
            // cancelDrawing();
776 1223 fernando
                        //Se crea la imagen con el color de fonde deseado
777 3375 fjp
                        /* if (image == null)
778 1223 fernando
                        {
779
                                image = new BufferedImage(this.getWidth(), this.getHeight(),
780
                                                BufferedImage.TYPE_INT_ARGB);
781
                                vp.setImageSize(new Dimension(getWidth(), getHeight()));
782
                                Graphics gTemp = image.createGraphics();
783 1303 fjp
                            Color theBackColor = vp.getBackColor();
784
                            if (theBackColor == null)
785
                                gTemp.setColor(Color.WHITE);
786
                            else
787
                                gTemp.setColor(theBackColor);
788 3719 caballero

789 1223 fernando
                                gTemp.fillRect(0,0,getWidth(), getHeight());
790
                                gTemp.dispose();
791
                                // g.drawImage(image,0,0,null);
792 3174 ldiaz
                                System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
793 3375 fjp
                        } */
794 3331 fjp
            // else
795
            // {
796 3719 caballero
797
798 3372 fjp
            // if (image != null)
799
            //  {
800 3331 fjp
                g.drawImage(image,0,0,null);
801 3719 caballero
802 3372 fjp
                drawer2.put(new PaintingRequest());
803
                timer.start();
804
            /* }
805
            else
806
                return; */
807 3331 fjp
            // }
808 3719 caballero
809 3368 fjp
            /* if (drawerAlive == false)
810 3331 fjp
            {
811
                drawer = new Drawer(image, canceldraw);
812
                drawer.start();
813 3719 caballero
                        //Se lanza el tread de dibujado
814 3368 fjp
            } */
815 3719 caballero
816 2946 fjp
                        // status = ACTUALIZADO;
817 1223 fernando
                }
818
        }
819
820
        /**
821 20397 vcaballero
         * <p>Gets the {@link BufferedImage BufferedImage} used to accelerate the draw of new ''frames'' with changes,
822 20098 jmvivo
         * or new graphical items in this component.</p>
823 20397 vcaballero
         *
824 20098 jmvivo
         * @return double buffered image used by this component to accelerate the draw of its graphical information, or
825
         * <code>null</code> if isn't already created
826 20397 vcaballero
         *
827
         * @see BufferedImage
828 1223 fernando
         */
829
        public BufferedImage getImage() {
830
                return image;
831
        }
832
833
        /**
834 20098 jmvivo
         * <p>Forces repaint all visible graphical information in this component.</p>
835
         *
836 20397 vcaballero
         * <p>If <code>doClear == true</code>, before repainting, clears the background color, with the
837
         *  inner viewport's background color.</p>
838
         *
839
         * @param doClear <code>true</code> if needs clearing the background color before drawing the map
840
         *
841 20098 jmvivo
         * @see #cancelDrawing()
842
         * @see FLayers#setDirty(boolean)
843 1223 fernando
         */
844
        public void drawMap(boolean doClear) {
845 3979 caballero
                cancelDrawing();
846 12173 nacho
                //System.out.println("drawMap con doClear=" + doClear);
847 3346 fjp
        status = DESACTUALIZADO;
848 5923 fjp
        getMapContext().getLayers().setDirty(true);
849 3331 fjp
                if (doClear)
850
        {
851 20397 vcaballero
            // image = null; // Se usa para el PAN
852 3372 fjp
            if (image != null)
853
            {
854
                Graphics2D g = image.createGraphics();
855 20397 vcaballero
                Color theBackColor = vp.getBackColor();
856
                if (theBackColor == null)
857
                    g.setColor(Color.WHITE);
858
                else
859
                    g.setColor(theBackColor);
860
                g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight());
861 3372 fjp
                g.dispose();
862 3719 caballero
            }
863 3331 fjp
        }
864 1223 fernando
                repaint();
865
        }
866 6306 caballero
867 20397 vcaballero
868 20098 jmvivo
        /**
869
         * <p>Cancels any current drawing process, changing the status to <code>OUTDATED</code>, and forcing
870
         * repaint only the layers dirty.</p>
871 20397 vcaballero
         *
872 20098 jmvivo
         * @see #cancelDrawing()
873
         */
874 5923 fjp
        public void rePaintDirtyLayers()
875
        {
876
                cancelDrawing();
877
        status = DESACTUALIZADO;
878
        repaint();
879
        }
880 6306 caballero
881 20098 jmvivo
        /**
882
         * <p>Cancels any current drawing process, changing the status to <code>ONLY_GRAPHICS</code>, and forcing
883
         * repaint only the graphical layer of the <code>MapContext</code>.</p>
884
         */
885 2901 fjp
    public void drawGraphics() {
886
        status = ONLY_GRAPHICS;
887
        repaint();
888
    }
889 1223 fernando
890
        /**
891
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
892
         */
893
        public void componentHidden(ComponentEvent e) {
894
        }
895
896
        /**
897
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
898
         */
899
        public void componentMoved(ComponentEvent e) {
900
        }
901
902
        /**
903
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
904
         */
905
        public void componentResized(ComponentEvent e) {
906 3375 fjp
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
907 3719 caballero
                                BufferedImage.TYPE_INT_ARGB);
908 1223 fernando
                Graphics gTemp = image.createGraphics();
909
                gTemp.setColor(vp.getBackColor());
910 3372 fjp
                gTemp.fillRect(0,0,getWidth(), getHeight());
911
        System.out.println("MapControl resized");
912
            // image = null;
913 1223 fernando
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
914 3375 fjp
                getMapContext().getViewPort().setScale(); */
915 3372 fjp
                // drawMap(true);
916 1223 fernando
        }
917
918
        /**
919
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
920
         */
921
        public void componentShown(ComponentEvent e) {
922
        }
923
924
        /**
925 20098 jmvivo
         * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
926 1223 fernando
         */
927
        public void addExceptionListener(ExceptionListener o) {
928
                exceptionHandlingSupport.addExceptionListener(o);
929
        }
930
931
        /**
932 20098 jmvivo
         * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
933 1223 fernando
         */
934
        public boolean removeExceptionListener(ExceptionListener o) {
935
                return exceptionHandlingSupport.removeExceptionListener(o);
936
        }
937
938
        /**
939 20098 jmvivo
         * @see ExceptionHandlingSupport#throwException(Throwable)
940 1223 fernando
         */
941 9079 ldiaz
        protected void throwException(Throwable t) {
942 1223 fernando
                exceptionHandlingSupport.throwException(t);
943
        }
944
945 20098 jmvivo
        /**
946
         * <p>Represents each <code>MapControl</code>'s data painting request.</p>
947 20397 vcaballero
         *
948 20098 jmvivo
         * <p>The request will be attended by a <code>Drawer2</code>, which will hold it since the <code>Drawer2</code>'s worker
949 20397 vcaballero
         *  takes it, or arrives a new painting request, which will replace it.</p>
950 20098 jmvivo
         */
951 3368 fjp
    private class PaintingRequest
952
    {
953 20098 jmvivo
            /**
954
             * <p>Creates a new <code>PaintingRequest</p> instance.</p>
955
             */
956 3372 fjp
        public PaintingRequest()
957 3368 fjp
        {
958
        }
959 3719 caballero
960 20098 jmvivo
        /**
961
         * <p><code>MapControl</code> paint process:</p>
962 20397 vcaballero
         *
963 20098 jmvivo
         * <p>
964
         *  <ul>
965
         *   <li><i>1.- </i>Cancels all previous <code>MapControl</code>'s drawing processes.</li>
966
         *   <li><i>2.- </i>If <i>status</i> was OUTDATED:
967
         *    <ul>
968
         *     <li><i>2.1.- </i>Fills the background color with viewport's background color, or <i>white</i> if it was undefined.</li>
969
         *     <li><i>2.2.- </i>Notifies <i>MapContext</i> to be drawn invoking: <code>mapContext.draw(double-buffer, double-buffer's buffer, shared cancel-draw object, mapContext.getScaleView());</code>.</li>
970
         *     <li><i>2.3.- </i>If <code>canceldraw.isCanceled()</code>
971
         *      <ul>
972
         *       <li><i>2.3.1.- </i>Sets <i>status</i> to OUTDATED.</li>
973
         *       <li><i>2.3.2.- </i>Sets <i>dirty</i> all layers stored in <i>MapContext</i>.</li>
974
         *      </ul>
975
         *     </li>
976
         *     <li><i>2.4.- </i>Else, sets <i>status</i> to UPDATED.</li>
977
         *    </ul>
978
         *   </li>
979
         *   <li><i>3.- </i>Else, if <i>status</i> was ONLY_GRAPHICS:
980
         *    <ul>
981
         *     <li><i>3.1.- </i>Sets <i>status</i> to UPDATED.</li>
982
         *     <li><i>3.2.- </i>Notifies <i>MapContext</i> to be drawn invoking: <code>mapContext.drawGraphics(double-buffer, double-buffer's buffer, shared cancel-draw object, mapContext.getScaleView());</code>.</li>
983
         *    </ul>
984
         *   </li>
985
         *   <li><i>4.- </i>Stops the <i>timer</i>.</li>
986
         *   <li><i>5.- </i>Repaints this component invoking: <code>repaint();</code></li>
987
         *  </ul>
988
         * </p>
989 20397 vcaballero
         *
990 20098 jmvivo
         * @see #cancelDrawing()
991
         * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
992
         * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
993 20397 vcaballero
         *
994 20098 jmvivo
         * @see ViewPort
995
         */
996 3368 fjp
        public void paint()
997
        {
998 3719 caballero
            try
999
            {
1000 4832 fjp
                    canceldraw.setCanceled(false);
1001 3372 fjp
                /* if (image == null)
1002
                {
1003
                    image = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
1004
                            BufferedImage.TYPE_INT_ARGB);
1005
                    Graphics gTemp = image.createGraphics();
1006
                    Color theBackColor = vp.getBackColor();
1007
                    if (theBackColor == null)
1008
                        gTemp.setColor(Color.WHITE);
1009
                    else
1010
                        gTemp.setColor(theBackColor);
1011 3719 caballero

1012 3372 fjp
                    gTemp.fillRect(0,0,getWidth(), getHeight());
1013
                    gTemp.dispose();
1014
                    // g.drawImage(image,0,0,null);
1015
                    System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
1016
                } */
1017 3368 fjp
                Graphics2D g = image.createGraphics();
1018 3719 caballero
1019 3368 fjp
                ViewPort viewPort = mapContext.getViewPort();
1020 3719 caballero
1021 3368 fjp
                if (status == DESACTUALIZADO)
1022
                {
1023 5874 fjp
                        Graphics2D gTemp = image.createGraphics();
1024 3368 fjp
                    Color theBackColor = viewPort.getBackColor();
1025
                    if (theBackColor == null)
1026 5874 fjp
                        gTemp.setColor(Color.WHITE);
1027 3368 fjp
                    else
1028 5874 fjp
                        gTemp.setColor(theBackColor);
1029
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1030 6261 fjp
                    // ESTILO MAC
1031 14410 vcaballero
//                  BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
1032
//                          BufferedImage.TYPE_INT_ARGB);
1033
          //
1034
//                  mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
1035
//                  g.drawImage(imgMac, 0, 0, null);
1036
                  // FIN ESTILO MAC
1037
                  // SIN MAC:
1038 3719 caballero
1039 14410 vcaballero
                  mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
1040
                  if (!canceldraw.isCanceled()){
1041
                          status=ACTUALIZADO;
1042
                 }else{
1043
                          status=DESACTUALIZADO;
1044
                          getMapContext().getLayers().setDirty(true);
1045
                  }
1046
1047 3368 fjp
                }
1048
                else if (status == ONLY_GRAPHICS)
1049
                {
1050 3719 caballero
                    status = ACTUALIZADO;
1051 3372 fjp
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
1052 3719 caballero
1053 3368 fjp
                }
1054 3719 caballero
1055
1056 3368 fjp
                // status = FAST_PAINT;
1057 3719 caballero
              //  drawerAlive = false;
1058 3372 fjp
                timer.stop();
1059 3368 fjp
                repaint();
1060 3719 caballero
1061
1062 3368 fjp
            } catch (Throwable e) {
1063
                timer.stop();
1064 3719 caballero
              //  isCancelled = true;
1065 3368 fjp
                e.printStackTrace();
1066
                throwException(e);
1067
            } finally {
1068
            }
1069
        }
1070 20098 jmvivo
    }
1071 3719 caballero
1072 20098 jmvivo
    /**
1073
     * <p>An instance of <code>Drawer2</code> could manage all <code>MapControl</code> painting requests.</p>
1074 20397 vcaballero
     *
1075 20098 jmvivo
     * <p>Based on the <i>WorkerThread</i> software pattern, creates a worker thread that will attend sequentially
1076
     *  the current waiting painting request, after finishing the previous (that could be by a cancel action).</p>
1077 20397 vcaballero
     *
1078 20098 jmvivo
     * <p>All new {@link PaintingRequest PaintingRequest} generated will be stored as <i>waiting requests</i> since the worker
1079
     * attends it.</p>
1080 20397 vcaballero
     *
1081 20098 jmvivo
     * <p>If a worker finished and there was no <i>painting request</i>, the worker would be set to wait until any
1082
     *  <i>painting request</i> would be put.</p>
1083 20397 vcaballero
     *
1084 3368 fjp
     * @author fjp
1085
     */
1086
    public class Drawer2
1087
    {
1088
        // Una mini cola de 2. No acumulamos peticiones de dibujado
1089
        // dibujamos solo lo ?ltimo que nos han pedido.
1090 3719 caballero
1091 20397 vcaballero
1092 20098 jmvivo
            /**
1093
             * <p>Painting request that's been attended by the <code>Drawer2</code>'s worker.</p>
1094 20397 vcaballero
             *
1095 20098 jmvivo
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1096
             * @see #take()
1097
             */
1098
            private PaintingRequest paintingRequest;
1099
1100
            /**
1101
             * <p>Painting request waiting to be attended by the <code>Drawer2</code>'s worker.</p>
1102 20397 vcaballero
             *
1103 20098 jmvivo
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1104
             * @see #take()
1105
             */
1106
            private PaintingRequest waitingRequest;
1107
1108
            /**
1109 20397 vcaballero
             * <p>Determines that the <code>Drawer2</code>'s worker is busy attending a painting request.</p>
1110
              *
1111 20098 jmvivo
             * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1112
             * @see #take()
1113
             */
1114 3368 fjp
        private boolean waiting;
1115 20098 jmvivo
1116
            /**
1117
             * <p>Notifies the <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1118 20397 vcaballero
             *
1119 20098 jmvivo
             * @see #setShutdown(boolean)
1120
             */
1121 3368 fjp
        private boolean shutdown;
1122 3719 caballero
1123 20098 jmvivo
        /**
1124
         * <p>Sets this <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1125 20397 vcaballero
         *
1126 20098 jmvivo
         * @param isShutdown a boolean value
1127
         */
1128 3368 fjp
        public void setShutdown(boolean isShutdown)
1129
        {
1130
            shutdown = isShutdown;
1131
        }
1132 3719 caballero
1133 20098 jmvivo
        /**
1134
         * <p>Creates a new drawer for managing all data painting requests in <code>MapControl</code>.</p>
1135 20397 vcaballero
         *
1136 20098 jmvivo
         * <p>Includes the following steps:
1137
         *  <ul>
1138
         *   <li>By default, there is no <i>current painting request</i>.</li>
1139
         *   <li>By default, there is no <i>waiting painting request</i>.</li>
1140
         *   <li>By default, the worker thread is waiting no <i>painting request</i>.</li>
1141
         *   <li>By default, the worker thread is running.</li>
1142
         *   <li>Creates and starts a worker thread for attending the <i>painting requests</i>.</li>
1143
         *  </ul>
1144
         * </p>
1145
         */
1146 3719 caballero
        public Drawer2()
1147 3368 fjp
        {
1148
            paintingRequest = null;
1149
            waitingRequest = null;
1150
            waiting = false;
1151
            shutdown = false;
1152
            new Thread(new Worker()).start();
1153
        }
1154 3719 caballero
1155 20098 jmvivo
        /**
1156 20397 vcaballero
         * <p>Sets a <code>PaintingRequest</code> to be attended by the worker thread of this object. If
1157 20098 jmvivo
         *  this one was waiting, wakes up.</p>
1158 20397 vcaballero
         *
1159 20098 jmvivo
         * <p>All waiting threads will be notified synchronized.</p>
1160 20397 vcaballero
         *
1161 20098 jmvivo
         * @param newPaintRequest
1162 20397 vcaballero
         *
1163 20098 jmvivo
         * @see #take()
1164
         */
1165 3368 fjp
        public void put(PaintingRequest newPaintRequest)
1166
        {
1167
            waitingRequest = newPaintRequest;
1168
            if (waiting)
1169
            {
1170
                synchronized (this) {
1171
                    notifyAll();
1172
                }
1173
            }
1174
        }
1175 3719 caballero
1176 20098 jmvivo
        /**
1177
         * <p>Used by this object's worker, returns the current waiting drawing request, causing current thread
1178
         *  to wait until another thread invokes {@link #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest) #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)},
1179
         *  if there was no waiting request.</p>
1180 20397 vcaballero
         *
1181 20098 jmvivo
         * <p>All threads will access synchronized to the waiting request.</p>
1182 20397 vcaballero
         *
1183 20098 jmvivo
         * @return <code>PaintingRequest</code> that was waiting to be attended
1184 20397 vcaballero
         *
1185 20098 jmvivo
         * @see #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)
1186
         */
1187 3368 fjp
        public PaintingRequest take()
1188
        {
1189
            if (waitingRequest == null)
1190
            {
1191
                synchronized (this) {
1192
                    waiting = true;
1193
                    try {
1194
                        wait();
1195
                    }
1196
                    catch (InterruptedException ie)
1197
                    {
1198
                        waiting = false;
1199
                    }
1200
                }
1201
            }
1202
            paintingRequest = waitingRequest;
1203
            waitingRequest = null;
1204
            return paintingRequest;
1205
        }
1206 3719 caballero
1207 20098 jmvivo
        /**
1208
         * <p>Thread for attending painting requests.</p>
1209 20397 vcaballero
         *
1210 20098 jmvivo
         * <p>If there was no double buffer, sets the status to <code>OUTDATED</code> and finishes, otherwise
1211
         *  takes the painting request (it's probably that would wait some time), cancel the previous drawing
1212
         *  process, and starts processing the request.</p>
1213 20397 vcaballero
         *
1214 20098 jmvivo
         * @see Thread
1215
         */
1216 3368 fjp
        private class Worker implements Runnable
1217
        {
1218 20098 jmvivo
                /*
1219
                 * (non-Javadoc)
1220
                 * @see java.lang.Runnable#run()
1221
                 */
1222
                public void run()
1223 3368 fjp
            {
1224
                while (!shutdown)
1225
                {
1226
                    PaintingRequest p = take();
1227 12173 nacho
                    //System.out.println("Pintando");
1228 4120 caballero
                    if (image != null){
1229
                            cancelDrawing();
1230 3372 fjp
                        p.paint();
1231 14410 vcaballero
                    } else{
1232 3372 fjp
                        status = DESACTUALIZADO;
1233 14410 vcaballero
                    }
1234 3368 fjp
                }
1235
            }
1236
        }
1237
    }
1238 3719 caballero
1239 1223 fernando
        /**
1240 20098 jmvivo
         * <p><code>Drawer</code> is implemented for drawing the layers of a <code>MapControl</code>'s <i>MapContext</i> instance
1241
         *  as a <i>thread</i> of execution.</p>
1242 20397 vcaballero
         *
1243 20098 jmvivo
         * <p>Draws <code>MapControl</code> according its <i>status</i>:
1244
         *  <ul>
1245
         *   <li><code><i>ONLY_GRAPHICS</i></code>: refreshes only the graphical layer, changing the status to <code><i>UPDATED</i></code>, via
1246
         *    {@linkplain MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double) MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)}.</li>
1247
         *   <li><code><i>OUTDATED</i></code>: refreshes all layers, changing the status to <code><i>UPDATED</i></code>, via
1248
         *    {@linkplain MapContext#draw(BufferedImage, Graphics2D, Cancellable, double) MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)}.</li>
1249
         *  <ul>
1250
         * </p>
1251 20397 vcaballero
         *
1252 20098 jmvivo
         * <p>This drawing process is accelerated by a <code>BufferedImage</code>, and can be canceled.</p>
1253 1223 fernando
         *
1254 20397 vcaballero
         * <p>Once the drawing process has finished, the timer stops and this component gets repainted.</p>
1255
         *
1256 20098 jmvivo
         * @deprecated
1257 1223 fernando
         * @author Vicente Caballero Navarro
1258
         */
1259
        public class Drawer extends Thread {
1260 2531 caballero
                //private Graphics g;
1261 20397 vcaballero
1262 20098 jmvivo
                /**
1263
                 * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
1264 20397 vcaballero
                 *
1265 20098 jmvivo
                 * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
1266
                 * Meanwhile, the previous image can be kept showed.</p>
1267 20397 vcaballero
                 *
1268 20098 jmvivo
                 * @see BufferedImage
1269
                 */
1270 3331 fjp
                private BufferedImage image = null;
1271 20098 jmvivo
1272
                /**
1273
                 * <p>Object to store the flag that notifies the drawing must be canceled or can continue with the process.</p>
1274 20397 vcaballero
                 *
1275 20098 jmvivo
                 * <p>At last resort, the particular implementation of each layer in a <code>MapControl</code>'s <code>MapContrext</code>
1276
         *   will be which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
1277
                 */
1278 1223 fernando
                private CancelDraw cancel;
1279 2531 caballero
                //private boolean threadCancel = false;
1280 1223 fernando
1281
                /**
1282 20098 jmvivo
                 * <p>Creates a new <code>Drawer</code> instance.</p>
1283 1223 fernando
                 */
1284 3331 fjp
                public Drawer(BufferedImage image, CancelDraw cancel)
1285
        {
1286 1223 fernando
                        this.image = image;
1287
                        this.cancel = cancel;
1288 3719 caballero
         //   drawerAlive = true;
1289 1223 fernando
                }
1290
1291
                /**
1292
                 * @see java.lang.Runnable#run()
1293 20098 jmvivo
                 * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
1294
                 * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
1295 1223 fernando
                 */
1296
                public void run() {
1297
                        try {
1298 2857 jaume
                                // synchronized (Drawer.class) {
1299 1282 fjp
                                    Graphics2D g = image.createGraphics();
1300 3719 caballero
1301 1282 fjp
                                    ViewPort viewPort = mapContext.getViewPort();
1302 2946 fjp
                    if (status == DESACTUALIZADO)
1303
                    {
1304
                                        Color theBackColor = viewPort.getBackColor();
1305
                                        if (theBackColor == null)
1306
                                            g.setColor(Color.WHITE);
1307
                                        else
1308
                                            g.setColor(theBackColor);
1309
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1310
                        status = ACTUALIZADO;
1311
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
1312
                    }
1313
                    else if (status == ONLY_GRAPHICS)
1314
                    {
1315 2951 fjp
                        status = ACTUALIZADO;
1316 2946 fjp
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
1317
                    }
1318 3719 caballero
1319 1327 fjp
                                        timer.stop();
1320 3346 fjp
                    // status = FAST_PAINT;
1321 3719 caballero
                  //  drawerAlive = false;
1322 1223 fernando
                                        repaint();
1323 3719 caballero
1324
1325
1326 2857 jaume
                                // }
1327 1223 fernando
                        } catch (Throwable e) {
1328 1266 fernando
                            timer.stop();
1329 3719 caballero
                                //isCancelled = true;
1330 2943 fjp
                e.printStackTrace();
1331 1223 fernando
                                throwException(e);
1332
                        } finally {
1333
                        }
1334
                }
1335
        }
1336
1337
        /**
1338 20098 jmvivo
         * <p>An instance of <code>CancelDraw</code> will be shared by all this <code>MapControl</code>'s <code>MapContext</code> layers,
1339
         *  allowing receive a notification that, when they're been drawn, to be cancelled.</p>
1340 1223 fernando
         *
1341 20098 jmvivo
         * @see Cancellable
1342
         *
1343 1223 fernando
         * @author Fernando Gonz?lez Cort?s
1344
         */
1345
        public class CancelDraw implements Cancellable {
1346 20098 jmvivo
                /**
1347
                 * <p>Determines if the drawing task must be canceled or not.</p>
1348 20397 vcaballero
                 *
1349 20098 jmvivo
                 * @see #isCanceled()
1350
                 * @see #setCanceled(boolean)
1351
                 */
1352 1223 fernando
                private boolean cancel = false;
1353
1354
                /**
1355 20098 jmvivo
                 * Creates a new <code>CancelDraw</code> object.
1356 1223 fernando
                 */
1357
                public CancelDraw() {
1358
                }
1359
1360 20098 jmvivo
                /*
1361
                 * (non-Javadoc)
1362
                 * @see com.iver.utiles.swing.threads.Cancellable#setCanceled(boolean)
1363 1223 fernando
                 */
1364 4832 fjp
                public void setCanceled(boolean b) {
1365 1223 fernando
                        cancel = b;
1366
                }
1367
1368 20098 jmvivo
                /*
1369
                 * (non-Javadoc)
1370 5317 fjp
                 * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
1371 1223 fernando
                 */
1372
                public boolean isCanceled() {
1373
                        return cancel;
1374
                }
1375
        }
1376
1377
        /**
1378 20098 jmvivo
         * <p>Listens all kind of mouse events produced in {@link MapControl MapControl}, and invokes its current
1379
         *  map tool <i>({@link MapControl#getCurrentMapTool() MapControl#getCurrentMapTool()}</i> to simulate a behavior.</p>
1380 20397 vcaballero
         *
1381 20098 jmvivo
         * <p>Mouse wheel moved events produce a <i>zoom in</i> operation if wheel rotation is negative, or a <i>zoom out</i>
1382
         *  if its positive. Both will be centered in the position of the mouse, but, meanwhile <i>zoom in</i> operation
1383
         *  applies a factor of 0.9, <i>zoom out</i> operation applies a factor of 1.2</p>
1384 20397 vcaballero
         *
1385 20098 jmvivo
         * <p>Mouse wheel moved events can be produced as much frequently, that between each one, the drawing process could
1386
         *  hadn't finished. This is the reason that, in this situation, cancels always the previous drawing process before
1387
         *  applying a <i>zoom</i> operation, and ignores all new mouse positions that are produced before 1 second.</p>
1388 1223 fernando
         *
1389
         * @author Fernando Gonz?lez Cort?s
1390
         */
1391
        public class MapToolListener implements MouseListener, MouseWheelListener,
1392
                MouseMotionListener {
1393 5881 fjp
1394 20098 jmvivo
                /**
1395
                 * <p>Used to avoid mouse wheel move events closed.</p>
1396 20397 vcaballero
                 *
1397
                 * <p>If a mouse wheel move event is produced
1398 20098 jmvivo
                 */
1399 5881 fjp
                long t1;
1400 20098 jmvivo
1401
                /**
1402
                 * <p>Position of the mouse, in map coordinates.</p>
1403 20397 vcaballero
                 *
1404 20098 jmvivo
                 * <p>This point coordinates will be used as center of the <i>zoom</i> operation.</p>
1405
                 */
1406 5881 fjp
                Point2D pReal;
1407 20098 jmvivo
1408 1223 fernando
                /**
1409
                 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1410 20098 jmvivo
                 * @see Behavior#mouseClicked(MouseEvent)
1411 1223 fernando
                 */
1412
                public void mouseClicked(MouseEvent e) {
1413
                        try {
1414 12208 jcampos
                                if (currentMapTool != null)
1415
                                    currentMapTool.mouseClicked(e);
1416 1223 fernando
                        } catch (BehaviorException t) {
1417
                                throwException(t);
1418
                        }
1419
                }
1420
1421
                /**
1422
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1423 20098 jmvivo
                 * @see Behavior#mouseEntered(MouseEvent)
1424 1223 fernando
                 */
1425
                public void mouseEntered(MouseEvent e) {
1426
                        try {
1427 12208 jcampos
                                if (currentMapTool != null)
1428
                                        currentMapTool.mouseEntered(e);
1429 1223 fernando
                        } catch (BehaviorException t) {
1430
                                throwException(t);
1431
                        }
1432
                }
1433
1434
                /**
1435
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1436 20098 jmvivo
                 * @see Behavior#mouseExited(MouseEvent)
1437 1223 fernando
                 */
1438
                public void mouseExited(MouseEvent e) {
1439
                        try {
1440 12208 jcampos
                                if (currentMapTool != null)
1441
                                    currentMapTool.mouseExited(e);
1442 1223 fernando
                        } catch (BehaviorException t) {
1443
                                throwException(t);
1444
                        }
1445
                }
1446
1447
                /**
1448
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1449 20098 jmvivo
                 * @see Behavior#mousePressed(MouseEvent)
1450 1223 fernando
                 */
1451
                public void mousePressed(MouseEvent e) {
1452
                        try {
1453 12208 jcampos
                                if (currentMapTool != null)
1454
                                        currentMapTool.mousePressed(e);
1455 1223 fernando
                        } catch (BehaviorException t) {
1456
                                throwException(t);
1457
                        }
1458
                }
1459
1460
                /**
1461
                 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1462 20098 jmvivo
                 * @see Behavior#mouseReleased(MouseEvent)
1463 1223 fernando
                 */
1464
                public void mouseReleased(MouseEvent e) {
1465
                        try {
1466 12208 jcampos
                                if (currentMapTool != null)
1467
                                        currentMapTool.mouseReleased(e);
1468 1223 fernando
                        } catch (BehaviorException t) {
1469
                                throwException(t);
1470
                        }
1471
                }
1472
1473
                /**
1474
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
1475 20098 jmvivo
                 * @see Behavior#mouseWheelMoved(MouseWheelEvent)
1476 1223 fernando
                 */
1477
                public void mouseWheelMoved(MouseWheelEvent e) {
1478
                        try {
1479 12208 jcampos
                                if (currentMapTool == null)
1480
                                        return;
1481 14410 vcaballero
1482 1223 fernando
                                currentMapTool.mouseWheelMoved(e);
1483 6306 caballero
1484 5874 fjp
                                // Si el tool actual no ha consumido el evento
1485
                                // entendemos que quiere el comportamiento por defecto.
1486
                                if (!e.isConsumed())
1487
                                {
1488 5881 fjp
                                        // Para usar el primer punto sobre el que queremos centrar
1489
                                        // el mapa, dejamos pasar un segundo para considerar el siguiente
1490
                                        // punto como v?lido.
1491
                                        if (t1 == 0)
1492
                                        {
1493
                                                t1= System.currentTimeMillis();
1494
                                                pReal = vp.toMapPoint(e.getPoint());
1495
                                        }
1496
                                        else
1497
                                        {
1498
                                                long t2 = System.currentTimeMillis();
1499
                                                if ((t2-t1) > 1000)
1500
                                                        t1=0;
1501
                                        }
1502 5874 fjp
                                        cancelDrawing();
1503
                                        ViewPort vp = getViewPort();
1504
1505 6306 caballero
1506 5874 fjp
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1507
                                                        vp.getAdjustedExtent().getCenterY()); */
1508
                                        int amount = e.getWheelRotation();
1509
                                        double nuevoX;
1510
                                        double nuevoY;
1511
                                        double factor;
1512
1513 6306 caballero
                                        if (amount < 0) // nos acercamos
1514 5874 fjp
                                        {
1515
                                                factor = 0.9;
1516
                                        } else // nos alejamos
1517
                                        {
1518
                                                factor = 1.2;
1519
                                        }
1520
                                        Rectangle2D.Double r = new Rectangle2D.Double();
1521
                                        if (vp.getExtent() != null) {
1522
                                                nuevoX = pReal.getX()
1523
                                                                - ((vp.getExtent().getWidth() * factor) / 2.0);
1524
                                                nuevoY = pReal.getY()
1525
                                                                - ((vp.getExtent().getHeight() * factor) / 2.0);
1526
                                                r.x = nuevoX;
1527
                                                r.y = nuevoY;
1528
                                                r.width = vp.getExtent().getWidth() * factor;
1529
                                                r.height = vp.getExtent().getHeight() * factor;
1530
1531
                                                vp.setExtent(r);
1532
                                        }
1533 6306 caballero
1534
1535 5874 fjp
                                }
1536 1223 fernando
                        } catch (BehaviorException t) {
1537
                                throwException(t);
1538
                        }
1539
                }
1540
1541
                /**
1542
                 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1543 20098 jmvivo
                 * @see Behavior#mouseDragged(MouseEvent)
1544 1223 fernando
                 */
1545
                public void mouseDragged(MouseEvent e) {
1546
                        try {
1547 12208 jcampos
                                if (currentMapTool != null)
1548
                                        currentMapTool.mouseDragged(e);
1549 1223 fernando
                        } catch (BehaviorException t) {
1550
                                throwException(t);
1551
                        }
1552
                }
1553
1554
                /**
1555
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
1556 20098 jmvivo
                 * @see Behavior#mouseMoved(MouseEvent)
1557 1223 fernando
                 */
1558
                public void mouseMoved(MouseEvent e) {
1559
                        try {
1560 12208 jcampos
                                if (currentMapTool != null)
1561
                                        currentMapTool.mouseMoved(e);
1562 1223 fernando
                        } catch (BehaviorException t) {
1563
                                throwException(t);
1564
                        }
1565
                }
1566
        }
1567
1568
        /**
1569 20098 jmvivo
         * <p<code>MapContextListener</code> listens all events produced in a <code>MapControl</code>'s <code>MapContext</code>
1570
         * object during an atomic period of time, and sets it to dirty, <i>executing <code>drawMap(false)</code>, if any of the
1571
         * following conditions is accomplished</i>:
1572
         * <ul>
1573
         *  <li>Any of the <code>LayerEvent</code> in the <code>AtomicEvent</code> parameter notifies a <i>visibility change</i>.</li>
1574
         *  <li>There is at least one <code>ColorEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1575
         *  <li>There is at least one <code>ExtentEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1576
         *  <li>Any of the <code>LayerCollectionEvent</code> in the <code>AtomicEvent</code> parameter notifies that a driver's layer has reloaded it successfully.</li>
1577
         *  <li>There is at least one <code>LegendEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1578
         *  <li>There is at least one <code>SelectionEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1579
         * </ul>
1580
         * </p>
1581 1223 fernando
         *
1582
         * @author Fernando Gonz?lez Cort?s
1583
         */
1584
        public class MapContextListener implements AtomicEventListener {
1585
                /**
1586
                 * @see com.iver.cit.gvsig.fmap.AtomicEventListener#atomicEvent(com.iver.cit.gvsig.fmap.AtomicEvent)
1587
                 */
1588
                public void atomicEvent(AtomicEvent e) {
1589
                        boolean redraw = false;
1590
                        LayerEvent[] layerEvents = e.getLayerEvents();
1591
1592
                        for (int i = 0; i < layerEvents.length; i++) {
1593
                                if (layerEvents[i].getProperty().equals("visible")) {
1594
                                        redraw = true;
1595
                                }
1596
                        }
1597
1598
                        if (e.getColorEvents().length > 0) {
1599
                                redraw = true;
1600
                        }
1601
1602
                        if (e.getExtentEvents().length > 0) {
1603
                                redraw = true;
1604
                        }
1605 6306 caballero
1606 5941 jmvivo
                        if (e.getProjectionEvents().length > 0) {
1607
                                //redraw = true;
1608
                        }
1609 1223 fernando
1610 6306 caballero
1611 14573 vcaballero
                        LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1612
                        if (aux.length > 0) {
1613
                                for (int i=0; i < aux.length; i++)
1614
                                {
1615
                                        if (aux[i].getAffectedLayer().getFLayerStatus().isDriverLoaded())
1616
                                        {
1617
                                                redraw = true;
1618
                                                break;
1619
                                        }
1620
                                }
1621
1622 1223 fernando
                        }
1623
1624
                        if (e.getLegendEvents().length > 0) {
1625
                                redraw = true;
1626
                        }
1627
1628
                        if (e.getSelectionEvents().length > 0) {
1629
                                redraw = true;
1630
                        }
1631
1632
                        if (redraw) {
1633 12173 nacho
                //System.out.println("MapContextListener redraw");
1634 3422 fjp
                                MapControl.this.drawMap(false);
1635 1223 fernando
                        }
1636
                }
1637
        }
1638 20098 jmvivo
1639
        /**
1640
         * <p>Gets the <code>ViewPort</code> of this component's {@link MapContext MapContext} .</p>
1641 20397 vcaballero
         *
1642 20098 jmvivo
         * @see MapContext#getViewPort()
1643
         */
1644 1223 fernando
        public ViewPort getViewPort() {
1645
                return vp;
1646
        }
1647 3719 caballero
1648 2877 caballero
        /**
1649 20098 jmvivo
         * <p>Returns all registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
1650 20397 vcaballero
         *
1651 20098 jmvivo
         * @return registered <code>Behavior</code> to this <code>MapControl</code>
1652 20397 vcaballero
         *
1653 20098 jmvivo
         * @see #addMapTool(String, Behavior)
1654
         * @see #addMapTool(String, Behavior[])
1655
         * @see #getMapToolsKeySet()
1656
         * @see #hasTool(String)
1657 2877 caballero
         */
1658 2876 caballero
        public HashMap getNamesMapTools() {
1659
                return namesMapTools;
1660
        }
1661 4120 caballero
1662 20098 jmvivo
        /*
1663
         * (non-Javadoc)
1664
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
1665
         */
1666 4142 caballero
        public void commandRepaint() {
1667 4127 caballero
                drawMap(false);
1668 4120 caballero
        }
1669 4127 caballero
1670 20098 jmvivo
        /*
1671
         * (non-Javadoc)
1672
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
1673
         */
1674 4127 caballero
        public void commandRefresh() {
1675
                // TODO Auto-generated method stub
1676
        }
1677 4888 caballero
1678 20098 jmvivo
        /**
1679
         * <p>Equivalent operation to <i>undo</i>.</p>
1680 20397 vcaballero
         *
1681 20098 jmvivo
         * <p>Exchanges the previous tool with the current one.</p>
1682 20397 vcaballero
         *
1683 20098 jmvivo
         * @see #addMapTool(String, Behavior)
1684
         * @see #addMapTool(String, Behavior[])
1685
         * @see #setTool(String)
1686
         */
1687 4888 caballero
        public void setPrevTool() {
1688
                setTool(prevTool);
1689
        }
1690 6306 caballero
1691 20098 jmvivo
        /**
1692
         * <p>Executes a <i>zoom in</i> operation centered at the center of the extent.</p>
1693 20397 vcaballero
         *
1694 20098 jmvivo
         * <p>This implementation is designed for being invoked outside a <code>Behavior</code>, for example
1695 20397 vcaballero
         *  by an action of pressing a button; and simulates that the event has been produced by
1696 20098 jmvivo
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1697
         *  <code>MapControl</code> object that's responsible for the <i>zoom in</i> operation.</p>
1698 20397 vcaballero
         *
1699 20098 jmvivo
         * @see #zoomOut()
1700
         */
1701 10837 caballero
        public void zoomIn() {
1702
                getMapContext().clearAllCachingImageDrawnLayers();
1703 6264 fjp
                Behavior mapTool = (Behavior) namesMapTools.get("zoomIn");
1704
                ViewPort vp=getViewPort();
1705
                Rectangle2D r=getViewPort().getAdjustedExtent();
1706
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1707
                MouseEvent e=new MouseEvent((Component)this,MouseEvent.MOUSE_RELEASED,MouseEvent.ACTION_EVENT_MASK,MouseEvent.BUTTON1,(int)pCenter.getX(),(int)pCenter.getY(),1,true,MouseEvent.BUTTON1);
1708
                try {
1709
                        mapTool.mousePressed(e);
1710
                        mapTool.mouseReleased(e);
1711
                } catch (BehaviorException t) {
1712
                        throwException(t);
1713
                }
1714
        }
1715 20397 vcaballero
1716 20098 jmvivo
        /**
1717
         * <p>Executes a <i>zoom out</i> operation centered at the center of the extent.</p>
1718 20397 vcaballero
         *
1719 20098 jmvivo
         * <p>This implementation is thought for being invoked outside a <code>Behavior</code>, for example
1720 20397 vcaballero
         *  by an action of pressing a button, and simulates that the event has been produced by
1721 20098 jmvivo
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1722
         *  <code>MapControl</code> object that's responsible for the <i>zoom out</i> operation.</p>
1723 20397 vcaballero
         *
1724 20098 jmvivo
         * @see #zoomIn()
1725
         */
1726 6264 fjp
        public void zoomOut() {
1727 10837 caballero
                getMapContext().clearAllCachingImageDrawnLayers();
1728 6264 fjp
                Behavior mapTool = (Behavior) namesMapTools.get("zoomOut");
1729
                ViewPort vp=getViewPort();
1730
                Rectangle2D r=getViewPort().getAdjustedExtent();
1731
                Point2D pCenter=vp.fromMapPoint(r.getCenterX(),r.getCenterY());
1732
                MouseEvent e=new MouseEvent((Component)this,MouseEvent.MOUSE_RELEASED,MouseEvent.ACTION_EVENT_MASK,MouseEvent.BUTTON1,(int)pCenter.getX(),(int)pCenter.getY(),1,true,MouseEvent.BUTTON1);
1733
                try {
1734
                        mapTool.mousePressed(e);
1735
                        mapTool.mouseReleased(e);
1736
                } catch (BehaviorException t) {
1737
                        throwException(t);
1738
                }
1739
        }
1740 20098 jmvivo
1741
        /**
1742
         * <p>Returns the listener used to catch all mouse events produced in this <code>MapControl</code> instance
1743 20397 vcaballero
         *  and that redirects the calls to the current map tool.</p>
1744
         *
1745 20098 jmvivo
         * @return the map tool listener used
1746
         */
1747 12208 jcampos
        public MapToolListener getMapToolListener() {
1748
                return mapToolListener;
1749
        }
1750 20098 jmvivo
1751 12208 jcampos
//         mapTool can be null, for instance, in 3D's navigation tools
1752 20098 jmvivo
        /**
1753
         * <p>Sets <code>mapTool</code> as this <code>MapControl</code>'s current map tool.
1754 20397 vcaballero
         *
1755 20098 jmvivo
         * @param mapTool a map tool, or <code>null</code> to disable the interaction with the user
1756 20397 vcaballero
         *
1757 20098 jmvivo
         * @see #getCurrentMapTool()
1758
         * @see #getCurrentTool()
1759
         * @see #setTool(String)
1760
         * @see #setPrevTool()
1761
         * @see #addMapTool(String, Behavior)
1762
         * @see #addMapTool(String, Behavior[])
1763
         */
1764 12208 jcampos
        public void setCurrentMapTool(Behavior mapTool ){
1765
                currentMapTool = mapTool;
1766
        }
1767 14410 vcaballero
1768 20098 jmvivo
        /**
1769
         * <p>Sets the delay to the timer that refreshes this <code>MapControl</code> instance.</p>
1770 20397 vcaballero
         *
1771 20098 jmvivo
         * <p><code>Delay (in ms) = 1000 / getDrawFrameRate()</code></p>
1772 20397 vcaballero
         *
1773 20098 jmvivo
         * @see #getDrawFrameRate()
1774
         * @see #setDrawFrameRate(int)
1775
         */
1776 13733 jaume
        public void applyFrameRate() {
1777
                if (getDrawFrameRate()>0) {
1778
                        timer.setDelay(1000/getDrawFrameRate());
1779
                }
1780
        }
1781
1782 20098 jmvivo
        /**
1783
         * <p>Returns the draw frame rate.</p>
1784 20397 vcaballero
         *
1785 20098 jmvivo
         * <p>Draw frame rate is the number of repaints of this <code>MapControl</code> instance that timer invokes per second.</p>
1786 20397 vcaballero
         *
1787 20098 jmvivo
         * @return number of repaints of this <code>MapControl</code> instance that timer invokes per second
1788 20397 vcaballero
         *
1789 20098 jmvivo
         * @see #applyFrameRate()
1790
         * @see #setDrawFrameRate(int)
1791
         */
1792 13733 jaume
        public static int getDrawFrameRate() {
1793
                return drawFrameRate;
1794
        }
1795
1796 20098 jmvivo
        /**
1797
         * <p>Sets the draw frame rate.</p>
1798 20397 vcaballero
         *
1799 20098 jmvivo
         * <p>Draw frame rate is the number of repaints of this <code>MapControl</code> instance that timer invokes per second.</p>
1800 20397 vcaballero
         *
1801 20098 jmvivo
         * @param drawFrameRate number of repaints of this <code>MapControl</code> instance that timer invokes per second
1802 20397 vcaballero
         *
1803 20098 jmvivo
         * @see #applyFrameRate()
1804
         * @see #getDrawFrameRate()
1805
         */
1806 13733 jaume
        public static void setDrawFrameRate(int drawFrameRate) {
1807
                MapControl.drawFrameRate = drawFrameRate;
1808
        }
1809
1810 20098 jmvivo
        /**
1811
         * <p>Determines if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1812 20397 vcaballero
         *
1813 20098 jmvivo
         * @return <code>true</code> if its enabled; otherwise <code>false</code>
1814
         */
1815 13733 jaume
        public static boolean isDrawAnimationEnabled() {
1816
                return drawAnimationEnabled;
1817
        }
1818
1819 20098 jmvivo
        /**
1820
         * <p>Sets if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1821 20397 vcaballero
         *
1822 20098 jmvivo
         * @param drawAnimationEnabled <code>true</code> to enable the mode; otherwise <code>false</code>
1823
         */
1824 13733 jaume
        public static void setDrawAnimationEnabled(boolean drawAnimationEnabled) {
1825
                MapControl.drawAnimationEnabled = drawAnimationEnabled;
1826
        }
1827 20098 jmvivo
1828
        /**
1829
         * <p>Gets the shared object that determines if a drawing process must be cancelled or can continue.</p>
1830 20397 vcaballero
         *
1831 20098 jmvivo
         * @return the shared object that determines if a drawing process must be cancelled or can continue
1832
         */
1833 18454 vcaballero
        public CancelDraw getCanceldraw() {
1834
                return canceldraw;
1835
        }
1836 20358 vcaballero
1837
        /**
1838
         * <p>Gets the tool used in combination with the current tool of this <code>MapControl</code>.</p>
1839
         *
1840
         * @return the tool used in combination with the <code>currentMapTool</code>; <code>null</code> if there is
1841
         *  no combined tool
1842
         */
1843
        public Behavior getCombinedTool() {
1844
                return combinedTool;
1845
        }
1846
1847
        /**
1848
         * <p>Sets a tool to be used in combination with the current tool of this <code>MapControl</code>.</p>
1849
         *
1850
         * @param combinedTool a tool to be used in combination with the current tool of <code>MapControl</code>
1851
         */
1852
        public void setCombinedTool(Behavior combinedTool) {
1853
                this.combinedTool = combinedTool;
1854
1855
                if (currentMapTool == null)
1856
                        return;
1857
1858
                if ((currentMapTool != null) && (currentMapTool instanceof CompoundBehavior)) {
1859
                        ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, combinedTool.getListener().cancelDrawing());
1860
                }
1861
                else {
1862
                        currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool, combinedTool});
1863
                }
1864
1865
        }
1866
1867
        /**
1868
         * <p>Removes the tool used in combination with the current tool of this <code>MapControl</code>.</p>
1869
         */
1870
        public void removeCombinedTool() {
1871
                if ((currentMapTool != null) && (currentMapTool instanceof CompoundBehavior)) {
1872
                                ((CompoundBehavior)currentMapTool).removeMapBehavior(combinedTool);
1873
                }
1874
1875
                combinedTool = null;
1876
        }
1877 1223 fernando
}