Statistics
| Revision:

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

History | View | Annotate | Download (82.8 KB)

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

    
43
import java.awt.Color;
44
import java.awt.Cursor;
45
import java.awt.Dimension;
46
import java.awt.Graphics;
47
import java.awt.Graphics2D;
48
import java.awt.Image;
49
import java.awt.Point;
50
import java.awt.Toolkit;
51
import java.awt.event.ActionEvent;
52
import java.awt.event.ActionListener;
53
import java.awt.event.ComponentEvent;
54
import java.awt.event.ComponentListener;
55
import java.awt.event.MouseEvent;
56
import java.awt.event.MouseListener;
57
import java.awt.event.MouseMotionListener;
58
import java.awt.event.MouseWheelEvent;
59
import java.awt.event.MouseWheelListener;
60
import java.awt.geom.Point2D;
61
import java.awt.image.BufferedImage;
62
import java.awt.image.MemoryImageSource;
63
import java.util.ArrayList;
64
import java.util.HashMap;
65
import java.util.Set;
66
import java.util.prefs.Preferences;
67

    
68
import javax.swing.JComponent;
69
import javax.swing.Timer;
70

    
71
import org.cresques.cts.IProjection;
72
import org.gvsig.fmap.crs.CRSFactory;
73
import org.gvsig.fmap.dal.DataStoreNotification;
74
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
75
import org.gvsig.fmap.geom.Geometry;
76
import org.gvsig.fmap.geom.GeometryLocator;
77
import org.gvsig.fmap.geom.GeometryManager;
78
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
79
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
80
import org.gvsig.fmap.geom.primitive.Envelope;
81
import org.gvsig.fmap.geom.util.Converter;
82
import org.gvsig.fmap.mapcontext.MapContext;
83
import org.gvsig.fmap.mapcontext.ViewPort;
84
import org.gvsig.fmap.mapcontext.events.AtomicEvent;
85
import org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener;
86
import org.gvsig.fmap.mapcontext.layers.FLayers;
87
import org.gvsig.fmap.mapcontext.layers.LayerCollectionEvent;
88
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
89
import org.gvsig.fmap.mapcontext.layers.SpatialCache;
90
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
91
import org.gvsig.fmap.mapcontext.layers.vectorial.GraphicLayer;
92
import org.gvsig.fmap.mapcontrol.tools.BehaviorException;
93
import org.gvsig.fmap.mapcontrol.tools.CompoundBehavior;
94
import org.gvsig.fmap.mapcontrol.tools.Behavior.Behavior;
95
import org.gvsig.fmap.mapcontrol.tools.Listeners.ToolListener;
96
import org.gvsig.fmap.mapcontrol.tools.grid.Grid;
97
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapper;
98
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapperRaster;
99
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapperVectorial;
100
import org.gvsig.tools.observer.Observable;
101
import org.gvsig.tools.observer.Observer;
102
import org.gvsig.tools.task.Cancellable;
103
import org.gvsig.utils.exceptionHandling.ExceptionHandlingSupport;
104
import org.gvsig.utils.exceptionHandling.ExceptionListener;
105
import org.slf4j.Logger;
106
import org.slf4j.LoggerFactory;
107
import java.util.TreeMap;
108
import java.util.Comparator;
109

    
110

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

    
212
        /**
213
         * <p>One of the possible status of <code>MapControl</code>. Determines that all visible information has been
214
         * drawn and its updated.</p>
215
         */
216
        public static final int ACTUALIZADO = 0;
217

    
218
        /**
219
         * <p>One of the possible status of <code>MapControl</code>. Determines that not all visible information has been
220
         * drawn or isn't updated.</p>
221
         */
222
        public static final int DESACTUALIZADO = 1;
223

    
224
        /**
225
         * <p>One of the possible status of <code>MapControl</code>. Determines that only the graphical layer must
226
         * be drawn / updated.</p>
227
         */
228
        public static final int ONLY_GRAPHICS = 2;
229

    
230

    
231

    
232
    /**
233
     * <p>Determines if the drawer can update this <code>MapControl</code> instance when the timer launches an event.</p>
234
     */
235
    private static boolean drawAnimationEnabled = true;
236

    
237
    // public static final int FAST_PAINT = 3;
238
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
239

    
240
    /**
241
     * <p>Inner model with the layers, event support for drawing them, and the <code>ViewPort</code>
242
     *  with information to adapt to the bounds available in <i>image coordinates</i>.</p>
243
     *
244
     * @see #getMapContext()
245
     * @see #setMapContext(MapContext)
246
     */
247
    private MapContext mapContext = null;
248

    
249
    //private boolean drawerAlive = false;
250

    
251

    
252
        /**
253
         * <p>All registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
254
         *
255
         * <p>Only one of them can be active at a given moment.</p>
256
         *
257
         * @see #addMapTool(String, Behavior)
258
         * @see #addMapTool(String, Behavior[])
259
         * @see #getMapTool(String)
260
         * @see #getMapToolsKeySet()
261
         * @see #getNamesMapTools()
262
         */
263
    protected HashMap namesMapTools = new HashMap();
264

    
265
        /**
266
         * <p>Active {@link Behavior Behavior} that will generate events according a criterion, and then, with a {@link ToolListener ToolListener}
267
         *  associated, will simulate to user that works with this component as a particular tool.</p>
268
         *
269
         * @see #getCurrentMapTool()
270
         * @see #getCurrentTool()
271
         * @see #setTool(String)
272
         */
273
    protected Behavior currentMapTool = null;
274

    
275
        /**
276
         * <p>Determines which's the current drawn status of this component:
277
         * <ul>
278
         *  <li><b>OUTDATED</b>: all visible information has been drawn or isn't updated.</li>
279
         *  <li><b>UTDATED</b>: all visible information has been drawn and its updated.</li>
280
         *  <li><b>ONLY_GRAPHICS</b>: only the graphical layer must be drawn / updated.</li>
281
         * </ul>
282
         * </p>
283
         *
284
         * <p>The <code>MapControl</code> drawing process will consider the value of this parameter to decide which elements will
285
         *  be updated or drawn.</p>
286
         */
287
    private int status = DESACTUALIZADO;
288

    
289
        /**
290
         * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
291
         *
292
         * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
293
         * Meanwhile, the previous image can be kept showed.</p>
294
         *
295
         * @see BufferedImage
296
         *
297
         * @see #getImage()
298
         */
299
    private BufferedImage image = null;
300

    
301
        /**
302
         * <p>Name of the tool used currently to interact with this component.</p>
303
         *
304
         * @see #getCurrentTool()
305
         * @see #setTool(String)
306
         */
307
    protected String currentTool;
308

    
309
        /**
310
         * <p>Object to store the flag that notifies a drawing thread task and <code>MapContext</code>'s layers,
311
         * that must be canceled or can continue with the process.</p>
312
         *
313
         * @see #cancelDrawing()
314
         */
315
    private CancelDraw canceldraw;
316

    
317
    //private boolean isCancelled = true;
318

    
319
        /**
320
         * <p>Fires an action events after a specified delay.</p>
321
         *
322
         * <p><code>MapControl</code> will use the timer to update its visible graphical information during
323
         *  a drawing process, or allowing to cancel that process.</p>
324
         *
325
         * <p>This is very useful to pretend faster interactivity to user when <code>MapControl</code> has
326
         *  lots of layers, and / or layers with heavy graphical elements, that need a long time to finish
327
         *  drawing all its data.</p>
328
         */
329
    private Timer timer;
330

    
331
        /**
332
         * <p>Reference to the {@link ViewPort ViewPort} of the {@link MapContext MapContext} of this component.</p>
333
         *
334
         * <p>The view port once is created an instance of <code>MapControl</code>,
335
         *  is obtained from the <i>EPSG:23030</i> projection, that's the default projection for this component.</p>
336
         *
337
         * <p>After, the view port will change adapting itself according the current projection and the extent.</p>
338
         *
339
         * @see #getViewPort()
340
         *
341
         * @see ViewPort
342
         */
343
    protected ViewPort vp;
344

    
345
    //private Drawer drawer;
346

    
347
        /**
348
         * <p>Manager of all <code>MapControl</code> painting requests.</p>
349
         */
350
    private Drawer2 drawer2;
351

    
352
    // private boolean firstDraw = true;
353

    
354
        /**
355
         * <p>Listener of all kind of mouse events produced in this component.</p>
356
         *
357
         * <p>Delegates each mouse event to the current map tool.</p>
358
         *
359
         * @see #addMapTool(String, Behavior)
360
         * @see #addMapTool(String, Behavior[])
361
         * @see #getMapTool(String)
362
         * @see #getMapToolsKeySet()
363
         * @see #getNamesMapTools()
364
         * @see #setTool(String)
365
         */
366
    protected MapToolListener mapToolListener = new MapToolListener();
367

    
368
        /**
369
         * <p>Listener of all events produced in a this component's <code>MapContext</code>
370
         * object during an atomic period of time.</p>
371
         */
372
    private MapContextListener mapContextListener = new MapContextListener();
373

    
374
        /**
375
         * <p>Group of <code>ExceptionListener</code> that, in whatever moment could be notified a Throwable Java error or exception.</p>
376
         *
377
         * @see #addExceptionListener(ExceptionListener)
378
         * @see #removeExceptionListener(ExceptionListener)
379
         */
380
    private ExceptionHandlingSupport exceptionHandlingSupport = new ExceptionHandlingSupport();
381

    
382
    /**
383
     * <p>Name of the previous tool used.</p>
384
     */
385
        protected String prevTool;
386

    
387
        /**
388
         * <p>Tool that will be used combined with the current tool of this <code>MapControl</code>.</p>
389
         */
390
        private Behavior combinedTool = null;
391

    
392
        /**
393
     * We need this to avoid not wanted refresh. REMEMBER TO SET TO TRUE!!
394
     */
395
    // private boolean paintEnabled = false;
396
        /**
397
         * Edition preferences.
398
         */
399
        private static Preferences prefs = Preferences.userRoot().node( "cadtooladapter" );
400
        /**
401
         * Optional grid that could be applied on the <code>MapControl</code>'s view port.
402
         *
403
         * @see #getGrid()
404
         * @see #setAdjustGrid(boolean)
405
         */
406
        private Grid cadgrid = new Grid();
407
        /**
408
         * Represents the cursor's point selected in <i>screen coordinates</i>.
409
         *
410
         * @see ViewPort#fromMapPoint(Point2D)
411
         */
412
        private Point2D adjustedPoint;
413
        /**
414
         * <p>Determines if the position of the snap of the mouse's cursor on the <code>MapControl</code>
415
         * is within the area around a control point of a geometry.</p>
416
         *
417
         * <p>The area is calculated as a circle centered at the control point and with radius the pixels tolerance
418
         *  defined in the preferences.</p>
419
         */
420
        private boolean bForceCoord = false;
421
        /**
422
         * Kind of geometry drawn to identify the kind of control point selected by the cursor's mouse.
423
         */
424
        private ISnapper usedSnap = null;
425
        /**
426
         * A light yellow color for the tool tip text box associated to the point indicated by the mouse's cursor.
427
         */
428
        private Color theTipColor = new Color(255, 255, 155);
429

    
430
        /**
431
         * Determines if the snap tools are enabled or disabled.
432
         *
433
         * @see #isRefentEnabled()
434
         * @see #setRefentEnabled(boolean)
435
         */
436
        private boolean bRefent = true;
437

    
438
        /**
439
         * Stores the 2D map coordinates of the last point added.
440
         */
441
        private double[] previousPoint = null;
442

    
443
        private static TreeMap selected = new TreeMap(new Comparator(){
444

    
445
                public int compare(Object o1, Object o2) {
446
                        if (o1.getClass().equals(o2.getClass()))
447
                                return 0;
448
                        if (((ISnapper)o1).getPriority()>((ISnapper)o2).getPriority())
449
                                return 1;
450
                        else
451
                                return -1;
452
                }
453

    
454
        });
455

    
456
        public static int tolerance=4;
457
        /**
458
         * Represents the cursor's point selected in <i>map coordinates</i>.
459
         *
460
         * @see MapControl#toMapPoint
461
         */
462
        private Point2D mapAdjustedPoint;
463

    
464
        /**
465
         * <p>Creates a new <code>MapControl</code> instance with the following characteristics:
466
         * <ul>
467
         *  <li><i>Name</i>: MapControl .</li>
468
         *  <li>Disables the double buffer of <code>JComponent</code> .</li>
469
         *  <li>Sets opaque <i>(see {@link JComponent#setOpaque(boolean)} )</i>. </li>
470
         *  <li>Sets its status to <code>OUTDATED</code> .</li>
471
         *  <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>
472
         *  <li>Creates a new {@link MapContext MapContext} with a new {@link ViewPort ViewPort} in the projection <i>"EPSG:23030"</i> .</li>
473
         *  <li>Creates a new {@link CommandListener CommandListener} for edition operations.</li>
474
         *  <li>Creates a new {@link MapToolListener MapToolListener}, and associates it as a listener of whatever kind of mouse events produced in this component.</li>
475
         *  <li>Creates a new {@link Drawer2 Drawer2} for managing the painting requests.</li>
476
         *  <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
477
         *   <code>drawAnimationEnabled</code>.</li>
478
         * </ul>
479
         * </p>
480
         */
481
        public MapControl() {
482
                this.setName("MapControl");
483
                setDoubleBuffered(false);
484
                setOpaque(true);
485
                status = DESACTUALIZADO;
486

    
487
                //Clase usada para cancelar el dibujado
488
                canceldraw = new CancelDraw();
489

    
490
                //Modelo de datos y ventana del mismo
491
                // TODO: Cuando creamos un mapControl, deber?amos asignar
492
                // la projecci?n por defecto con la que vayamos a trabajar.
493
                // 23030 es el c?digo EPSG del UTM30 elipsoide ED50
494
                vp = new ViewPort(CRSFactory.getCRS("EPSG:23030"));
495
                setMapContext(new MapContext(vp));
496

    
497
                //eventos
498
                this.addComponentListener(this);
499
                this.addMouseListener(mapToolListener);
500
                this.addMouseMotionListener(mapToolListener);
501
                this.addMouseWheelListener(mapToolListener);
502

    
503
        this.drawer2 = new Drawer2();
504
                //Timer para mostrar el redibujado mientras se dibuja
505
                timer = new Timer(1000/MapContext.getDrawFrameRate(),
506
                                new ActionListener() {
507
                                        public void actionPerformed(ActionEvent e) {
508

    
509
                                                if (drawAnimationEnabled) {
510
                                                        MapControl.this.repaint();
511
                                                }
512
                                        }
513
                                });
514
                initializeGrid();
515
        }
516

    
517
        /**
518
         * <p>Sets a <code>MapContext</code> to this component.</p>
519
         *
520
         * <p>The <code>MapContext</code> has the <i>model</i>, and most of the <i>view</i>,
521
         * and <i>control</i> logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the
522
         * information to the projection, and to display it in the available area.</p>
523
         *
524
         * <p>If <code>model</code> hadn't a <code>ViewPort</code>, assigns the current one to it, otherwise, use its <code>ViewPort</code>.</p>
525
         *
526
         * <p>After assigning the <code>MapContext</code> and <code>ViewPort</code>, sets the same {@link MapContextListener MapContextListener}
527
         *  that was using, and changes the <i>status</i> to <code>OUTDATED</code>.</p>
528
         *
529
         * @param model this component's <code>MapContext</code>, that includes the <code>ViewPort</code>.
530
         *
531
         * @see MapContext
532
         *
533
         * @see #getMapContext()
534
         */
535
        public void setMapContext(MapContext model) {
536
                if (mapContext != null) {
537
                        mapContext.removeAtomicEventListener(mapContextListener);
538
                }
539

    
540
                mapContext = model;
541

    
542
                if (mapContext.getViewPort() == null) {
543
                        mapContext.setViewPort(vp);
544
                } else {
545
                        vp = mapContext.getViewPort();
546
                        cadgrid.setViewPort(vp);
547
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
548
                        //System.err.println("Viewport en setMapContext:" + vp);
549
                }
550

    
551
                mapContext.addAtomicEventListener(mapContextListener);
552

    
553
                status = DESACTUALIZADO;
554
        }
555

    
556
        /**
557
         * <p>Gets this component's {@link MapContext MapContext} projection.</p>
558
         *
559
         * @return this component's {@link MapContext MapContext} projection
560
         *
561
         * @see MapContext#getProjection()
562
         * @see MapControl#setProjection(IProjection)
563
         */
564
        public IProjection getProjection() {
565
                return getMapContext().getProjection();
566
        }
567

    
568
        /**
569
         * <p>Sets the projection to this component's {@link MapContext MapContext}.</p>
570
         *
571
         * @param proj the kind of projection to this component's {@link MapContext MapContext}
572
         *
573
         * @see MapContext#setProjection(IProjection)
574
         * @see MapControl#getProjection()
575
         */
576
        public void setProjection(IProjection proj) {
577
                getMapContext().setProjection(proj);
578
        }
579

    
580
        /**
581
         * <p>Gets this component's <code>MapContext</code>, with the <i>model</i>, and most of the <i>view</i>,
582
         * and <i>control</i> logic of the layers of this component, including a {@link ViewPort ViewPort} to adapt the
583
         * information to the projection, and display it in the available area.</p>
584
         *
585
         * @return this component's <code>MapContext</code>, that includes the <code>ViewPort</code> used to project the
586
         * graphical information, and display it in the available area
587
         *
588
         * @see MapContext
589
         *
590
         * @see MapControl#setMapContext(MapContext)
591
         */
592
        public MapContext getMapContext() {
593
                return mapContext;
594
        }
595

    
596
        /**
597
         * <p>Registers a new behavior to this component.</p>
598
         *
599
         * <p>According the nature of the {@link Behavior Behavior}, different events will be generated. Those
600
         *  events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this
601
         *  <code>MapControl</code> object as a <i>tool</i>.</p>
602
         *
603
         * @param name name to identify the behavior to add
604
         * @param tool the behavior to add
605
         *
606
         * @see #addMapTool(String, Behavior[])
607
         * @see #getNamesMapTools()
608
         * @see #getMapToolsKeySet()
609
         * @see #hasTool(String)
610
         */
611
        public void addMapTool(String name, Behavior tool) {
612
                namesMapTools.put(name, tool);
613
                tool.setMapControl(this);
614
        }
615

    
616
        /**
617
         * <p>Registers a new behavior to this component as a {@link CompoundBehavior CompoundBehavior} made up of <code>tools</code>.</p>
618
         *
619
         * <p>According the nature of the behaviors registered, different events will be generated. Those
620
         *  events can be caught by a particular {@link ToolListener ToolListener}, allowing user to interact with this
621
         *  <code>MapControl</code> object as a <i>tool</i>.</p>
622
         *
623
         * @param name name to identify the compound behavior to add
624
         * @param tools the compound behavior to add
625
         *
626
         * @see #addMapTool(String, Behavior)
627
         * @see #getNamesMapTools()
628
         * @see #getMapToolsKeySet()
629
         * @see #hasTool(String)
630
         */
631
        public void addMapTool(String name, Behavior[] tools){
632
                CompoundBehavior tool = new CompoundBehavior(tools);
633
                addMapTool(name, tool);
634
        }
635

    
636
        /**
637
         * <p>Gets the <code>Behavior</code> registered in this component, identified
638
         *  by <code>name</code>.</p>
639
         *
640
         * @param name name of a registered behavior
641
         *
642
         * @return tool the registered behavior in this component as <code>name</code>, or <code>null</code> if
643
         *  no one has that identifier
644
         *
645
         * @see #addMapTool(String, Behavior)
646
         * @see #addMapTool(String, Behavior[])
647
         * @see #hasTool(String)
648
         */
649
        public Behavior getMapTool(String name) {
650
                return (Behavior)namesMapTools.get(name);
651
        }
652

    
653
        /**
654
         * <p>Returns a set view of the keys that identified the tools
655
         *  registered.</p>
656
         *
657
         * @return a set view of the keys that identified the tools registered
658
         *
659
         * @see HashMap#keySet()
660
         *
661
         * @see #getNamesMapTools()
662
          * @see #addMapTool(String, Behavior)
663
          * @see #addMapTool(String, Behavior[])
664
         */
665
        public Set getMapToolsKeySet() {
666
                return namesMapTools.keySet();
667
        }
668

    
669
        /**
670
         * <p>Returns <code>true</code> if this component contains a tool identified by <code>toolName</code>.</p>
671
         *
672
         * @param toolName identifier of the tool
673
         *
674
         * @return <code>true</code> if this component contains a tool identified by <code>toolName</code>; otherwise <code>false</code>
675
         *
676
         * @see #addMapTool(String, Behavior)
677
         * @see #addMapTool(String, Behavior[])
678
         */
679
        public boolean hasTool(String toolName) {
680
                return namesMapTools.containsKey(toolName);
681
        }
682

    
683
        /**
684
         * <p>Sets as current active <code>Behavior</code> associated to this component, that one which
685
         *  is registered and identified by <code>toolName</code>.</p>
686
         *
687
         * <p>Changing the current active behavior for this <code>MapControl</code>, implies also updating the
688
         *  previous <i>behavior</i> tool, and the current cursor.</p>
689
         *
690
         * @param toolName name of a registered behavior
691
         *
692
         * @see #getCurrentMapTool()
693
         * @see #getCurrentTool()
694
         */
695
        public void setTool(String toolName) {
696
                prevTool=getCurrentTool();
697
                Behavior mapTool = (Behavior) namesMapTools.get(toolName);
698
                currentMapTool = mapTool;
699
                currentTool = toolName;
700

    
701
                if (combinedTool != null) {
702
                        if (mapTool instanceof CompoundBehavior) {
703
                                ((CompoundBehavior)mapTool).addMapBehavior(combinedTool, true);
704
                        }
705
                        else {
706
                                currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool});
707
                                ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true);
708
                        }
709
                }
710

    
711
//                this.setCursor(mapTool.getCursor());
712
        }
713

    
714
        /**
715
         * <p>Gets as current active <code>Behavior</code> associated to this component, that one which
716
         *  is registered and identified by <code>toolName</code>.</p>
717
         *
718
         * <p>Changing the current active behavior for this <code>MapControl</code>, implies also updating the
719
         *  previous <i>behavior</i> tool, and the current cursor.</p>
720
         *
721
         * @param toolName name of a registered behavior
722
         *
723
         * @see #getCurrentTool()
724
         * @see #setTool(String)
725
         */
726
        public Behavior getCurrentMapTool(){
727
                return currentMapTool;
728
        }
729

    
730
        /**
731
         * <p>Returns the name of the current selected tool on this MapControl</p>
732
         *
733
         * @return the name of the current's behavior tool associated to this component
734
         *
735
         * @see #getCurrentMapTool()
736
         * @see #setTool(String)
737
         */
738
        public String getCurrentTool() {
739
                return currentTool;
740
        }
741

    
742
        /**
743
         * <p>Determines that current drawing process of <code>MapControl</code>'s <code>MapContext</code>'s data must be canceled.</p>
744
         *
745
         * <p>It has no effects if now isn't drawing that graphical information.</p>
746
         *
747
         * <p>At last resort, the particular implementation of each layer in this <code>MapControl</code>'s <code>MapContrext</code>
748
     *   will be that one which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
749
         */
750
        public void cancelDrawing() {
751
                /* if (drawer != null) {
752
                        if (!drawer.isAlive()) {
753
                                return;
754
                        }
755
                }
756
                */
757
                canceldraw.setCanceled(true);
758

    
759
                /* while (!isCancelled) {
760
                        if (!drawer.isAlive()) {
761
                            // Si hemos llegado aqu? con un thread vivo, seguramente
762
                            // no estamos actualizados.
763

764
                                break;
765
                        }
766

767
                }
768
                canceldraw.setCancel(false);
769
                isCancelled = false;
770
        drawerAlive = false; */
771
        }
772

    
773
        /**
774
         * <p>Creates a {@link BufferedImage BufferedImage} image if there was no buffered image, or if
775
         *  its viewport's image height or width is different from this component's size. Once has created
776
         *  a double-buffer, fills it with the vieport's background color, or with <i>white</i> if it had no background color.</p>
777
         *
778
         * <p>If no double-buffered existed, creates a {@link BufferedImage BufferedImage} with the size of this component,
779
         * and as an image with 8-bit RGBA color components packed into integer pixels. That image has a <code>DirectColorModel</code> with alpha.
780
         * The color data in that image is considered not to be premultiplied with alpha.</p>
781
         *
782
         * <p>Once has created and filled the new inner <code>MapControl</code>'s double-buffer, changes the status to
783
         * <code>OUTDATED</code>.</p>
784
         *
785
         * @return <code>true</code> if has created and filled a new double-buffer for this <code>MapControl</code> instance; otherwise <code>false</code>
786
         */
787
    private boolean adaptToImageSize()
788
    {
789
        if ((image == null) || (vp.getImageWidth() != this.getWidth()) || (vp.getImageHeight() != this.getHeight()))
790
        {
791
            image = new BufferedImage(this.getWidth(), this.getHeight(),
792
                    BufferedImage.TYPE_INT_ARGB);
793
            // ESTILO MAC
794
//                image = GraphicsEnvironment.getLocalGraphicsEnvironment()
795
//                                .getDefaultScreenDevice().getDefaultConfiguration()
796
//                                .createCompatibleImage(this.getWidth(), this.getHeight());
797
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
798
            getMapContext().getViewPort().refreshExtent();
799

    
800

    
801
            Graphics gTemp = image.createGraphics();
802
            Color theBackColor = vp.getBackColor();
803
            if (theBackColor == null) {
804
                                gTemp.setColor(Color.WHITE);
805
                        } else {
806
                                gTemp.setColor(theBackColor);
807
                        }
808

    
809
            gTemp.fillRect(0,0,getWidth(), getHeight());
810
            gTemp.dispose();
811
            status = DESACTUALIZADO;
812
            // g.drawImage(image,0,0,null);
813
            return true;
814
        }
815
        return false;
816
    }
817

    
818
        /**
819
         * <p>Paints the graphical information of this component using a double buffer.</p>
820
         *
821
         * <p>If the double buffer wasn't created, creates a new one.</p>
822
         *
823
         * <p>Paints the component according the following algorithm:
824
         * <br>
825
         *  &nbsp If <i>status</i> is <i>UPDATED</i>:<br>
826
         *  &nbsp &nbsp If there is no <i>double buffer</i>:<br>
827
         *  &nbsp &nbsp &nbsp If there is a <i>behavior</i> for managing the <code>MapControl</code> instance, delegates
828
         *   the drawing process to that behavior, calling: <code><i>behavior_instance</i>.paintComponent(g)</code> &nbsp .<br>
829
         *  &nbsp &nbsp &nbsp Else, repaints the current graphical information quickly calling: <code>g.drawImage(image,0,0,null)</code> &nbsp .<br>
830
         *  &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
831
         *   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
832
         *   (invoking <code>repaint()</code> that comprises invoke this method) the view every delay of 360 ms. during the the process drawing.</p>
833
         *
834
           * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
835
           * @see Drawer2
836
         */
837
        protected void paintComponent(Graphics g) {
838
        adaptToImageSize();
839
        /* if (status == FAST_PAINT) {
840
            System.out.println("FAST_PAINT");
841
            g.drawImage(image,0,0,null);
842
            status = ACTUALIZADO;
843
            return;
844
        } */
845
        // System.out.println("PINTANDO MAPCONTROL" + this);
846
                if (status == ACTUALIZADO) {
847
                        // LWS logger.debug("Dibujando la imagen obtenida");
848

    
849
                        /*
850
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
851
                         * en dicho behaviour
852
                         */
853
            if (image != null)
854
            {
855
                if (currentMapTool != null) {
856
                                        currentMapTool.paintComponent(g);
857
                                } else {
858
                                        g.drawImage(image,0,0,null);
859
                                }
860

    
861
                                // System.out.println("Pinto ACTUALIZADO");
862
                        }
863
                } else if ((status == DESACTUALIZADO)
864
                || (status == ONLY_GRAPHICS)) {
865
                        // LWS System.out.println("DESACTUALIZADO: Obteniendo la imagen de la cartograf?a");
866
                        /* if (isOpaque())
867
                        {
868
                            if (image==null)
869
                            {
870
                                g.setColor(vp.getBackColor());
871
                                g.fillRect(0,0,getWidth(), getHeight());
872
                            }
873
                            // else g.drawImage(image,0,0,null);
874
                        } */
875
            // cancelDrawing();
876
                        //Se crea la imagen con el color de fonde deseado
877
                        /* if (image == null)
878
                        {
879
                                image = new BufferedImage(this.getWidth(), this.getHeight(),
880
                                                BufferedImage.TYPE_INT_ARGB);
881
                                vp.setImageSize(new Dimension(getWidth(), getHeight()));
882
                                Graphics gTemp = image.createGraphics();
883
                            Color theBackColor = vp.getBackColor();
884
                            if (theBackColor == null)
885
                                gTemp.setColor(Color.WHITE);
886
                            else
887
                                gTemp.setColor(theBackColor);
888

889
                                gTemp.fillRect(0,0,getWidth(), getHeight());
890
                                gTemp.dispose();
891
                                // g.drawImage(image,0,0,null);
892
                                System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
893
                        } */
894
            // else
895
            // {
896

    
897

    
898
            // if (image != null)
899
            //  {
900
                g.drawImage(image,0,0,null);
901

    
902
                drawer2.put(new PaintingRequest());
903
                timer.start();
904
            /* }
905
            else
906
                return; */
907
            // }
908

    
909
            /* if (drawerAlive == false)
910
            {
911
                drawer = new Drawer(image, canceldraw);
912
                drawer.start();
913
                        //Se lanza el tread de dibujado
914
            } */
915

    
916
                        // status = ACTUALIZADO;
917
                }
918
                cadgrid.drawGrid(g);
919
                drawCursor(g);
920
        }
921

    
922
        /**
923
         * <p>Gets the {@link BufferedImage BufferedImage} used to accelerate the draw of new ''frames'' with changes,
924
         * or new graphical items in this component.</p>
925
         *
926
         * @return double buffered image used by this component to accelerate the draw of its graphical information, or
927
         * <code>null</code> if isn't already created
928
         *
929
         * @see BufferedImage
930
         */
931
        public BufferedImage getImage() {
932
                return image;
933
        }
934

    
935
        /**
936
         * <p>Forces repaint all visible graphical information in this component.</p>
937
         *
938
         * <p>If <code>doClear == true</code>, before repainting, clears the background color, with the
939
         *  inner viewport's background color.</p>
940
         *
941
         * @param doClear <code>true</code> if needs clearing the background color before drawing the map
942
         *
943
         * @see #cancelDrawing()
944
         * @see FLayers#setDirty(boolean)
945
         */
946
        public void drawMap(boolean doClear) {
947
                cancelDrawing();
948
                //System.out.println("drawMap con doClear=" + doClear);
949
        status = DESACTUALIZADO;
950
                if (doClear)
951
        {
952
            // image = null; // Se usa para el PAN
953
            if (image != null)
954
            {
955
                Graphics2D g = image.createGraphics();
956
                Color theBackColor = vp.getBackColor();
957
                if (theBackColor == null) {
958
                                        g.setColor(Color.WHITE);
959
                                } else {
960
                                        g.setColor(theBackColor);
961
                                }
962
                g.fillRect(0, 0, vp.getImageWidth(), vp.getImageHeight());
963
                g.dispose();
964
            }
965
        }
966
                repaint();
967
        }
968

    
969

    
970
        /**
971
         * <p>Cancels any current drawing process, changing the status to <code>OUTDATED</code>, and forcing
972
         * repaint only the layers dirty.</p>
973
         *
974
         * @see #cancelDrawing()
975
         */
976
        public void rePaintDirtyLayers()
977
        {
978
                cancelDrawing();
979
        status = DESACTUALIZADO;
980
        repaint();
981
        }
982

    
983
        /**
984
         * <p>Cancels any current drawing process, changing the status to <code>ONLY_GRAPHICS</code>, and forcing
985
         * repaint only the graphical layer of the <code>MapContext</code>.</p>
986
         */
987
    public void drawGraphics() {
988
        status = ONLY_GRAPHICS;
989
        repaint();
990
    }
991

    
992
        /**
993
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
994
         */
995
        public void componentHidden(ComponentEvent e) {
996
        }
997

    
998
        /**
999
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
1000
         */
1001
        public void componentMoved(ComponentEvent e) {
1002
        }
1003

    
1004
        /**
1005
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
1006
         */
1007
        public void componentResized(ComponentEvent e) {
1008
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
1009
                                BufferedImage.TYPE_INT_ARGB);
1010
                Graphics gTemp = image.createGraphics();
1011
                gTemp.setColor(vp.getBackColor());
1012
                gTemp.fillRect(0,0,getWidth(), getHeight());
1013
        System.out.println("MapControl resized");
1014
            // image = null;
1015
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
1016
                getMapContext().getViewPort().setScale(); */
1017
                // drawMap(true);
1018
        }
1019

    
1020
        /**
1021
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1022
         */
1023
        public void componentShown(ComponentEvent e) {
1024
        }
1025

    
1026
        /**
1027
         * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
1028
         */
1029
        public void addExceptionListener(ExceptionListener o) {
1030
                exceptionHandlingSupport.addExceptionListener(o);
1031
        }
1032

    
1033
        /**
1034
         * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
1035
         */
1036
        public boolean removeExceptionListener(ExceptionListener o) {
1037
                return exceptionHandlingSupport.removeExceptionListener(o);
1038
        }
1039

    
1040
        /**
1041
         * @see ExceptionHandlingSupport#throwException(Throwable)
1042
         */
1043
        protected void throwException(Throwable t) {
1044
                exceptionHandlingSupport.throwException(t);
1045
        }
1046

    
1047
        /**
1048
         * <p>Represents each <code>MapControl</code>'s data painting request.</p>
1049
         *
1050
         * <p>The request will be attended by a <code>Drawer2</code>, which will hold it since the <code>Drawer2</code>'s worker
1051
         *  takes it, or arrives a new painting request, which will replace it.</p>
1052
         */
1053
    private class PaintingRequest
1054
    {
1055
            /**
1056
             * <p>Creates a new <code>PaintingRequest</p> instance.</p>
1057
             */
1058
        public PaintingRequest()
1059
        {
1060
        }
1061

    
1062
        /**
1063
         * <p><code>MapControl</code> paint process:</p>
1064
         *
1065
         * <p>
1066
         *  <ul>
1067
         *   <li><i>1.- </i>Cancels all previous <code>MapControl</code>'s drawing processes.</li>
1068
         *   <li><i>2.- </i>If <i>status</i> was OUTDATED:
1069
         *    <ul>
1070
         *     <li><i>2.1.- </i>Fills the background color with viewport's background color, or <i>white</i> if it was undefined.</li>
1071
         *     <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>
1072
         *     <li><i>2.3.- </i>If <code>canceldraw.isCanceled()</code>
1073
         *      <ul>
1074
         *       <li><i>2.3.1.- </i>Sets <i>status</i> to OUTDATED.</li>
1075
         *       <li><i>2.3.2.- </i>Sets <i>dirty</i> all layers stored in <i>MapContext</i>.</li>
1076
         *      </ul>
1077
         *     </li>
1078
         *     <li><i>2.4.- </i>Else, sets <i>status</i> to UPDATED.</li>
1079
         *    </ul>
1080
         *   </li>
1081
         *   <li><i>3.- </i>Else, if <i>status</i> was ONLY_GRAPHICS:
1082
         *    <ul>
1083
         *     <li><i>3.1.- </i>Sets <i>status</i> to UPDATED.</li>
1084
         *     <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>
1085
         *    </ul>
1086
         *   </li>
1087
         *   <li><i>4.- </i>Stops the <i>timer</i>.</li>
1088
         *   <li><i>5.- </i>Repaints this component invoking: <code>repaint();</code></li>
1089
         *  </ul>
1090
         * </p>
1091
         *
1092
         * @see #cancelDrawing()
1093
         * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
1094
         * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
1095
         *
1096
         * @see ViewPort
1097
         */
1098
        public void paint()
1099
        {
1100
            try
1101
            {
1102
                    canceldraw.setCanceled(false);
1103
                /* if (image == null)
1104
                {
1105
                    image = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
1106
                            BufferedImage.TYPE_INT_ARGB);
1107
                    Graphics gTemp = image.createGraphics();
1108
                    Color theBackColor = vp.getBackColor();
1109
                    if (theBackColor == null)
1110
                        gTemp.setColor(Color.WHITE);
1111
                    else
1112
                        gTemp.setColor(theBackColor);
1113

1114
                    gTemp.fillRect(0,0,getWidth(), getHeight());
1115
                    gTemp.dispose();
1116
                    // g.drawImage(image,0,0,null);
1117
                    System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
1118
                } */
1119
                Graphics2D g = image.createGraphics();
1120

    
1121
                ViewPort viewPort = mapContext.getViewPort();
1122

    
1123
                if (status == DESACTUALIZADO)
1124
                {
1125
                        Graphics2D gTemp = image.createGraphics();
1126
                    Color theBackColor = viewPort.getBackColor();
1127
                    if (theBackColor == null) {
1128
                                                gTemp.setColor(Color.WHITE);
1129
                                        } else {
1130
                                                gTemp.setColor(theBackColor);
1131
                                        }
1132
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1133
                    // ESTILO MAC
1134
//                  BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
1135
//                          BufferedImage.TYPE_INT_ARGB);
1136
          //
1137
//                  mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
1138
//                  g.drawImage(imgMac, 0, 0, null);
1139
                  // FIN ESTILO MAC
1140
                  // SIN MAC:
1141

    
1142
                  mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
1143
                  if (!canceldraw.isCanceled()){
1144
                          status=ACTUALIZADO;
1145
                 }else{
1146
                          status=DESACTUALIZADO;
1147
//                          getMapContext().getLayers().setDirty(true);
1148
                  }
1149

    
1150
                }
1151
                else if (status == ONLY_GRAPHICS)
1152
                {
1153
                    status = ACTUALIZADO;
1154
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
1155

    
1156
                }
1157

    
1158

    
1159

    
1160
                // status = FAST_PAINT;
1161
              //  drawerAlive = false;
1162
                timer.stop();
1163
                repaint();
1164

    
1165

    
1166
            } catch (Throwable e) {
1167
                timer.stop();
1168
              //  isCancelled = true;
1169
                e.printStackTrace();
1170
                throwException(e);
1171
            } finally {
1172
            }
1173
        }
1174
    }
1175

    
1176
    /**
1177
     * <p>An instance of <code>Drawer2</code> could manage all <code>MapControl</code> painting requests.</p>
1178
     *
1179
     * <p>Based on the <i>WorkerThread</i> software pattern, creates a worker thread that will attend sequentially
1180
     *  the current waiting painting request, after finishing the previous (that could be by a cancel action).</p>
1181
     *
1182
     * <p>All new {@link PaintingRequest PaintingRequest} generated will be stored as <i>waiting requests</i> since the worker
1183
     * attends it.</p>
1184
     *
1185
     * <p>If a worker finished and there was no <i>painting request</i>, the worker would be set to wait until any
1186
     *  <i>painting request</i> would be put.</p>
1187
     *
1188
     * @author fjp
1189
     */
1190
    public class Drawer2
1191
    {
1192
        // Una mini cola de 2. No acumulamos peticiones de dibujado
1193
        // dibujamos solo lo ?ltimo que nos han pedido.
1194

    
1195

    
1196
            /**
1197
             * <p>Painting request that's been attended by the <code>Drawer2</code>'s worker.</p>
1198
             *
1199
             * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1200
             * @see #take()
1201
             */
1202
            private PaintingRequest paintingRequest;
1203

    
1204
            /**
1205
             * <p>Painting request waiting to be attended by the <code>Drawer2</code>'s worker.</p>
1206
             *
1207
             * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1208
             * @see #take()
1209
             */
1210
            private PaintingRequest waitingRequest;
1211

    
1212
            /**
1213
             * <p>Determines that the <code>Drawer2</code>'s worker is busy attending a painting request.</p>
1214
              *
1215
             * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1216
             * @see #take()
1217
             */
1218
        private boolean waiting;
1219

    
1220
            /**
1221
             * <p>Notifies the <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1222
             *
1223
             * @see #setShutdown(boolean)
1224
             */
1225
        private boolean shutdown;
1226

    
1227
        /**
1228
         * <p>Sets this <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1229
         *
1230
         * @param isShutdown a boolean value
1231
         */
1232
        public void setShutdown(boolean isShutdown)
1233
        {
1234
            shutdown = isShutdown;
1235
        }
1236

    
1237
        /**
1238
         * <p>Creates a new drawer for managing all data painting requests in <code>MapControl</code>.</p>
1239
         *
1240
         * <p>Includes the following steps:
1241
         *  <ul>
1242
         *   <li>By default, there is no <i>current painting request</i>.</li>
1243
         *   <li>By default, there is no <i>waiting painting request</i>.</li>
1244
         *   <li>By default, the worker thread is waiting no <i>painting request</i>.</li>
1245
         *   <li>By default, the worker thread is running.</li>
1246
         *   <li>Creates and starts a worker thread for attending the <i>painting requests</i>.</li>
1247
         *  </ul>
1248
         * </p>
1249
         */
1250
        public Drawer2()
1251
        {
1252
            paintingRequest = null;
1253
            waitingRequest = null;
1254
            waiting = false;
1255
            shutdown = false;
1256
            new Thread(new Worker()).start();
1257
        }
1258

    
1259
        /**
1260
         * <p>Sets a <code>PaintingRequest</code> to be attended by the worker thread of this object. If
1261
         *  this one was waiting, wakes up.</p>
1262
         *
1263
         * <p>All waiting threads will be notified synchronized.</p>
1264
         *
1265
         * @param newPaintRequest
1266
         *
1267
         * @see #take()
1268
         */
1269
        public void put(PaintingRequest newPaintRequest)
1270
        {
1271
            waitingRequest = newPaintRequest;
1272
            if (waiting)
1273
            {
1274
                synchronized (this) {
1275
                    notifyAll();
1276
                }
1277
            }
1278
        }
1279

    
1280
        /**
1281
         * <p>Used by this object's worker, returns the current waiting drawing request, causing current thread
1282
         *  to wait until another thread invokes {@link #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest) #put(com.iver.cit.gvsig.fmap.MapControl.PaintingRequest)},
1283
         *  if there was no waiting request.</p>
1284
         *
1285
         * <p>All threads will access synchronized to the waiting request.</p>
1286
         *
1287
         * @return <code>PaintingRequest</code> that was waiting to be attended
1288
         *
1289
         * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1290
         */
1291
        public PaintingRequest take()
1292
        {
1293
            if (waitingRequest == null)
1294
            {
1295
                synchronized (this) {
1296
                    waiting = true;
1297
                    try {
1298
                        wait();
1299
                    }
1300
                    catch (InterruptedException ie)
1301
                    {
1302
                        waiting = false;
1303
                    }
1304
                }
1305
            }
1306
            paintingRequest = waitingRequest;
1307
            waitingRequest = null;
1308
            return paintingRequest;
1309
        }
1310

    
1311
        /**
1312
         * <p>Thread for attending painting requests.</p>
1313
         *
1314
         * <p>If there was no double buffer, sets the status to <code>OUTDATED</code> and finishes, otherwise
1315
         *  takes the painting request (it's probably that would wait some time), cancel the previous drawing
1316
         *  process, and starts processing the request.</p>
1317
         *
1318
         * @see Thread
1319
         */
1320
        private class Worker implements Runnable
1321
        {
1322
                /*
1323
                 * (non-Javadoc)
1324
                 * @see java.lang.Runnable#run()
1325
                 */
1326
                public void run()
1327
            {
1328
                while (!shutdown)
1329
                {
1330
                    PaintingRequest p = take();
1331
                    //System.out.println("Pintando");
1332
                    if (image != null){
1333
                            cancelDrawing();
1334
                        p.paint();
1335
                    } else{
1336
                        status = DESACTUALIZADO;
1337
                    }
1338
                }
1339
            }
1340
        }
1341
    }
1342

    
1343
        /**
1344
         * <p><code>Drawer</code> is implemented for drawing the layers of a <code>MapControl</code>'s <i>MapContext</i> instance
1345
         *  as a <i>thread</i> of execution.</p>
1346
         *
1347
         * <p>Draws <code>MapControl</code> according its <i>status</i>:
1348
         *  <ul>
1349
         *   <li><code><i>ONLY_GRAPHICS</i></code>: refreshes only the graphical layer, changing the status to <code><i>UPDATED</i></code>, via
1350
         *    {@linkplain MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double) MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)}.</li>
1351
         *   <li><code><i>OUTDATED</i></code>: refreshes all layers, changing the status to <code><i>UPDATED</i></code>, via
1352
         *    {@linkplain MapContext#draw(BufferedImage, Graphics2D, Cancellable, double) MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)}.</li>
1353
         *  <ul>
1354
         * </p>
1355
         *
1356
         * <p>This drawing process is accelerated by a <code>BufferedImage</code>, and can be canceled.</p>
1357
         *
1358
         * <p>Once the drawing process has finished, the timer stops and this component gets repainted.</p>
1359
         *
1360
         * @deprecated
1361
         * @author Vicente Caballero Navarro
1362
         */
1363
        public class Drawer extends Thread {
1364
                //private Graphics g;
1365

    
1366
                /**
1367
                 * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
1368
                 *
1369
                 * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
1370
                 * Meanwhile, the previous image can be kept showed.</p>
1371
                 *
1372
                 * @see BufferedImage
1373
                 */
1374
                private BufferedImage image = null;
1375

    
1376
                /**
1377
                 * <p>Object to store the flag that notifies the drawing must be canceled or can continue with the process.</p>
1378
                 *
1379
                 * <p>At last resort, the particular implementation of each layer in a <code>MapControl</code>'s <code>MapContrext</code>
1380
         *   will be which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
1381
                 */
1382
                private CancelDraw cancel;
1383
                //private boolean threadCancel = false;
1384

    
1385
                /**
1386
                 * <p>Creates a new <code>Drawer</code> instance.</p>
1387
                 */
1388
                public Drawer(BufferedImage image, CancelDraw cancel)
1389
        {
1390
                        this.image = image;
1391
                        this.cancel = cancel;
1392
         //   drawerAlive = true;
1393
                }
1394

    
1395
                /**
1396
                 * @see java.lang.Runnable#run()
1397
                 * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
1398
                 * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
1399
                 */
1400
                public void run() {
1401
                        try {
1402
                                // synchronized (Drawer.class) {
1403
                                    Graphics2D g = image.createGraphics();
1404

    
1405
                                    ViewPort viewPort = mapContext.getViewPort();
1406
                    if (status == DESACTUALIZADO)
1407
                    {
1408
                                        Color theBackColor = viewPort.getBackColor();
1409
                                        if (theBackColor == null) {
1410
                                                        g.setColor(Color.WHITE);
1411
                                                } else {
1412
                                                        g.setColor(theBackColor);
1413
                                                }
1414
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1415
                        status = ACTUALIZADO;
1416
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
1417
                    }
1418
                    else if (status == ONLY_GRAPHICS)
1419
                    {
1420
                        status = ACTUALIZADO;
1421
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
1422
                    }
1423

    
1424
                                        timer.stop();
1425
                    // status = FAST_PAINT;
1426
                  //  drawerAlive = false;
1427
                                        repaint();
1428

    
1429

    
1430

    
1431
                                // }
1432
                        } catch (Throwable e) {
1433
                            timer.stop();
1434
                                //isCancelled = true;
1435
                e.printStackTrace();
1436
                                throwException(e);
1437
                        } finally {
1438
                        }
1439
                }
1440
        }
1441

    
1442
        /**
1443
         * <p>An instance of <code>CancelDraw</code> will be shared by all this <code>MapControl</code>'s <code>MapContext</code> layers,
1444
         *  allowing receive a notification that, when they're been drawn, to be cancelled.</p>
1445
         *
1446
         * @see Cancellable
1447
         *
1448
         * @author Fernando Gonz?lez Cort?s
1449
         */
1450
        public class CancelDraw implements Cancellable {
1451
                /**
1452
                 * <p>Determines if the drawing task must be canceled or not.</p>
1453
                 *
1454
                 * @see #isCanceled()
1455
                 * @see #setCanceled(boolean)
1456
                 */
1457
                private boolean cancel = false;
1458

    
1459
                /**
1460
                 * Creates a new <code>CancelDraw</code> object.
1461
                 */
1462
                public CancelDraw() {
1463
                }
1464

    
1465
                /*
1466
                 * (non-Javadoc)
1467
                 * @see com.iver.utiles.swing.threads.Cancellable#setCanceled(boolean)
1468
                 */
1469
                public void setCanceled(boolean b) {
1470
                        cancel = b;
1471
                }
1472

    
1473
                /*
1474
                 * (non-Javadoc)
1475
                 * @see com.iver.utiles.swing.threads.Cancellable#isCanceled()
1476
                 */
1477
                public boolean isCanceled() {
1478
                        return cancel;
1479
                }
1480
        }
1481

    
1482
        /**
1483
         * <p>Listens all kind of mouse events produced in {@link MapControl MapControl}, and invokes its current
1484
         *  map tool <i>({@link MapControl#getCurrentMapTool() MapControl#getCurrentMapTool()}</i> to simulate a behavior.</p>
1485
         *
1486
         * <p>Mouse wheel moved events produce a <i>zoom in</i> operation if wheel rotation is negative, or a <i>zoom out</i>
1487
         *  if its positive. Both will be centered in the position of the mouse, but, meanwhile <i>zoom in</i> operation
1488
         *  applies a factor of 0.9, <i>zoom out</i> operation applies a factor of 1.2</p>
1489
         *
1490
         * <p>Mouse wheel moved events can be produced as much frequently, that between each one, the drawing process could
1491
         *  hadn't finished. This is the reason that, in this situation, cancels always the previous drawing process before
1492
         *  applying a <i>zoom</i> operation, and ignores all new mouse positions that are produced before 1 second.</p>
1493
         *
1494
         * @author Fernando Gonz?lez Cort?s
1495
         */
1496
        public class MapToolListener implements MouseListener, MouseWheelListener,
1497
                MouseMotionListener {
1498

    
1499
                /**
1500
                 * <p>Used to avoid mouse wheel move events closed.</p>
1501
                 *
1502
                 * <p>If a mouse wheel move event is produced
1503
                 */
1504
                long t1;
1505

    
1506
                /**
1507
                 * <p>Position of the mouse, in map coordinates.</p>
1508
                 *
1509
                 * <p>This point coordinates will be used as center of the <i>zoom</i> operation.</p>
1510
                 */
1511
                Point2D pReal;
1512

    
1513
                /**
1514
                 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1515
                 * @see Behavior#mouseClicked(MouseEvent)
1516
                 */
1517
                public void mouseClicked(MouseEvent e) {
1518
                        try {
1519
                                if (currentMapTool != null) {
1520
                                        currentMapTool.mouseClicked(e);
1521
                                }
1522
                        } catch (BehaviorException t) {
1523
                                throwException(t);
1524
                        }
1525
                }
1526

    
1527
                /**
1528
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1529
                 * @see Behavior#mouseEntered(MouseEvent)
1530
                 */
1531
                public void mouseEntered(MouseEvent e) {
1532
                        clearMouseImage();
1533
                        try {
1534
                                if (currentMapTool != null) {
1535
                                        currentMapTool.mouseEntered(e);
1536
                                }
1537
                        } catch (BehaviorException t) {
1538
                                throwException(t);
1539
                        }
1540
                }
1541

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

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

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

    
1584
                /**
1585
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
1586
                 * @see Behavior#mouseWheelMoved(MouseWheelEvent)
1587
                 */
1588
                public void mouseWheelMoved(MouseWheelEvent e) {
1589
                        try {
1590
                                if (currentMapTool == null) {
1591
                                        return;
1592
                                }
1593

    
1594
                                currentMapTool.mouseWheelMoved(e);
1595

    
1596
                                // Si el tool actual no ha consumido el evento
1597
                                // entendemos que quiere el comportamiento por defecto.
1598
                                if (!e.isConsumed())
1599
                                {
1600
                                        // Para usar el primer punto sobre el que queremos centrar
1601
                                        // el mapa, dejamos pasar un segundo para considerar el siguiente
1602
                                        // punto como v?lido.
1603
                                        if (t1 == 0)
1604
                                        {
1605
                                                t1= System.currentTimeMillis();
1606
                                                pReal = vp.toMapPoint(e.getPoint());
1607
                                        }
1608
                                        else
1609
                                        {
1610
                                                long t2 = System.currentTimeMillis();
1611
                                                if ((t2-t1) > 1000) {
1612
                                                        t1=0;
1613
                                                }
1614
                                        }
1615
                                        cancelDrawing();
1616
                                        ViewPort vp = getViewPort();
1617

    
1618

    
1619
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1620
                                                        vp.getAdjustedExtent().getCenterY()); */
1621
                                        int amount = e.getWheelRotation();
1622
                                        double nuevoX;
1623
                                        double nuevoY;
1624
                                        double factor;
1625

    
1626
                                        if (amount < 0) // nos acercamos
1627
                                        {
1628
                                                factor = 0.9;
1629
                                        } else // nos alejamos
1630
                                        {
1631
                                                factor = 1.2;
1632
                                        }
1633
                                        if (vp.getExtent() != null) {
1634
                                                nuevoX = pReal.getX()
1635
                                                                - ((vp.getExtent().getWidth() * factor) / 2.0);
1636
                                                nuevoY = pReal.getY()
1637
                                                                - ((vp.getExtent().getHeight() * factor) / 2.0);
1638
                                                double x = nuevoX;
1639
                                                double y = nuevoY;
1640
                                                double width = vp.getExtent().getWidth() * factor;
1641
                                                double height = vp.getExtent().getHeight() * factor;
1642

    
1643
                                                try {
1644
                                                        vp.setEnvelope(geomManager.createEnvelope(x,y,x+width,y+height, SUBTYPES.GEOM2D));
1645
                                                } catch (CreateEnvelopeException e1) {
1646
                                                        logger.error("Error creating the envelope", e);
1647
                                                }
1648
                                        }
1649

    
1650

    
1651
                                }
1652
                        } catch (BehaviorException t) {
1653
                                throwException(t);
1654
                        }
1655
                }
1656

    
1657
                /**
1658
                 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1659
                 * @see Behavior#mouseDragged(MouseEvent)
1660
                 */
1661
                public void mouseDragged(MouseEvent e) {
1662
                        calculateSnapPoint(e.getPoint());
1663
                        try {
1664
                                if (currentMapTool != null) {
1665
                                        currentMapTool.mouseDragged(e);
1666
                                }
1667
                        } catch (BehaviorException t) {
1668
                                throwException(t);
1669
                        }
1670
                        repaint();
1671
                }
1672

    
1673
                /**
1674
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
1675
                 * @see Behavior#mouseMoved(MouseEvent)
1676
                 */
1677
                public void mouseMoved(MouseEvent e) {
1678
                        calculateSnapPoint(e.getPoint());
1679
                        try {
1680
                                if (currentMapTool != null) {
1681
                                        currentMapTool.mouseMoved(e);
1682
                                }
1683
                        } catch (BehaviorException t) {
1684
                                throwException(t);
1685
                        }
1686
                        repaint();
1687
                }
1688
        }
1689

    
1690
        /**
1691
         * <p<code>MapContextListener</code> listens all events produced in a <code>MapControl</code>'s <code>MapContext</code>
1692
         * object during an atomic period of time, and sets it to dirty, <i>executing <code>drawMap(false)</code>, if any of the
1693
         * following conditions is accomplished</i>:
1694
         * <ul>
1695
         *  <li>Any of the <code>LayerEvent</code> in the <code>AtomicEvent</code> parameter notifies a <i>visibility change</i>.</li>
1696
         *  <li>There is at least one <code>ColorEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1697
         *  <li>There is at least one <code>ExtentEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1698
         *  <li>Any of the <code>LayerCollectionEvent</code> in the <code>AtomicEvent</code> parameter notifies that a driver's layer has reloaded it successfully.</li>
1699
         *  <li>There is at least one <code>LegendEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1700
         *  <li>There is at least one <code>SelectionEvent</code> in the <code>AtomicEvent</code> parameter.</li>
1701
         * </ul>
1702
         * </p>
1703
         *
1704
         * @author Fernando Gonz?lez Cort?s
1705
         */
1706
        public class MapContextListener implements AtomicEventListener {
1707
                /**
1708
                 * @see org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener#atomicEvent(org.gvsig.fmap.mapcontext.events.AtomicEvent)
1709
                 */
1710
                public void atomicEvent(AtomicEvent e) {
1711
                        LayerEvent[] layerEvents = e.getLayerEvents();
1712

    
1713
                        int eType;
1714
                        for (int i = 0; i < layerEvents.length; i++) {
1715
                                eType=layerEvents[i].getEventType();
1716
//                                if (eType == LayerEvent.DRAW_VALUES_CHANGED || eType == LayerEvent.VISIBILITY_CHANGED) {
1717
//                                        MapControl.this.drawMap(false);
1718
//                                        return;
1719
//                                }
1720
                                if (layerEvents[i].getProperty().equals("visible")) {
1721
                                        MapControl.this.drawMap(false);
1722
                                        return;
1723
                                } else if (layerEvents[i].getEventType() == LayerEvent.EDITION_CHANGED){
1724
                                        MapControl.this.drawMap(false);
1725
                                        return;
1726
                                }
1727
                        }
1728

    
1729
                        if (e.getColorEvents().length > 0) {
1730
                                MapControl.this.drawMap(false);
1731
                                return;
1732
                        }
1733

    
1734
                        if (e.getExtentEvents().length > 0) {
1735
                                MapControl.this.drawMap(false);
1736
                                return;
1737
                        }
1738

    
1739
                        if (e.getProjectionEvents().length > 0) {
1740
                                //redraw = true;
1741
                        }
1742

    
1743

    
1744
                        LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1745
                        if (aux.length > 0) {
1746
                                for (int i=0; i < aux.length; i++)
1747
                                {
1748
                                        if (aux[i].getAffectedLayer().getFLayerStatus().isDriverLoaded())
1749
                                        {
1750
                                                MapControl.this.drawMap(false);
1751
                                                return;
1752
                                        }
1753
                                }
1754

    
1755
                        }
1756

    
1757
                        if (e.getLegendEvents().length > 0) {
1758
                                MapControl.this.drawMap(false);
1759
                                return;
1760
                        }
1761

    
1762
                        if (e.getSelectionEvents().length > 0) {
1763
                                MapControl.this.drawMap(false);
1764
                                return;
1765
                        }
1766
                }
1767
        }
1768

    
1769
        /**
1770
         * <p>Gets the <code>ViewPort</code> of this component's {@link MapContext MapContext} .</p>
1771
         *
1772
         * @see MapContext#getViewPort()
1773
         */
1774
        public ViewPort getViewPort() {
1775
                return vp;
1776
        }
1777

    
1778
        /**
1779
         * <p>Returns all registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
1780
         *
1781
         * @return registered <code>Behavior</code> to this <code>MapControl</code>
1782
         *
1783
         * @see #addMapTool(String, Behavior)
1784
         * @see #addMapTool(String, Behavior[])
1785
         * @see #getMapToolsKeySet()
1786
         * @see #hasTool(String)
1787
         */
1788
        public HashMap getNamesMapTools() {
1789
                return namesMapTools;
1790
        }
1791

    
1792
        /*
1793
         * (non-Javadoc)
1794
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
1795
         */
1796
        public void commandRepaint() {
1797
                drawMap(false);
1798
        }
1799

    
1800
        /*
1801
         * (non-Javadoc)
1802
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
1803
         */
1804
        public void commandRefresh() {
1805
                // TODO Auto-generated method stub
1806
        }
1807

    
1808
        /**
1809
         * <p>Equivalent operation to <i>undo</i>.</p>
1810
         *
1811
         * <p>Exchanges the previous tool with the current one.</p>
1812
         *
1813
         * @see #addMapTool(String, Behavior)
1814
         * @see #addMapTool(String, Behavior[])
1815
         * @see #setTool(String)
1816
         */
1817
        public void setPrevTool() {
1818
                setTool(prevTool);
1819
        }
1820

    
1821
        /**
1822
         * <p>Executes a <i>zoom in</i> operation centered at the center of the extent.</p>
1823
         *
1824
         * <p>This implementation is designed for being invoked outside a <code>Behavior</code>, for example
1825
         *  by an action of pressing a button; and simulates that the event has been produced by
1826
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1827
         *  <code>MapControl</code> object that's responsible for the <i>zoom in</i> operation.</p>
1828
         *
1829
         * @see #zoomOut()
1830
         */
1831
        public void zoomIn() {
1832
                Behavior mapTool = (Behavior) namesMapTools.get("zoomIn");
1833
                ViewPort vp=getViewPort();
1834
                Envelope r=getViewPort().getAdjustedExtent();
1835
                Point2D pCenter=vp.fromMapPoint(r.getCenter(0),r.getCenter(1));
1836
                MouseEvent e=new MouseEvent(this,MouseEvent.MOUSE_RELEASED,MouseEvent.ACTION_EVENT_MASK,MouseEvent.BUTTON1,(int)pCenter.getX(),(int)pCenter.getY(),1,true,MouseEvent.BUTTON1);
1837
                try {
1838
                        mapTool.mousePressed(e);
1839
                        mapTool.mouseReleased(e);
1840
                } catch (BehaviorException t) {
1841
                        throwException(t);
1842
                }
1843
        }
1844

    
1845
        /**
1846
         * <p>Executes a <i>zoom out</i> operation centered at the center of the extent.</p>
1847
         *
1848
         * <p>This implementation is thought for being invoked outside a <code>Behavior</code>, for example
1849
         *  by an action of pressing a button, and simulates that the event has been produced by
1850
         *  releasing the <i>button 1</i> of the mouse using the registered <code>Behavior</code> in this
1851
         *  <code>MapControl</code> object that's responsible for the <i>zoom out</i> operation.</p>
1852
         *
1853
         * @see #zoomIn()
1854
         */
1855
        public void zoomOut() {
1856
                Behavior mapTool = (Behavior) namesMapTools.get("zoomOut");
1857
                ViewPort vp=getViewPort();
1858
                Envelope r=getViewPort().getAdjustedExtent();
1859
                Point2D pCenter=vp.fromMapPoint(r.getCenter(0),r.getCenter(1));
1860
                MouseEvent e=new MouseEvent(this,MouseEvent.MOUSE_RELEASED,MouseEvent.ACTION_EVENT_MASK,MouseEvent.BUTTON1,(int)pCenter.getX(),(int)pCenter.getY(),1,true,MouseEvent.BUTTON1);
1861
                try {
1862
                        mapTool.mousePressed(e);
1863
                        mapTool.mouseReleased(e);
1864
                } catch (BehaviorException t) {
1865
                        throwException(t);
1866
                }
1867
        }
1868

    
1869
        /**
1870
         * <p>Returns the listener used to catch all mouse events produced in this <code>MapControl</code> instance
1871
         *  and that redirects the calls to the current map tool.</p>
1872
         *
1873
         * @return the map tool listener used
1874
         */
1875
        public MapToolListener getMapToolListener() {
1876
                return mapToolListener;
1877
        }
1878

    
1879
//         mapTool can be null, for instance, in 3D's navigation tools
1880
        /**
1881
         * <p>Sets <code>mapTool</code> as this <code>MapControl</code>'s current map tool.
1882
         *
1883
         * @param mapTool a map tool, or <code>null</code> to disable the interaction with the user
1884
         *
1885
         * @see #getCurrentMapTool()
1886
         * @see #getCurrentTool()
1887
         * @see #setTool(String)
1888
         * @see #setPrevTool()
1889
         * @see #addMapTool(String, Behavior)
1890
         * @see #addMapTool(String, Behavior[])
1891
         */
1892
        public void setCurrentMapTool(Behavior mapTool ){
1893
                currentMapTool = mapTool;
1894
        }
1895

    
1896
        /**
1897
         * <p>Sets the delay to the timer that refreshes this <code>MapControl</code> instance.</p>
1898
         *
1899
         * <p><code>Delay (in ms) = 1000 / getDrawFrameRate()</code></p>
1900
         *
1901
         * @see #getDrawFrameRate()
1902
         * @see #setDrawFrameRate(int)
1903
         */
1904
        public void applyFrameRate() {
1905
                if (MapContext.getDrawFrameRate()>0) {
1906
                        timer.setDelay(1000/MapContext.getDrawFrameRate());
1907
                }
1908
        }
1909

    
1910

    
1911

    
1912
        /**
1913
         * <p>Determines if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1914
         *
1915
         * @return <code>true</code> if its enabled; otherwise <code>false</code>
1916
         */
1917
        public static boolean isDrawAnimationEnabled() {
1918
                return drawAnimationEnabled;
1919
        }
1920

    
1921
        /**
1922
         * <p>Sets if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1923
         *
1924
         * @param drawAnimationEnabled <code>true</code> to enable the mode; otherwise <code>false</code>
1925
         */
1926
        public static void setDrawAnimationEnabled(boolean drawAnimationEnabled) {
1927
                MapControl.drawAnimationEnabled = drawAnimationEnabled;
1928
        }
1929

    
1930
        /**
1931
         * <p>Gets the shared object that determines if a drawing process must be cancelled or can continue.</p>
1932
         *
1933
         * @return the shared object that determines if a drawing process must be cancelled or can continue
1934
         */
1935
        public CancelDraw getCanceldraw() {
1936
                return canceldraw;
1937
        }
1938

    
1939
        /**
1940
         * <p>Gets the tool used in combination with the current tool of this <code>MapControl</code>.</p>
1941
         *
1942
         * @return the tool used in combination with the <code>currentMapTool</code>; <code>null</code> if there is
1943
         *  no combined tool
1944
         */
1945
        public Behavior getCombinedTool() {
1946
                return combinedTool;
1947
        }
1948

    
1949
        /**
1950
         * <p>Sets a tool to be used in combination with the current tool of this <code>MapControl</code>.</p>
1951
         *
1952
         * @param combinedTool a tool to be used in combination with the current tool of <code>MapControl</code>
1953
         */
1954
        public void setCombinedTool(Behavior combinedTool) {
1955
                this.combinedTool = combinedTool;
1956

    
1957
                if (currentMapTool == null) {
1958
                        return;
1959
                }
1960

    
1961
                if (currentMapTool instanceof CompoundBehavior) {
1962
                        ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true);
1963
                }
1964
                else {
1965
                        currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool});
1966
                        ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true);
1967
                }
1968

    
1969
        }
1970
        /**
1971
         * <p>Adds a new tool as combined tool.</p>
1972
         * <p>The new tool will be stored with the previous combined tools, and will be combined with
1973
         *  the current tool.</p>
1974
         * <p>If <code>tool</code> was already stored as a combined tool, doesn't adds it.</p>
1975
         *
1976
         * @param tool a new tool to be used combined with the current tool
1977
         */
1978
        public void addCombinedTool(Behavior tool) {
1979
                if (combinedTool == null) {
1980
                        combinedTool = tool;
1981
                }
1982
                else {
1983
                        if (combinedTool instanceof CompoundBehavior) {
1984
                                if (((CompoundBehavior)combinedTool).containsBehavior(tool)) {
1985
                                        return;
1986
                                }
1987

    
1988
                                ((CompoundBehavior)combinedTool).addMapBehavior(tool, true);
1989
                        }
1990
                        else {
1991
                                if (combinedTool.equals(tool)) {
1992
                                        return;
1993
                                }
1994

    
1995
                                combinedTool = new CompoundBehavior(new Behavior[] {combinedTool});
1996
                                ((CompoundBehavior)combinedTool).addMapBehavior(tool, true);
1997
                        }
1998
                }
1999

    
2000
                if (currentMapTool == null) {
2001
                        return;
2002
                }
2003

    
2004
                if (currentMapTool instanceof CompoundBehavior) {
2005
                        ((CompoundBehavior)currentMapTool).addMapBehavior(tool, true);
2006
                }
2007
                else {
2008
                        currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool});
2009
                        ((CompoundBehavior)currentMapTool).addMapBehavior(tool, true);
2010
                }
2011
        }
2012
        /**
2013
         * <p>Removes the tool <code>tool</code> used in combination with the current tool of this <code>MapControl</code>.</p>
2014
         */
2015
        public void removeCombinedTool(Behavior tool) {
2016
                if ((currentMapTool != null) && (currentMapTool instanceof CompoundBehavior)) {
2017
                                ((CompoundBehavior)currentMapTool).removeMapBehavior(tool);
2018
                }
2019

    
2020
                if (combinedTool == null) {
2021
                        return;
2022
                }
2023

    
2024
                if (combinedTool instanceof CompoundBehavior) {
2025
                        ((CompoundBehavior)combinedTool).removeMapBehavior(tool);
2026
                }
2027
                else {
2028
                        combinedTool = null;
2029
                }
2030
        }
2031

    
2032

    
2033
        /**
2034
         * <p>Updates the grid on the <code>ViewPort</code> of the associated <code>MapControl</code>
2035
         *  object according the values in the {@link com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences com.iver.cit.gvsig.gui.cad.CADToolAdapter.prefs.Preferences}.</p>
2036
         *
2037
         * <p>The preferences are:
2038
         *  <ul>
2039
         *   <li>Show/hide the grid.</li>
2040
         *   <li>Adjust or not the grid.</li>
2041
         *   <li>Horizontal ( X ) line separation.</li>
2042
         *   <li>Vertical ( Y ) line separation.</li>
2043
         *  </ul>
2044
         * </p>
2045
         */
2046
        public void initializeGrid(){
2047
                boolean showGrid = prefs.getBoolean("grid.showgrid",cadgrid.isShowGrid());
2048
                boolean adjustGrid = prefs.getBoolean("grid.adjustgrid",cadgrid.isAdjustGrid());
2049

    
2050
                double dx = prefs.getDouble("grid.distancex",cadgrid.getGridSizeX());
2051
                double dy = prefs.getDouble("grid.distancey",cadgrid.getGridSizeY());
2052

    
2053
                setGridVisibility(showGrid);
2054
                setAdjustGrid(adjustGrid);
2055
                cadgrid.setGridSizeX(dx);
2056
                cadgrid.setGridSizeY(dy);
2057
        }
2058

    
2059
        public void setAdjustGrid(boolean adjustGrid) {
2060
                cadgrid.setAdjustGrid(adjustGrid);
2061
        }
2062

    
2063
        public void setGridVisibility(boolean showGrid) {
2064
                cadgrid.setShowGrid(showGrid);
2065
                cadgrid.setViewPort(getViewPort());
2066
                this.repaint();
2067
        }
2068
        /**
2069
         * <p>Draws a 31x31 pixels cross round the mouse's cursor with an small geometry centered:
2070
         *  <ul>
2071
         *   <li><i>an square centered</i>: if isn't over a <i>control point</i>.
2072
         *   <li><i>an small geometry centered according to the kind of control point</i>: if it's over a control
2073
         *    point. In this case, the small geometry is drawn by a {@link ISnapper ISnapper} type object.<br>
2074
         *    On the other hand, a light-yellowed background tool tip text with the type of <i>control point</i> will
2075
         *     be displayed.</li>
2076
         * </p>
2077
         *
2078
         * @param g <code>MapControl</code>'s graphics where the data will be drawn
2079
         */
2080
        private void drawCursor(Graphics g) {
2081
                Image cursor=getCurrentMapTool().getImageCursor();
2082

    
2083

    
2084

    
2085
                g.setColor(Color.black);
2086
                Point2D p = adjustedPoint;
2087

    
2088
                if (p == null) {
2089
                        cadgrid.setViewPort(vp);
2090
                        return;
2091
                }
2092
                g.drawImage(cursor, (int)p.getX()-16, (int)p.getY()-16, this);
2093
//                int size1 = 15;
2094
//                int size2 = 3;
2095
//                g.drawLine((int) (p.getX() - size1), (int) (p.getY()),
2096
//                                (int) (p.getX() + size1), (int) (p.getY()));
2097
//                g.drawLine((int) (p.getX()), (int) (p.getY() - size1),
2098
//                                (int) (p.getX()), (int) (p.getY() + size1));
2099
//
2100
//                // getMapControl().setToolTipText(null);
2101
//                if (adjustedPoint != null) {
2102
//                        if (bForceCoord) {
2103
//                                /* g.setColor(Color.ORANGE);
2104
//                                g.drawRect((int) (adjustedPoint.getX() - 6),
2105
//                                                (int) (adjustedPoint.getY() - 6), 12, 12);
2106
//                                g.drawRect((int) (adjustedPoint.getX() - 3),
2107
//                                                (int) (adjustedPoint.getY() - 3), 6, 6);
2108
//                                g.setColor(Color.MAGENTA);
2109
//                                g.drawRect((int) (adjustedPoint.getX() - 4),
2110
//                                                (int) (adjustedPoint.getY() - 4), 8, 8); */
2111
//                                if (usedSnap != null)
2112
//                                {
2113
//                                        usedSnap.draw(g, adjustedPoint);
2114
//
2115
//                                        Graphics2D g2 = (Graphics2D) g;
2116
//                                FontMetrics metrics = g2.getFontMetrics();
2117
//                                int w = metrics.stringWidth(usedSnap.getToolTipText()) + 5;
2118
//                                int h = metrics.getMaxAscent() + 5;
2119
//                                int x = (int)p.getX()+9;
2120
//                                int y = (int)p.getY()- 7;
2121
//
2122
//                                g2.setColor(theTipColor );
2123
//                                g2.fillRect(x, y-h, w, h);
2124
//                                g2.setColor(Color.BLACK);
2125
//                                g2.drawRect(x, y-h, w, h);
2126
//                                        g2.drawString(usedSnap.getToolTipText(), x+3, y-3);
2127
//
2128
//
2129
//                                        // getMapControl().setToolTipText(usedSnap.getToolTipText());
2130
//                                }
2131
//
2132
//                                bForceCoord = false;
2133
//                        } else {
2134
//                                g.drawRect((int) (p.getX() - size2), (int) (p.getY() - size2),
2135
//                                                (int) (size2 * 2), (int) (size2 * 2));
2136
//                        }
2137
//                }
2138
//                repaint();
2139
        }
2140
        /**
2141
         * Hides the mouse's cursor.
2142
         */
2143
        private void clearMouseImage() {
2144
                int[] pixels = new int[16 * 16];
2145
                Image image = Toolkit.getDefaultToolkit().createImage(
2146
                                new MemoryImageSource(16, 16, pixels, 0, 16));
2147
                Cursor transparentCursor = Toolkit.getDefaultToolkit()
2148
                                .createCustomCursor(image, new Point(0, 0), "invisiblecursor");
2149

    
2150
                setCursor(transparentCursor);
2151
        }
2152
        /**
2153
         * <p>Adjusts the <code>point</code> to the grid if its enabled, and
2154
         *  sets <code>mapHandlerAdjustedPoint</code> with that new value.</p>
2155
         *
2156
         * <p>The value returned is the distance between those points: the original and
2157
         *  the adjusted one.</p>
2158
         *
2159
         * @param point point to adjust
2160
         * @param mapHandlerAdjustedPoint <code>point</code> adjusted
2161
         *
2162
         * @return distance from <code>point</code> to the adjusted one. If there is no
2163
         *  adjustment, returns <code>Double.MAX_VALUE</code>.
2164
         */
2165

    
2166

    
2167
        private double adjustToHandler(Point2D point,
2168
            Point2D mapHandlerAdjustedPoint) {
2169

    
2170
        if (!isRefentEnabled())
2171
            return Double.MAX_VALUE;
2172

    
2173
        ArrayList snappers=new ArrayList(selected.keySet());
2174
        ArrayList layersToSnap = getMapContext().getLayersToSnap();
2175

    
2176
        double mapTolerance = vp.toMapDistance(MapControl.tolerance);
2177
        double minDist = mapTolerance;
2178
        double middleTol=mapTolerance * 0.5;
2179
        Point2D mapPoint = point;
2180
        org.gvsig.fmap.geom.primitive.Envelope r;
2181
                com.vividsolutions.jts.geom.Envelope e = null;
2182
                try {
2183
                        r = geomManager.createEnvelope(mapPoint.getX() - middleTol,
2184
                                        mapPoint.getY() - middleTol,
2185
                                        mapPoint.getX() + middleTol,
2186
                                        mapPoint.getY() + middleTol,
2187
                                        SUBTYPES.GEOM2D);
2188

    
2189
                        e = Converter.convertEnvelopeToJTS(r);
2190
                } catch (CreateEnvelopeException e1) {
2191
                        logger.error("Error creating the envelope", e1);
2192
                }
2193

    
2194
        usedSnap = null;
2195
        Point2D lastPoint = null;
2196
        if (previousPoint != null)
2197
        {
2198
            lastPoint = new Point2D.Double(previousPoint[0], previousPoint[1]);
2199
        }
2200
        for (int j = 0; j < layersToSnap.size(); j++)
2201
        {
2202
            FLyrVect lyrVect = (FLyrVect) layersToSnap.get(j);
2203
            SpatialCache cache = lyrVect.getSpatialCache();
2204
            if (lyrVect.isVisible())
2205
            {
2206
                // La lista de snappers est? siempre ordenada por prioridad. Los de mayor
2207
                // prioridad est?n primero.
2208
                java.util.List geoms = cache.query(e);
2209
                for (int n=0; n < geoms.size(); n++) {
2210
                    Geometry geom = (Geometry) geoms.get(n);
2211
                    for (int i = 0; i < snappers.size(); i++)
2212
                    {
2213
                        ISnapper theSnapper = (ISnapper) snappers.get(i);
2214

    
2215
                        if (usedSnap != null)
2216
                        {
2217
                            // Si ya tenemos un snap y es de alta prioridad, cogemos ese. (A no ser que en otra capa encontremos un snapper mejor)
2218
                            if (theSnapper.getPriority() > usedSnap.getPriority())
2219
                                break;
2220
                        }
2221
//                        SnappingVisitor snapVisitor = null;
2222
                        Point2D theSnappedPoint = null;
2223
                        if (theSnapper instanceof ISnapperVectorial)
2224
                        {
2225
                            theSnappedPoint = ((ISnapperVectorial) theSnapper).getSnapPoint(point, geom, mapTolerance, lastPoint);
2226
                        }
2227
                        if (theSnapper instanceof ISnapperRaster)
2228
                        {
2229
                            ISnapperRaster snapRaster = (ISnapperRaster) theSnapper;
2230
                            theSnappedPoint = snapRaster.getSnapPoint(this, point, mapTolerance, lastPoint);
2231
                        }
2232

    
2233

    
2234
                        if (theSnappedPoint != null) {
2235
                            double distAux = theSnappedPoint.distance(point);
2236
                            if (minDist > distAux)
2237
                            {
2238
                                minDist = distAux;
2239
                                usedSnap = theSnapper;
2240
                                mapHandlerAdjustedPoint.setLocation(theSnappedPoint);
2241
                            }
2242
                        }
2243
                    }
2244
                } // for n
2245
            } // visible
2246
        }
2247
        if (usedSnap != null)
2248
            return minDist;
2249
        return Double.MAX_VALUE;
2250

    
2251
    }
2252
        /**
2253
         * Determines if snap tools are enabled or disabled.
2254
         *
2255
         * @return <code>true</code> to enable the snap tools; <code>false</code> to disable them
2256
         *
2257
         * @see #setRefentEnabled(boolean)
2258
         */
2259
        public boolean isRefentEnabled()
2260
        {
2261
                return bRefent;
2262
        }
2263
        public void initializeSnapping() {
2264
                ArrayList snappers=getMapContext().getSnappers();
2265
        for (int n = 0; n < snappers.size(); n++) {
2266
            ISnapper snp = (ISnapper) snappers.get(n);
2267
            String nameClass=snp.getClass().getName();
2268
            nameClass=nameClass.substring(nameClass.lastIndexOf('.'));
2269
            boolean select = prefs.getBoolean("snapper_activated" + nameClass, false);
2270
            if (select) {
2271
                                selected.put(snp, new Boolean(select));
2272
                        }
2273
            int priority = prefs.getInt("snapper_priority" + nameClass,3);
2274
            snp.setPriority(priority);
2275
        }
2276
//        applySnappers = prefs.getBoolean("apply-snappers",true);
2277
//        snapConfig.setApplySnappers(applySnappers);
2278
//        snapConfig.selectSnappers(selected);
2279

    
2280
    }
2281
        /**
2282
         * <p>Tries to find the nearest geometry or grid control point by the position of the current snap tool.</p>
2283
         *
2284
         * <p>Prioritizes the grid control points than the geometries ones.</p>
2285
         *
2286
         * <p>If finds any near, stores the <i>map</i> and <i>pixel</i> coordinates for the snap, and enables
2287
         *  the <code>bForceCoord</code> attribute for the next draw of the mouse's cursor.</p>
2288
         *
2289
         * @param point current mouse 2D position
2290
         */
2291
        public Point2D calculateSnapPoint(Point point) {
2292
                // Se comprueba el ajuste a rejilla
2293

    
2294
                Point2D gridAdjustedPoint = vp.toMapPoint(
2295
                                point);
2296
                double minDistance = Double.MAX_VALUE;
2297
//                CADTool ct = (CADTool) cadToolStack.peek();
2298
//                if (ct instanceof SelectionCADTool
2299
//                                && ((SelectionCADTool) ct).getStatus().equals(
2300
//                                                "Selection.FirstPoint")) {
2301
//                        mapAdjustedPoint = gridAdjustedPoint;
2302
//                        adjustedPoint = (Point2D) point.clone();
2303
//                } else {
2304

    
2305
                        minDistance = cadgrid.adjustToGrid(gridAdjustedPoint);
2306
                        if (minDistance < Double.MAX_VALUE) {
2307
                                adjustedPoint = vp.fromMapPoint(
2308
                                                gridAdjustedPoint);
2309
                                mapAdjustedPoint = gridAdjustedPoint;
2310
                        } else {
2311
                                mapAdjustedPoint = null;
2312
                        }
2313
//                }
2314
                Point2D handlerAdjustedPoint = null;
2315

    
2316
                // Se comprueba el ajuste a los handlers
2317
                if (mapAdjustedPoint != null) {
2318
                        handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
2319
                } else {
2320
                        handlerAdjustedPoint = vp.toMapPoint(
2321
                                        point);
2322
                }
2323

    
2324
                Point2D mapPoint = new Point2D.Double();
2325
                double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
2326

    
2327
                if (distance < minDistance) {
2328
                        bForceCoord = true;
2329
                        adjustedPoint = vp.fromMapPoint(mapPoint);
2330
                        mapAdjustedPoint = mapPoint;
2331
                        minDistance = distance;
2332
                }
2333

    
2334
                // Si no hay ajuste
2335
                if (minDistance == Double.MAX_VALUE) {
2336
                        adjustedPoint = point;
2337
                        mapAdjustedPoint = null;
2338
                }
2339
                return mapAdjustedPoint;
2340
        }
2341
        /**
2342
         * Sets the snap tools enabled or disabled.
2343
         *
2344
         * @param activated <code>true</code> to enable the snap tools; <code>false</code> to disable them
2345
         *
2346
         * @see #isRefentEnabled()
2347
         */
2348
        public void setRefentEnabled(boolean activated) {
2349
                bRefent = activated;
2350
        }
2351

    
2352
        public Grid getGrid() {
2353
                return cadgrid;
2354
        }
2355

    
2356
        public static TreeMap getSelectedSnapppers() {
2357
                return selected;
2358
        }
2359

    
2360
        public void update(Observable observable, Object notification) {
2361
                DataStoreNotification ddsn=(DataStoreNotification)notification;
2362
                String type=ddsn.getType();
2363
                if (type.equals(FeatureStoreNotification.AFTER_UNDO) ||
2364
                                type.equals(FeatureStoreNotification.AFTER_REDO)){
2365
                        repaint();
2366
                }
2367
        }
2368
}