Statistics
| Revision:

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

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.geom.util.UtilFunctions;
83
import org.gvsig.fmap.mapcontext.MapContext;
84
import org.gvsig.fmap.mapcontext.ViewPort;
85
import org.gvsig.fmap.mapcontext.events.AtomicEvent;
86
import org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener;
87
import org.gvsig.fmap.mapcontext.layers.FLayers;
88
import org.gvsig.fmap.mapcontext.layers.GraphicLayer;
89
import org.gvsig.fmap.mapcontext.layers.LayerCollectionEvent;
90
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
91
import org.gvsig.fmap.mapcontext.layers.SpatialCache;
92
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
93
import org.gvsig.fmap.mapcontrol.tools.BehaviorException;
94
import org.gvsig.fmap.mapcontrol.tools.CompoundBehavior;
95
import org.gvsig.fmap.mapcontrol.tools.Behavior.Behavior;
96
import org.gvsig.fmap.mapcontrol.tools.Listeners.ToolListener;
97
import org.gvsig.fmap.mapcontrol.tools.grid.Grid;
98
import org.gvsig.fmap.mapcontrol.tools.snapping.GeometriesSnappingVisitor;
99
import org.gvsig.fmap.mapcontrol.tools.snapping.SnappingVisitor;
100
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapper;
101
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapperGeometriesVectorial;
102
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapperRaster;
103
import org.gvsig.fmap.mapcontrol.tools.snapping.snappers.ISnapperVectorial;
104
import org.gvsig.tools.observer.Observable;
105
import org.gvsig.tools.observer.Observer;
106
import org.gvsig.tools.task.Cancellable;
107
import org.slf4j.Logger;
108
import org.slf4j.LoggerFactory;
109

    
110
import com.iver.utiles.exceptionHandling.ExceptionHandlingSupport;
111
import com.iver.utiles.exceptionHandling.ExceptionListener;
112

    
113

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

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

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

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

    
233

    
234

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

    
240
    // public static final int FAST_PAINT = 3;
241
        //private static Logger logger = Logger.getLogger(MapControl.class.getName());
242

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

    
252
    //private boolean drawerAlive = false;
253

    
254

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

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

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

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

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

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

    
320
    //private boolean isCancelled = true;
321

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

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

    
348
    //private Drawer drawer;
349

    
350
        /**
351
         * <p>Manager of all <code>MapControl</code> painting requests.</p>
352
         */
353
    private Drawer2 drawer2;
354

    
355
    // private boolean firstDraw = true;
356

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

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

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

    
385
    /**
386
     * <p>Name of the previous tool used.</p>
387
     */
388
        protected String prevTool;
389

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

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

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

    
441
        /**
442
         * Stores the 2D map coordinates of the last point added.
443
         */
444
        private double[] previousPoint = null;
445

    
446
        private static HashMap selected = new HashMap();
447

    
448
        public static int tolerance=4;
449
        /**
450
         * Represents the cursor's point selected in <i>map coordinates</i>.
451
         *
452
         * @see MapControl#toMapPoint
453
         */
454
        private Point2D mapAdjustedPoint;
455

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

    
479
                //Clase usada para cancelar el dibujado
480
                canceldraw = new CancelDraw();
481

    
482
                //Modelo de datos y ventana del mismo
483
                // TODO: Cuando creamos un mapControl, deber?amos asignar
484
                // la projecci?n por defecto con la que vayamos a trabajar.
485
                // 23030 es el c?digo EPSG del UTM30 elipsoide ED50
486
                vp = new ViewPort(CRSFactory.getCRS("EPSG:23030"));
487
                setMapContext(new MapContext(vp));
488

    
489
                //eventos
490
                this.addComponentListener(this);
491
                this.addMouseListener(mapToolListener);
492
                this.addMouseMotionListener(mapToolListener);
493
                this.addMouseWheelListener(mapToolListener);
494

    
495
        this.drawer2 = new Drawer2();
496
                //Timer para mostrar el redibujado mientras se dibuja
497
                timer = new Timer(1000/MapContext.getDrawFrameRate(),
498
                                new ActionListener() {
499
                                        public void actionPerformed(ActionEvent e) {
500

    
501
                                                if (drawAnimationEnabled) {
502
                                                        MapControl.this.repaint();
503
                                                }
504
                                        }
505
                                });
506
                initializeGrid();
507
        }
508

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

    
532
                mapContext = model;
533

    
534
                if (mapContext.getViewPort() == null) {
535
                        mapContext.setViewPort(vp);
536
                } else {
537
                        vp = mapContext.getViewPort();
538
                        cadgrid.setViewPort(vp);
539
                        // vp.setImageSize(new Dimension(getWidth(), getHeight()));
540
                        //System.err.println("Viewport en setMapContext:" + vp);
541
                }
542

    
543
                mapContext.addAtomicEventListener(mapContextListener);
544

    
545
                status = DESACTUALIZADO;
546
        }
547

    
548
        /**
549
         * <p>Gets this component's {@link MapContext MapContext} projection.</p>
550
         *
551
         * @return this component's {@link MapContext MapContext} projection
552
         *
553
         * @see MapContext#getProjection()
554
         * @see MapControl#setProjection(IProjection)
555
         */
556
        public IProjection getProjection() {
557
                return getMapContext().getProjection();
558
        }
559

    
560
        /**
561
         * <p>Sets the projection to this component's {@link MapContext MapContext}.</p>
562
         *
563
         * @param proj the kind of projection to this component's {@link MapContext MapContext}
564
         *
565
         * @see MapContext#setProjection(IProjection)
566
         * @see MapControl#getProjection()
567
         */
568
        public void setProjection(IProjection proj) {
569
                getMapContext().setProjection(proj);
570
        }
571

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

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

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

    
628
        /**
629
         * <p>Gets the <code>Behavior</code> registered in this component, identified
630
         *  by <code>name</code>.</p>
631
         *
632
         * @param name name of a registered behavior
633
         *
634
         * @return tool the registered behavior in this component as <code>name</code>, or <code>null</code> if
635
         *  no one has that identifier
636
         *
637
         * @see #addMapTool(String, Behavior)
638
         * @see #addMapTool(String, Behavior[])
639
         * @see #hasTool(String)
640
         */
641
        public Behavior getMapTool(String name) {
642
                return (Behavior)namesMapTools.get(name);
643
        }
644

    
645
        /**
646
         * <p>Returns a set view of the keys that identified the tools
647
         *  registered.</p>
648
         *
649
         * @return a set view of the keys that identified the tools registered
650
         *
651
         * @see HashMap#keySet()
652
         *
653
         * @see #getNamesMapTools()
654
          * @see #addMapTool(String, Behavior)
655
          * @see #addMapTool(String, Behavior[])
656
         */
657
        public Set getMapToolsKeySet() {
658
                return namesMapTools.keySet();
659
        }
660

    
661
        /**
662
         * <p>Returns <code>true</code> if this component contains a tool identified by <code>toolName</code>.</p>
663
         *
664
         * @param toolName identifier of the tool
665
         *
666
         * @return <code>true</code> if this component contains a tool identified by <code>toolName</code>; otherwise <code>false</code>
667
         *
668
         * @see #addMapTool(String, Behavior)
669
         * @see #addMapTool(String, Behavior[])
670
         */
671
        public boolean hasTool(String toolName) {
672
                return namesMapTools.containsKey(toolName);
673
        }
674

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

    
693
                if (combinedTool != null) {
694
                        if (mapTool instanceof CompoundBehavior) {
695
                                ((CompoundBehavior)mapTool).addMapBehavior(combinedTool, true);
696
                        }
697
                        else {
698
                                currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool});
699
                                ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true);
700
                        }
701
                }
702

    
703
//                this.setCursor(mapTool.getCursor());
704
        }
705

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

    
722
        /**
723
         * <p>Returns the name of the current selected tool on this MapControl</p>
724
         *
725
         * @return the name of the current's behavior tool associated to this component
726
         *
727
         * @see #getCurrentMapTool()
728
         * @see #setTool(String)
729
         */
730
        public String getCurrentTool() {
731
                return currentTool;
732
        }
733

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

    
751
                /* while (!isCancelled) {
752
                        if (!drawer.isAlive()) {
753
                            // Si hemos llegado aqu? con un thread vivo, seguramente
754
                            // no estamos actualizados.
755

756
                                break;
757
                        }
758

759
                }
760
                canceldraw.setCancel(false);
761
                isCancelled = false;
762
        drawerAlive = false; */
763
        }
764

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

    
792

    
793
            Graphics gTemp = image.createGraphics();
794
            Color theBackColor = vp.getBackColor();
795
            if (theBackColor == null) {
796
                                gTemp.setColor(Color.WHITE);
797
                        } else {
798
                                gTemp.setColor(theBackColor);
799
                        }
800

    
801
            gTemp.fillRect(0,0,getWidth(), getHeight());
802
            gTemp.dispose();
803
            status = DESACTUALIZADO;
804
            // g.drawImage(image,0,0,null);
805
            return true;
806
        }
807
        return false;
808
    }
809

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

    
841
                        /*
842
                         * Si hay un behaviour y la imagen es distinta de null se delega el dibujado
843
                         * en dicho behaviour
844
                         */
845
            if (image != null)
846
            {
847
                if (currentMapTool != null) {
848
                                        currentMapTool.paintComponent(g);
849
                                } else {
850
                                        g.drawImage(image,0,0,null);
851
                                }
852

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

881
                                gTemp.fillRect(0,0,getWidth(), getHeight());
882
                                gTemp.dispose();
883
                                // g.drawImage(image,0,0,null);
884
                                System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
885
                        } */
886
            // else
887
            // {
888

    
889

    
890
            // if (image != null)
891
            //  {
892
                g.drawImage(image,0,0,null);
893

    
894
                drawer2.put(new PaintingRequest());
895
                timer.start();
896
            /* }
897
            else
898
                return; */
899
            // }
900

    
901
            /* if (drawerAlive == false)
902
            {
903
                drawer = new Drawer(image, canceldraw);
904
                drawer.start();
905
                        //Se lanza el tread de dibujado
906
            } */
907

    
908
                        // status = ACTUALIZADO;
909
                }
910
                cadgrid.drawGrid(g);
911
                drawCursor(g);
912
        }
913

    
914
        /**
915
         * <p>Gets the {@link BufferedImage BufferedImage} used to accelerate the draw of new ''frames'' with changes,
916
         * or new graphical items in this component.</p>
917
         *
918
         * @return double buffered image used by this component to accelerate the draw of its graphical information, or
919
         * <code>null</code> if isn't already created
920
         *
921
         * @see BufferedImage
922
         */
923
        public BufferedImage getImage() {
924
                return image;
925
        }
926

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

    
961

    
962
        /**
963
         * <p>Cancels any current drawing process, changing the status to <code>OUTDATED</code>, and forcing
964
         * repaint only the layers dirty.</p>
965
         *
966
         * @see #cancelDrawing()
967
         */
968
        public void rePaintDirtyLayers()
969
        {
970
                cancelDrawing();
971
        status = DESACTUALIZADO;
972
        repaint();
973
        }
974

    
975
        /**
976
         * <p>Cancels any current drawing process, changing the status to <code>ONLY_GRAPHICS</code>, and forcing
977
         * repaint only the graphical layer of the <code>MapContext</code>.</p>
978
         */
979
    public void drawGraphics() {
980
        status = ONLY_GRAPHICS;
981
        repaint();
982
    }
983

    
984
        /**
985
         * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)
986
         */
987
        public void componentHidden(ComponentEvent e) {
988
        }
989

    
990
        /**
991
         * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)
992
         */
993
        public void componentMoved(ComponentEvent e) {
994
        }
995

    
996
        /**
997
         * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)
998
         */
999
        public void componentResized(ComponentEvent e) {
1000
                /* image = new BufferedImage(this.getWidth(), this.getHeight(),
1001
                                BufferedImage.TYPE_INT_ARGB);
1002
                Graphics gTemp = image.createGraphics();
1003
                gTemp.setColor(vp.getBackColor());
1004
                gTemp.fillRect(0,0,getWidth(), getHeight());
1005
        System.out.println("MapControl resized");
1006
            // image = null;
1007
            vp.setImageSize(new Dimension(getWidth(), getHeight()));
1008
                getMapContext().getViewPort().setScale(); */
1009
                // drawMap(true);
1010
        }
1011

    
1012
        /**
1013
         * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)
1014
         */
1015
        public void componentShown(ComponentEvent e) {
1016
        }
1017

    
1018
        /**
1019
         * @see ExceptionHandlingSupport#addExceptionListener(ExceptionListener)
1020
         */
1021
        public void addExceptionListener(ExceptionListener o) {
1022
                exceptionHandlingSupport.addExceptionListener(o);
1023
        }
1024

    
1025
        /**
1026
         * @see ExceptionHandlingSupport#removeExceptionListener(ExceptionListener)
1027
         */
1028
        public boolean removeExceptionListener(ExceptionListener o) {
1029
                return exceptionHandlingSupport.removeExceptionListener(o);
1030
        }
1031

    
1032
        /**
1033
         * @see ExceptionHandlingSupport#throwException(Throwable)
1034
         */
1035
        protected void throwException(Throwable t) {
1036
                exceptionHandlingSupport.throwException(t);
1037
        }
1038

    
1039
        /**
1040
         * <p>Represents each <code>MapControl</code>'s data painting request.</p>
1041
         *
1042
         * <p>The request will be attended by a <code>Drawer2</code>, which will hold it since the <code>Drawer2</code>'s worker
1043
         *  takes it, or arrives a new painting request, which will replace it.</p>
1044
         */
1045
    private class PaintingRequest
1046
    {
1047
            /**
1048
             * <p>Creates a new <code>PaintingRequest</p> instance.</p>
1049
             */
1050
        public PaintingRequest()
1051
        {
1052
        }
1053

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

1106
                    gTemp.fillRect(0,0,getWidth(), getHeight());
1107
                    gTemp.dispose();
1108
                    // g.drawImage(image,0,0,null);
1109
                    System.out.println("Imagen con null en DESACTUALIZADO. Width = " + this.getWidth());
1110
                } */
1111
                Graphics2D g = image.createGraphics();
1112

    
1113
                ViewPort viewPort = mapContext.getViewPort();
1114

    
1115
                if (status == DESACTUALIZADO)
1116
                {
1117
                        Graphics2D gTemp = image.createGraphics();
1118
                    Color theBackColor = viewPort.getBackColor();
1119
                    if (theBackColor == null) {
1120
                                                gTemp.setColor(Color.WHITE);
1121
                                        } else {
1122
                                                gTemp.setColor(theBackColor);
1123
                                        }
1124
                    gTemp.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1125
                    // ESTILO MAC
1126
//                  BufferedImage imgMac = new BufferedImage(vp.getImageWidth(), vp.getImageHeight(),
1127
//                          BufferedImage.TYPE_INT_ARGB);
1128
          //
1129
//                  mapContext.draw(imgMac, g, canceldraw, mapContext.getScaleView());
1130
//                  g.drawImage(imgMac, 0, 0, null);
1131
                  // FIN ESTILO MAC
1132
                  // SIN MAC:
1133

    
1134
                  mapContext.draw(image, g, canceldraw, mapContext.getScaleView());
1135
                  if (!canceldraw.isCanceled()){
1136
                          status=ACTUALIZADO;
1137
                 }else{
1138
                          status=DESACTUALIZADO;
1139
//                          getMapContext().getLayers().setDirty(true);
1140
                  }
1141

    
1142
                }
1143
                else if (status == ONLY_GRAPHICS)
1144
                {
1145
                    status = ACTUALIZADO;
1146
                    mapContext.drawGraphics(image, g, canceldraw,mapContext.getScaleView());
1147

    
1148
                }
1149

    
1150

    
1151

    
1152
                // status = FAST_PAINT;
1153
              //  drawerAlive = false;
1154
                timer.stop();
1155
                repaint();
1156

    
1157

    
1158
            } catch (Throwable e) {
1159
                timer.stop();
1160
              //  isCancelled = true;
1161
                e.printStackTrace();
1162
                throwException(e);
1163
            } finally {
1164
            }
1165
        }
1166
    }
1167

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

    
1187

    
1188
            /**
1189
             * <p>Painting request that's been attended by the <code>Drawer2</code>'s worker.</p>
1190
             *
1191
             * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1192
             * @see #take()
1193
             */
1194
            private PaintingRequest paintingRequest;
1195

    
1196
            /**
1197
             * <p>Painting request waiting to be 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 waitingRequest;
1203

    
1204
            /**
1205
             * <p>Determines that the <code>Drawer2</code>'s worker is busy attending a painting request.</p>
1206
              *
1207
             * @see #put(org.gvsig.fmap.mapcontrol.MapControl.PaintingRequest)
1208
             * @see #take()
1209
             */
1210
        private boolean waiting;
1211

    
1212
            /**
1213
             * <p>Notifies the <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1214
             *
1215
             * @see #setShutdown(boolean)
1216
             */
1217
        private boolean shutdown;
1218

    
1219
        /**
1220
         * <p>Sets this <code>Drawer2</code>'s worker to finish or continue with its process.</p>
1221
         *
1222
         * @param isShutdown a boolean value
1223
         */
1224
        public void setShutdown(boolean isShutdown)
1225
        {
1226
            shutdown = isShutdown;
1227
        }
1228

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

    
1251
        /**
1252
         * <p>Sets a <code>PaintingRequest</code> to be attended by the worker thread of this object. If
1253
         *  this one was waiting, wakes up.</p>
1254
         *
1255
         * <p>All waiting threads will be notified synchronized.</p>
1256
         *
1257
         * @param newPaintRequest
1258
         *
1259
         * @see #take()
1260
         */
1261
        public void put(PaintingRequest newPaintRequest)
1262
        {
1263
            waitingRequest = newPaintRequest;
1264
            if (waiting)
1265
            {
1266
                synchronized (this) {
1267
                    notifyAll();
1268
                }
1269
            }
1270
        }
1271

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

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

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

    
1358
                /**
1359
                 * <p>Image with a buffer to accelerate the draw the changes of the graphical items in this component.</p>
1360
                 *
1361
                 * <p>Firstly, information will be drawn in the buffer, and, when is outright drawn, that information will be displayed.
1362
                 * Meanwhile, the previous image can be kept showed.</p>
1363
                 *
1364
                 * @see BufferedImage
1365
                 */
1366
                private BufferedImage image = null;
1367

    
1368
                /**
1369
                 * <p>Object to store the flag that notifies the drawing must be canceled or can continue with the process.</p>
1370
                 *
1371
                 * <p>At last resort, the particular implementation of each layer in a <code>MapControl</code>'s <code>MapContrext</code>
1372
         *   will be which will draw the graphical information, and, if supports, which could cancel its drawing subprocess.</p>
1373
                 */
1374
                private CancelDraw cancel;
1375
                //private boolean threadCancel = false;
1376

    
1377
                /**
1378
                 * <p>Creates a new <code>Drawer</code> instance.</p>
1379
                 */
1380
                public Drawer(BufferedImage image, CancelDraw cancel)
1381
        {
1382
                        this.image = image;
1383
                        this.cancel = cancel;
1384
         //   drawerAlive = true;
1385
                }
1386

    
1387
                /**
1388
                 * @see java.lang.Runnable#run()
1389
                 * @see MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)
1390
                 * @see MapContext#drawGraphics(BufferedImage, Graphics2D, Cancellable, double)
1391
                 */
1392
                public void run() {
1393
                        try {
1394
                                // synchronized (Drawer.class) {
1395
                                    Graphics2D g = image.createGraphics();
1396

    
1397
                                    ViewPort viewPort = mapContext.getViewPort();
1398
                    if (status == DESACTUALIZADO)
1399
                    {
1400
                                        Color theBackColor = viewPort.getBackColor();
1401
                                        if (theBackColor == null) {
1402
                                                        g.setColor(Color.WHITE);
1403
                                                } else {
1404
                                                        g.setColor(theBackColor);
1405
                                                }
1406
                                            g.fillRect(0, 0, viewPort.getImageWidth(), viewPort.getImageHeight());
1407
                        status = ACTUALIZADO;
1408
                        mapContext.draw(image, g, cancel,mapContext.getScaleView());
1409
                    }
1410
                    else if (status == ONLY_GRAPHICS)
1411
                    {
1412
                        status = ACTUALIZADO;
1413
                        mapContext.drawGraphics(image, g, cancel,mapContext.getScaleView());
1414
                    }
1415

    
1416
                                        timer.stop();
1417
                    // status = FAST_PAINT;
1418
                  //  drawerAlive = false;
1419
                                        repaint();
1420

    
1421

    
1422

    
1423
                                // }
1424
                        } catch (Throwable e) {
1425
                            timer.stop();
1426
                                //isCancelled = true;
1427
                e.printStackTrace();
1428
                                throwException(e);
1429
                        } finally {
1430
                        }
1431
                }
1432
        }
1433

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

    
1451
                /**
1452
                 * Creates a new <code>CancelDraw</code> object.
1453
                 */
1454
                public CancelDraw() {
1455
                }
1456

    
1457
                /*
1458
                 * (non-Javadoc)
1459
                 * @see com.iver.utiles.swing.threads.Cancellable#setCanceled(boolean)
1460
                 */
1461
                public void setCanceled(boolean b) {
1462
                        cancel = b;
1463
                }
1464

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

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

    
1491
                /**
1492
                 * <p>Used to avoid mouse wheel move events closed.</p>
1493
                 *
1494
                 * <p>If a mouse wheel move event is produced
1495
                 */
1496
                long t1;
1497

    
1498
                /**
1499
                 * <p>Position of the mouse, in map coordinates.</p>
1500
                 *
1501
                 * <p>This point coordinates will be used as center of the <i>zoom</i> operation.</p>
1502
                 */
1503
                Point2D pReal;
1504

    
1505
                /**
1506
                 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1507
                 * @see Behavior#mouseClicked(MouseEvent)
1508
                 */
1509
                public void mouseClicked(MouseEvent e) {
1510
                        try {
1511
                                if (currentMapTool != null) {
1512
                                        currentMapTool.mouseClicked(e);
1513
                                }
1514
                        } catch (BehaviorException t) {
1515
                                throwException(t);
1516
                        }
1517
                }
1518

    
1519
                /**
1520
                 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1521
                 * @see Behavior#mouseEntered(MouseEvent)
1522
                 */
1523
                public void mouseEntered(MouseEvent e) {
1524
                        clearMouseImage();
1525
                        try {
1526
                                if (currentMapTool != null) {
1527
                                        currentMapTool.mouseEntered(e);
1528
                                }
1529
                        } catch (BehaviorException t) {
1530
                                throwException(t);
1531
                        }
1532
                }
1533

    
1534
                /**
1535
                 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1536
                 * @see Behavior#mouseExited(MouseEvent)
1537
                 */
1538
                public void mouseExited(MouseEvent e) {
1539
                        try {
1540
                                if (currentMapTool != null) {
1541
                                        currentMapTool.mouseExited(e);
1542
                                }
1543
                        } catch (BehaviorException t) {
1544
                                throwException(t);
1545
                        }
1546
                }
1547

    
1548
                /**
1549
                 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1550
                 * @see Behavior#mousePressed(MouseEvent)
1551
                 */
1552
                public void mousePressed(MouseEvent e) {
1553
                        try {
1554
                                if (currentMapTool != null) {
1555
                                        currentMapTool.mousePressed(e);
1556
                                }
1557
                        } catch (BehaviorException t) {
1558
                                throwException(t);
1559
                        }
1560
                }
1561

    
1562
                /**
1563
                 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1564
                 * @see Behavior#mouseReleased(MouseEvent)
1565
                 */
1566
                public void mouseReleased(MouseEvent e) {
1567
                        try {
1568
                                if (currentMapTool != null) {
1569
                                        currentMapTool.mouseReleased(e);
1570
                                }
1571
                        } catch (BehaviorException t) {
1572
                                throwException(t);
1573
                        }
1574
                }
1575

    
1576
                /**
1577
                 * @see java.awt.event.MouseWheelListener#mouseWheelMoved(java.awt.event.MouseWheelEvent)
1578
                 * @see Behavior#mouseWheelMoved(MouseWheelEvent)
1579
                 */
1580
                public void mouseWheelMoved(MouseWheelEvent e) {
1581
                        try {
1582
                                if (currentMapTool == null) {
1583
                                        return;
1584
                                }
1585

    
1586
                                currentMapTool.mouseWheelMoved(e);
1587

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

    
1610

    
1611
                                        /* Point2D pReal = new Point2D.Double(vp.getAdjustedExtent().getCenterX(),
1612
                                                        vp.getAdjustedExtent().getCenterY()); */
1613
                                        int amount = e.getWheelRotation();
1614
                                        double nuevoX;
1615
                                        double nuevoY;
1616
                                        double factor;
1617

    
1618
                                        if (amount < 0) // nos acercamos
1619
                                        {
1620
                                                factor = 0.9;
1621
                                        } else // nos alejamos
1622
                                        {
1623
                                                factor = 1.2;
1624
                                        }
1625
                                        if (vp.getExtent() != null) {
1626
                                                nuevoX = pReal.getX()
1627
                                                                - ((vp.getExtent().getWidth() * factor) / 2.0);
1628
                                                nuevoY = pReal.getY()
1629
                                                                - ((vp.getExtent().getHeight() * factor) / 2.0);
1630
                                                double x = nuevoX;
1631
                                                double y = nuevoY;
1632
                                                double width = vp.getExtent().getWidth() * factor;
1633
                                                double height = vp.getExtent().getHeight() * factor;
1634

    
1635
                                                try {
1636
                                                        vp.setEnvelope(geomManager.createEnvelope(x,y,x+width,y+height, SUBTYPES.GEOM2D));
1637
                                                } catch (CreateEnvelopeException e1) {
1638
                                                        logger.error("Error creating the envelope", e);
1639
                                                }
1640
                                        }
1641

    
1642

    
1643
                                }
1644
                        } catch (BehaviorException t) {
1645
                                throwException(t);
1646
                        }
1647
                }
1648

    
1649
                /**
1650
                 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1651
                 * @see Behavior#mouseDragged(MouseEvent)
1652
                 */
1653
                public void mouseDragged(MouseEvent e) {
1654
                        calculateSnapPoint(e.getPoint());
1655
                        try {
1656
                                if (currentMapTool != null) {
1657
                                        currentMapTool.mouseDragged(e);
1658
                                }
1659
                        } catch (BehaviorException t) {
1660
                                throwException(t);
1661
                        }
1662
                        repaint();
1663
                }
1664

    
1665
                /**
1666
                 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
1667
                 * @see Behavior#mouseMoved(MouseEvent)
1668
                 */
1669
                public void mouseMoved(MouseEvent e) {
1670
                        calculateSnapPoint(e.getPoint());
1671
                        try {
1672
                                if (currentMapTool != null) {
1673
                                        currentMapTool.mouseMoved(e);
1674
                                }
1675
                        } catch (BehaviorException t) {
1676
                                throwException(t);
1677
                        }
1678
                        repaint();
1679
                }
1680
        }
1681

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

    
1705
                        int eType;
1706
                        for (int i = 0; i < layerEvents.length; i++) {
1707
                                eType=layerEvents[i].getEventType();
1708
//                                if (eType == LayerEvent.DRAW_VALUES_CHANGED || eType == LayerEvent.VISIBILITY_CHANGED) {
1709
//                                        MapControl.this.drawMap(false);
1710
//                                        return;
1711
//                                }
1712
                                if (layerEvents[i].getProperty().equals("visible")) {
1713
                                        MapControl.this.drawMap(false);
1714
                                        return;
1715
                                } else if (layerEvents[i].getEventType() == LayerEvent.EDITION_CHANGED){
1716
                                        MapControl.this.drawMap(false);
1717
                                        return;
1718
                                }
1719
                        }
1720

    
1721
                        if (e.getColorEvents().length > 0) {
1722
                                MapControl.this.drawMap(false);
1723
                                return;
1724
                        }
1725

    
1726
                        if (e.getExtentEvents().length > 0) {
1727
                                MapControl.this.drawMap(false);
1728
                                return;
1729
                        }
1730

    
1731
                        if (e.getProjectionEvents().length > 0) {
1732
                                //redraw = true;
1733
                        }
1734

    
1735

    
1736
                        LayerCollectionEvent[] aux = e.getLayerCollectionEvents();
1737
                        if (aux.length > 0) {
1738
                                for (int i=0; i < aux.length; i++)
1739
                                {
1740
                                        if (aux[i].getAffectedLayer().getFLayerStatus().isDriverLoaded())
1741
                                        {
1742
                                                MapControl.this.drawMap(false);
1743
                                                return;
1744
                                        }
1745
                                }
1746

    
1747
                        }
1748

    
1749
                        if (e.getLegendEvents().length > 0) {
1750
                                MapControl.this.drawMap(false);
1751
                                return;
1752
                        }
1753

    
1754
                        if (e.getSelectionEvents().length > 0) {
1755
                                MapControl.this.drawMap(false);
1756
                                return;
1757
                        }
1758
                }
1759
        }
1760

    
1761
        /**
1762
         * <p>Gets the <code>ViewPort</code> of this component's {@link MapContext MapContext} .</p>
1763
         *
1764
         * @see MapContext#getViewPort()
1765
         */
1766
        public ViewPort getViewPort() {
1767
                return vp;
1768
        }
1769

    
1770
        /**
1771
         * <p>Returns all registered <code>Behavior</code> that can define a way to work with this <code>MapControl</code>.</p>
1772
         *
1773
         * @return registered <code>Behavior</code> to this <code>MapControl</code>
1774
         *
1775
         * @see #addMapTool(String, Behavior)
1776
         * @see #addMapTool(String, Behavior[])
1777
         * @see #getMapToolsKeySet()
1778
         * @see #hasTool(String)
1779
         */
1780
        public HashMap getNamesMapTools() {
1781
                return namesMapTools;
1782
        }
1783

    
1784
        /*
1785
         * (non-Javadoc)
1786
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRepaint()
1787
         */
1788
        public void commandRepaint() {
1789
                drawMap(false);
1790
        }
1791

    
1792
        /*
1793
         * (non-Javadoc)
1794
         * @see com.iver.cit.gvsig.fmap.edition.commands.CommandListener#commandRefresh()
1795
         */
1796
        public void commandRefresh() {
1797
                // TODO Auto-generated method stub
1798
        }
1799

    
1800
        /**
1801
         * <p>Equivalent operation to <i>undo</i>.</p>
1802
         *
1803
         * <p>Exchanges the previous tool with the current one.</p>
1804
         *
1805
         * @see #addMapTool(String, Behavior)
1806
         * @see #addMapTool(String, Behavior[])
1807
         * @see #setTool(String)
1808
         */
1809
        public void setPrevTool() {
1810
                setTool(prevTool);
1811
        }
1812

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

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

    
1861
        /**
1862
         * <p>Returns the listener used to catch all mouse events produced in this <code>MapControl</code> instance
1863
         *  and that redirects the calls to the current map tool.</p>
1864
         *
1865
         * @return the map tool listener used
1866
         */
1867
        public MapToolListener getMapToolListener() {
1868
                return mapToolListener;
1869
        }
1870

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

    
1888
        /**
1889
         * <p>Sets the delay to the timer that refreshes this <code>MapControl</code> instance.</p>
1890
         *
1891
         * <p><code>Delay (in ms) = 1000 / getDrawFrameRate()</code></p>
1892
         *
1893
         * @see #getDrawFrameRate()
1894
         * @see #setDrawFrameRate(int)
1895
         */
1896
        public void applyFrameRate() {
1897
                if (MapContext.getDrawFrameRate()>0) {
1898
                        timer.setDelay(1000/MapContext.getDrawFrameRate());
1899
                }
1900
        }
1901

    
1902

    
1903

    
1904
        /**
1905
         * <p>Determines if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1906
         *
1907
         * @return <code>true</code> if its enabled; otherwise <code>false</code>
1908
         */
1909
        public static boolean isDrawAnimationEnabled() {
1910
                return drawAnimationEnabled;
1911
        }
1912

    
1913
        /**
1914
         * <p>Sets if its enabled the repaint that invokes the timer according to {@link #getDrawFrameRate() #getDrawFrameRate()}.</p>
1915
         *
1916
         * @param drawAnimationEnabled <code>true</code> to enable the mode; otherwise <code>false</code>
1917
         */
1918
        public static void setDrawAnimationEnabled(boolean drawAnimationEnabled) {
1919
                MapControl.drawAnimationEnabled = drawAnimationEnabled;
1920
        }
1921

    
1922
        /**
1923
         * <p>Gets the shared object that determines if a drawing process must be cancelled or can continue.</p>
1924
         *
1925
         * @return the shared object that determines if a drawing process must be cancelled or can continue
1926
         */
1927
        public CancelDraw getCanceldraw() {
1928
                return canceldraw;
1929
        }
1930

    
1931
        /**
1932
         * <p>Gets the tool used in combination with the current tool of this <code>MapControl</code>.</p>
1933
         *
1934
         * @return the tool used in combination with the <code>currentMapTool</code>; <code>null</code> if there is
1935
         *  no combined tool
1936
         */
1937
        public Behavior getCombinedTool() {
1938
                return combinedTool;
1939
        }
1940

    
1941
        /**
1942
         * <p>Sets a tool to be used in combination with the current tool of this <code>MapControl</code>.</p>
1943
         *
1944
         * @param combinedTool a tool to be used in combination with the current tool of <code>MapControl</code>
1945
         */
1946
        public void setCombinedTool(Behavior combinedTool) {
1947
                this.combinedTool = combinedTool;
1948

    
1949
                if (currentMapTool == null) {
1950
                        return;
1951
                }
1952

    
1953
                if (currentMapTool instanceof CompoundBehavior) {
1954
                        ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true);
1955
                }
1956
                else {
1957
                        currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool});
1958
                        ((CompoundBehavior)currentMapTool).addMapBehavior(combinedTool, true);
1959
                }
1960

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

    
1980
                                ((CompoundBehavior)combinedTool).addMapBehavior(tool, true);
1981
                        }
1982
                        else {
1983
                                if (combinedTool.equals(tool)) {
1984
                                        return;
1985
                                }
1986

    
1987
                                combinedTool = new CompoundBehavior(new Behavior[] {combinedTool});
1988
                                ((CompoundBehavior)combinedTool).addMapBehavior(tool, true);
1989
                        }
1990
                }
1991

    
1992
                if (currentMapTool == null) {
1993
                        return;
1994
                }
1995

    
1996
                if (currentMapTool instanceof CompoundBehavior) {
1997
                        ((CompoundBehavior)currentMapTool).addMapBehavior(tool, true);
1998
                }
1999
                else {
2000
                        currentMapTool = new CompoundBehavior(new Behavior[] {currentMapTool});
2001
                        ((CompoundBehavior)currentMapTool).addMapBehavior(tool, true);
2002
                }
2003
        }
2004
        /**
2005
         * <p>Removes the tool <code>tool</code> used in combination with the current tool of this <code>MapControl</code>.</p>
2006
         */
2007
        public void removeCombinedTool(Behavior tool) {
2008
                if ((currentMapTool != null) && (currentMapTool instanceof CompoundBehavior)) {
2009
                                ((CompoundBehavior)currentMapTool).removeMapBehavior(tool);
2010
                }
2011

    
2012
                if (combinedTool == null) {
2013
                        return;
2014
                }
2015

    
2016
                if (combinedTool instanceof CompoundBehavior) {
2017
                        ((CompoundBehavior)combinedTool).removeMapBehavior(tool);
2018
                }
2019
                else {
2020
                        combinedTool = null;
2021
                }
2022
        }
2023

    
2024

    
2025
        /**
2026
         * <p>Updates the grid on the <code>ViewPort</code> of the associated <code>MapControl</code>
2027
         *  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>
2028
         *
2029
         * <p>The preferences are:
2030
         *  <ul>
2031
         *   <li>Show/hide the grid.</li>
2032
         *   <li>Adjust or not the grid.</li>
2033
         *   <li>Horizontal ( X ) line separation.</li>
2034
         *   <li>Vertical ( Y ) line separation.</li>
2035
         *  </ul>
2036
         * </p>
2037
         */
2038
        public void initializeGrid(){
2039
                boolean showGrid = prefs.getBoolean("grid.showgrid",cadgrid.isShowGrid());
2040
                boolean adjustGrid = prefs.getBoolean("grid.adjustgrid",cadgrid.isAdjustGrid());
2041

    
2042
                double dx = prefs.getDouble("grid.distancex",cadgrid.getGridSizeX());
2043
                double dy = prefs.getDouble("grid.distancey",cadgrid.getGridSizeY());
2044

    
2045
                setGridVisibility(showGrid);
2046
                setAdjustGrid(adjustGrid);
2047
                cadgrid.setGridSizeX(dx);
2048
                cadgrid.setGridSizeY(dy);
2049
        }
2050

    
2051
        public void setAdjustGrid(boolean adjustGrid) {
2052
                cadgrid.setAdjustGrid(adjustGrid);
2053
        }
2054

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

    
2075

    
2076

    
2077
                g.setColor(Color.black);
2078
                Point2D p = adjustedPoint;
2079

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

    
2142
                setCursor(transparentCursor);
2143
        }
2144
        /**
2145
         * <p>Adjusts the <code>point</code> to the grid if its enabled, and
2146
         *  sets <code>mapHandlerAdjustedPoint</code> with that new value.</p>
2147
         *
2148
         * <p>The value returned is the distance between those points: the original and
2149
         *  the adjusted one.</p>
2150
         *
2151
         * @param point point to adjust
2152
         * @param mapHandlerAdjustedPoint <code>point</code> adjusted
2153
         *
2154
         * @return distance from <code>point</code> to the adjusted one. If there is no
2155
         *  adjustment, returns <code>Double.MAX_VALUE</code>.
2156
         */
2157

    
2158

    
2159
        private double adjustToHandler(Point2D point,
2160
            Point2D mapHandlerAdjustedPoint) {
2161

    
2162
        if (!isRefentEnabled())
2163
            return Double.MAX_VALUE;
2164

    
2165
        ArrayList snappers=new ArrayList(selected.keySet());
2166
        ArrayList layersToSnap = getMapContext().getLayersToSnap();
2167

    
2168
        double mapTolerance = vp.toMapDistance(MapControl.tolerance);
2169
        double minDist = mapTolerance;
2170
        double middleTol=mapTolerance * 0.5;
2171
        Point2D mapPoint = point;
2172
        org.gvsig.fmap.geom.primitive.Envelope r;
2173
                com.vividsolutions.jts.geom.Envelope e = null;
2174
                try {
2175
                        r = geomManager.createEnvelope(mapPoint.getX() - middleTol,
2176
                                        mapPoint.getY() - middleTol,
2177
                                        mapPoint.getX() + middleTol,
2178
                                        mapPoint.getY() + middleTol,
2179
                                        SUBTYPES.GEOM2D);
2180

    
2181
                        e = Converter.convertEnvelopeToJTS(r);
2182
                } catch (CreateEnvelopeException e1) {
2183
                        logger.error("Error creating the envelope", e1);
2184
                }
2185

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

    
2207
                        if (usedSnap != null)
2208
                        {
2209
                            // Si ya tenemos un snap y es de alta prioridad, cogemos ese. (A no ser que en otra capa encontremos un snapper mejor)
2210
                            if (theSnapper.getPriority() > usedSnap.getPriority())
2211
                                break;
2212
                        }
2213
//                        SnappingVisitor snapVisitor = null;
2214
                        Point2D theSnappedPoint = null;
2215
                        if (theSnapper instanceof ISnapperVectorial)
2216
                        {
2217
                            theSnappedPoint = ((ISnapperVectorial) theSnapper).getSnapPoint(point, geom, mapTolerance, lastPoint);
2218
                        }
2219
                        if (theSnapper instanceof ISnapperRaster)
2220
                        {
2221
                            ISnapperRaster snapRaster = (ISnapperRaster) theSnapper;
2222
                            theSnappedPoint = snapRaster.getSnapPoint(this, point, mapTolerance, lastPoint);
2223
                        }
2224

    
2225

    
2226
                        if (theSnappedPoint != null) {
2227
                            double distAux = theSnappedPoint.distance(point);
2228
                            if (minDist > distAux)
2229
                            {
2230
                                minDist = distAux;
2231
                                usedSnap = theSnapper;
2232
                                mapHandlerAdjustedPoint.setLocation(theSnappedPoint);
2233
                            }
2234
                        }
2235
                    }
2236
                } // for n
2237
            } // visible
2238
        }
2239
        if (usedSnap != null)
2240
            return minDist;
2241
        return Double.MAX_VALUE;
2242

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

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

    
2286
                Point2D gridAdjustedPoint = vp.toMapPoint(
2287
                                point);
2288
                double minDistance = Double.MAX_VALUE;
2289
//                CADTool ct = (CADTool) cadToolStack.peek();
2290
//                if (ct instanceof SelectionCADTool
2291
//                                && ((SelectionCADTool) ct).getStatus().equals(
2292
//                                                "Selection.FirstPoint")) {
2293
//                        mapAdjustedPoint = gridAdjustedPoint;
2294
//                        adjustedPoint = (Point2D) point.clone();
2295
//                } else {
2296

    
2297
                        minDistance = cadgrid.adjustToGrid(gridAdjustedPoint);
2298
                        if (minDistance < Double.MAX_VALUE) {
2299
                                adjustedPoint = vp.fromMapPoint(
2300
                                                gridAdjustedPoint);
2301
                                mapAdjustedPoint = gridAdjustedPoint;
2302
                        } else {
2303
                                mapAdjustedPoint = null;
2304
                        }
2305
//                }
2306
                Point2D handlerAdjustedPoint = null;
2307

    
2308
                // Se comprueba el ajuste a los handlers
2309
                if (mapAdjustedPoint != null) {
2310
                        handlerAdjustedPoint = (Point2D) mapAdjustedPoint.clone(); // getMapControl().getViewPort().toMapPoint(point);
2311
                } else {
2312
                        handlerAdjustedPoint = vp.toMapPoint(
2313
                                        point);
2314
                }
2315

    
2316
                Point2D mapPoint = new Point2D.Double();
2317
                double distance = adjustToHandler(handlerAdjustedPoint, mapPoint);
2318

    
2319
                if (distance < minDistance) {
2320
                        bForceCoord = true;
2321
                        adjustedPoint = vp.fromMapPoint(mapPoint);
2322
                        mapAdjustedPoint = mapPoint;
2323
                        minDistance = distance;
2324
                }
2325

    
2326
                // Si no hay ajuste
2327
                if (minDistance == Double.MAX_VALUE) {
2328
                        adjustedPoint = point;
2329
                        mapAdjustedPoint = null;
2330
                }
2331
                return mapAdjustedPoint;
2332
        }
2333
        /**
2334
         * Sets the snap tools enabled or disabled.
2335
         *
2336
         * @param activated <code>true</code> to enable the snap tools; <code>false</code> to disable them
2337
         *
2338
         * @see #isRefentEnabled()
2339
         */
2340
        public void setRefentEnabled(boolean activated) {
2341
                bRefent = activated;
2342
        }
2343

    
2344
        public Grid getGrid() {
2345
                return cadgrid;
2346
        }
2347

    
2348
        public static HashMap getSelectedSnapppers() {
2349
                return selected;
2350
        }
2351

    
2352
        public void update(Observable observable, Object notification) {
2353
                DataStoreNotification ddsn=(DataStoreNotification)notification;
2354
                String type=ddsn.getType();
2355
                if (type.equals(FeatureStoreNotification.AFTER_UNDO) ||
2356
                                type.equals(FeatureStoreNotification.AFTER_REDO)){
2357
                        repaint();
2358
                }
2359
        }
2360
}