Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.mapcontext / org.gvsig.fmap.mapcontext.api / src / main / java / org / gvsig / fmap / mapcontext / MapContext.java @ 44240

History | View | Annotate | Download (63.6 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.fmap.mapcontext;
24

    
25
import java.awt.Color;
26
import java.awt.Graphics;
27
import java.awt.Graphics2D;
28
import java.awt.geom.Rectangle2D;
29
import java.awt.image.BufferedImage;
30
import java.util.ArrayList;
31
import java.util.Iterator;
32
import java.util.LinkedHashMap;
33
import java.util.List;
34
import java.util.Map;
35
import org.apache.commons.lang3.ArrayUtils;
36

    
37
import org.cresques.cts.ICoordTrans;
38
import org.cresques.cts.IProjection;
39
import org.cresques.geo.Projected;
40
import org.slf4j.Logger;
41
import org.slf4j.LoggerFactory;
42

    
43
import org.gvsig.compat.CompatLocator;
44
import org.gvsig.compat.print.PrintAttributes;
45
import org.gvsig.fmap.dal.DataStore;
46
import org.gvsig.fmap.dal.exception.ReadException;
47
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
48
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
49
import org.gvsig.fmap.geom.GeometryLocator;
50
import org.gvsig.fmap.geom.GeometryManager;
51
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
52
import org.gvsig.fmap.geom.primitive.Envelope;
53
import org.gvsig.fmap.mapcontext.events.ErrorEvent;
54
import org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener;
55
import org.gvsig.fmap.mapcontext.events.listeners.ErrorListener;
56
import org.gvsig.fmap.mapcontext.events.listeners.EventBuffer;
57
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
58
import org.gvsig.fmap.mapcontext.impl.DefaultMapContextManager;
59
import org.gvsig.fmap.mapcontext.layers.BaseLayerCollectionListener;
60
import org.gvsig.fmap.mapcontext.layers.FLayer;
61
import org.gvsig.fmap.mapcontext.layers.FLayers;
62
import org.gvsig.fmap.mapcontext.layers.LayerCollectionEvent;
63
import org.gvsig.fmap.mapcontext.layers.LayerCollectionListener;
64
import org.gvsig.fmap.mapcontext.layers.LayerDrawEvent;
65
import org.gvsig.fmap.mapcontext.layers.LayerDrawingListener;
66
import org.gvsig.fmap.mapcontext.layers.LayerPositionEvent;
67
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
68
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
69
import org.gvsig.fmap.mapcontext.layers.order.LayerOrderManager;
70
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
71
import org.gvsig.fmap.mapcontext.layers.vectorial.GraphicLayer;
72
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
73
import org.gvsig.fmap.mapcontext.rendering.strategies.SelectedEnvelopeVisitor;
74
import org.gvsig.timesupport.AbsoluteInstant;
75
import org.gvsig.timesupport.AbsoluteIntervalTypeNotRegisteredException;
76
import org.gvsig.timesupport.Instant;
77
import org.gvsig.timesupport.Interval;
78
import org.gvsig.timesupport.RelativeInstant;
79
import org.gvsig.timesupport.TimeSupportLocator;
80
import org.gvsig.timesupport.TimeSupportManager;
81
import org.gvsig.tools.ToolsLocator;
82
import org.gvsig.tools.dispose.impl.AbstractDisposable;
83
import org.gvsig.tools.dynobject.DynStruct;
84
import org.gvsig.tools.exception.BaseException;
85
import org.gvsig.tools.observer.Observable;
86
import org.gvsig.tools.observer.Observer;
87
import org.gvsig.tools.persistence.PersistenceManager;
88
import org.gvsig.tools.persistence.Persistent;
89
import org.gvsig.tools.persistence.PersistentState;
90
import org.gvsig.tools.persistence.exception.PersistenceException;
91
import org.gvsig.tools.task.Cancellable;
92
import org.gvsig.tools.util.Callable;
93
import org.gvsig.tools.visitor.Visitor;
94

    
95
/**
96
 * <p>
97
 * The <code>MapContext</code> class represents the model and a part of the
98
 * control and view around graphical layers used by
99
 * {@link MapControl MapControl}.</p>
100
 *
101
 * <p>
102
 * An instance of <code>MapContext</code> is made up with:
103
 * <ul>
104
 * <li>a hierarchy of {@link FLayers FLayers} nodes
105
 * <li>a {@link GraphicLayer GraphicLayer} layer
106
 * <li>a {@link ViewPort ViewPort}
107
 * <li>an {@link EventBuffer EventButter}
108
 * <li>some
109
 * {@link com.iver.cit.gvsig.fmap.layers.LegendListener LegendListener}s
110
 * <li>some {@link LayerDrawingListener LayerDrawingListener}s
111
 * <li>some {@link ErrorListener ErrorListener}s
112
 * </ul>
113
 * </p>
114
 */
115
public class MapContext extends AbstractDisposable implements Projected,
116
        Persistent, Observer, Iterable<FLayer> {
117

    
118
    public interface MapTimeContext {
119
        public Interval getInterval();
120
        public List<Instant> getTimes();
121
    }    
122

    
123
    /**
124
     * @deprecated use getDistanceTrans2Meter()
125
     */
126
    public static final double[] CHANGEM = {1000, 1, 0.01, 0.001, 1609.344,
127
        0.9144, 0.3048, 0.0254, 1 / 8.983152841195214E-6};
128

    
129
    public static ArrayList AREANAMES = new ArrayList();
130
    public static ArrayList AREAABBR = new ArrayList();
131
    public static ArrayList AREATRANS2METER = new ArrayList();
132

    
133
    public static ArrayList DISTANCENAMES = new ArrayList();
134
    public static ArrayList DISTANCEABBR = new ArrayList();
135
    public static ArrayList DISTANCETRANS2METER = new ArrayList();
136

    
137
    static {
138
        MapContext.addDistanceUnit("Kilometros", "Km", 1000);
139
        MapContext.addDistanceUnit("Metros", "m", 1);
140
        MapContext.addDistanceUnit("Centimetros", "cm", 0.01);
141
        MapContext.addDistanceUnit("Milimetros", "mm", 0.001);
142
        MapContext.addDistanceUnit("Millas", "mi", 1609.344);
143
        MapContext.addDistanceUnit("Yardas", "Ya", 0.9144);
144
        MapContext.addDistanceUnit("Pies", "ft", 0.3048);
145
        MapContext.addDistanceUnit("Pulgadas", "inche", 0.0254);
146
        MapContext.addDistanceUnit("Grados", "?", 1 / 8.983152841195214E-6);
147

    
148
        MapContext.addAreaUnit("Kilometros", "Km", true, 1000);
149
        MapContext.addAreaUnit("Metros", "m", true, 1);
150
        MapContext.addAreaUnit("Centimetros", "cm", true, 0.01);
151
        MapContext.addAreaUnit("Milimetros", "mm", true, 0.001);
152
        MapContext.addAreaUnit("Millas", "mi", true, 1609.344);
153
        MapContext.addAreaUnit("Yardas", "Ya", true, 0.9144);
154
        MapContext.addAreaUnit("Pies", "ft", true, 0.3048);
155
        MapContext.addAreaUnit("Pulgadas", "inche", true, 0.0254);
156
        MapContext.addAreaUnit("Grados", "?", true, 1 / 8.983152841195214E-6);
157

    
158
    }
159

    
160
    private static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
161

    
162
    private static final MapContextManager mapContextManager = MapContextLocator
163
            .getMapContextManager();
164

    
165
    private static final Logger logger = LoggerFactory.getLogger(MapContext.class);
166

    
167
    /**
168
     * <p>
169
     * Determines the number of frames.</p>
170
     *
171
     * <p>
172
     * Number of updates per second that the timer will invoke repaint this
173
     * component.</p>
174
     */
175
    private static int drawFrameRate = 3;
176

    
177
    /**
178
     * <p>
179
     * Returns the draw frame rate.</p>
180
     *
181
     * <p>
182
     * Draw frame rate is the number of repaints of this <code>MapControl</code>
183
     * instance that timer invokes per second.</p>
184
     *
185
     * @return number of repaints of this <code>MapControl</code> instance that
186
     * timer invokes per second
187
     *
188
     * @see #applyFrameRate()
189
     * @see #setDrawFrameRate(int)
190
     */
191
    public static int getDrawFrameRate() {
192
        return drawFrameRate;
193
    }
194

    
195
    /**
196
     * <p>
197
     * Sets the draw frame rate.</p>
198
     *
199
     * <p>
200
     * Draw frame rate is the number of repaints of this <code>MapControl</code>
201
     * instance that timer invokes per second.</p>
202
     *
203
     * @param drawFrameRate number of repaints of this <code>MapControl</code>
204
     * instance that timer invokes per second
205
     *
206
     * @see #applyFrameRate()
207
     * @see #getDrawFrameRate()
208
     */
209
    public static void setDrawFrameRate(int dFR) {
210
        drawFrameRate = dFR;
211
    }
212

    
213
    public static void addAreaUnit(String name, String abbr, boolean isLinear, double trans2meter) {
214
        if (!AREANAMES.contains(name)) {
215
            AREANAMES.add(name);
216
            String pow = "";
217
            if (isLinear) {
218
                pow = String.valueOf((char) 178);
219
            }
220
            AREAABBR.add(abbr + pow);
221
            AREATRANS2METER.add(new Double(trans2meter));
222
        }
223
    }
224

    
225
    public static String[] getAreaNames() {
226
        return (String[]) AREANAMES.toArray(new String[0]);
227
    }
228

    
229
    public static String[] getAreaAbbr() {
230
        return (String[]) AREAABBR.toArray(new String[0]);
231
    }
232

    
233
    public static double[] getAreaTrans2Meter() {
234
        int size = AREATRANS2METER.size();
235
        double[] trans2meters = new double[size];
236
        for (int i = 0; i < size; i++) {
237
            trans2meters[i] = ((Double) AREATRANS2METER.get(i)).doubleValue();
238
        }
239
        return trans2meters;
240
    }
241

    
242
    public static String getOfLinear(int i) {
243
        if (((String) AREAABBR.get(i)).toLowerCase().endsWith(String.valueOf((char) 178))) {
244
            return String.valueOf((char) 178);
245
        }
246
        return "";
247
    }
248

    
249
    public static void addDistanceUnit(String name, String abbr, double trans2meter) {
250
        if (!DISTANCENAMES.contains(name)) {
251
            DISTANCENAMES.add(name);
252
            DISTANCEABBR.add(abbr);
253
            DISTANCETRANS2METER.add(new Double(trans2meter));
254
        }
255
    }
256

    
257
    public static String[] getDistanceNames() {
258
        return (String[]) DISTANCENAMES.toArray(new String[0]);
259
    }
260

    
261
    public String getDistanceName() {
262
        return (String) DISTANCENAMES.get(this.getViewPort().getDistanceUnits());
263
    }
264

    
265
    public static String[] getDistanceAbbr() {
266
        return (String[]) DISTANCEABBR.toArray(new String[0]);
267
    }
268

    
269
    public static double[] getDistanceTrans2Meter() {
270
        int size = DISTANCETRANS2METER.size();
271
        double[] trans2meters = new double[size];
272
        for (int i = 0; i < size; i++) {
273
            trans2meters[i] = ((Double) DISTANCETRANS2METER.get(i)).doubleValue();
274
        }
275
        return trans2meters;
276
    }
277

    
278
    public static int getDistancePosition(String s) {
279
        for (int i = 0; i < DISTANCENAMES.size(); i++) {
280
            if (DISTANCENAMES.get(i).equals(s)) {
281
                return i;
282
            }
283
        }
284
        return 0;
285
    }
286

    
287
    /**
288
     * <p>
289
     * Defines the value which a unit of a distance measurement must be divided
290
     * to obtain its equivalent <b>in centimeters</b>.</p>
291
     *
292
     * <p>
293
     * <b><i>Conversion values of distance measurements:</i></b>
294
     * <ul>
295
     * <li><code>MapContext.CHANGE[0]</code>: kilometer
296
     * <li><code>MapContext.CHANGE[1]</code>: meter
297
     * <li><code>MapContext.CHANGE[2]</code>: centimeter
298
     * <li><code>MapContext.CHANGE[3]</code>: millimeter
299
     * <li><code>MapContext.CHANGE[4]</code>: international statute mile
300
     * <li><code>MapContext.CHANGE[5]</code>: yard
301
     * <li><code>MapContext.CHANGE[6]</code>: foot
302
     * <li><code>MapContext.CHANGE[7]</code>: inch
303
     * <li><code>MapContext.CHANGE[8]</code>: grade
304
     * </ul>
305
     *
306
     * <p>
307
     * <h3>Examples:</h3>
308
     * <pre>1 international statute mile / MapContext.CHANGE[4] = X centimeters</pre>
309
     * <pre>1 kilometer / MapContext.CHANGE[0] = X centimeters</pre>
310
     * <pre>1 grade / MapContext.CHANGE[8] = X centimeters</pre>
311
     * </p>
312
     *
313
     * <p>
314
     * <h3>Grade conversion value: <code>MapContext.CHANGE[8]</code></h3>
315
     * The value of <code>MapContext.CHANGE[8]</code> represents the centimeters
316
     * of a straight line between two points on the Earth surface that are 1
317
     * grade far each other of the center of the Earth. This value has been
318
     * calculated using a radius approximated of
319
     * R<sub>Earth</sub>=6.37846082678100774672e6 meters, according these
320
     * equations:
321
     * <pre>D = 2 * (sin (1)) * R<sub>Earth</sub></pre>
322
     * <pre>MapContext.CHANGE[8] = 1 / D</pre>
323
     * <h4>Explanation:</h4>
324
     * We get an isosceles triangle with the center of the Earth and the 2
325
     * points on the surface. This triangle can be divided into two rectangle
326
     * triangles. We know two values, the angle of 1 grade, that will be 0.50
327
     * grades in each triangle, and the Earth radius that is the hypotenuse.
328
     * Then we apply trigonometry and get the distance <i>D</i> between both
329
     * points on the Earth surface.</p>
330
     * <p>
331
     * Now we only must invert that value to obtain
332
     * <code>MapContext.CHANGE[8]</code>.</p>
333
     *
334
     * @deprecated use getDistanceTrans2Meter() * 100
335
     */
336
    public static final double[] CHANGE = {100000, 100, 1, 0.1, 160934.4,
337
        91.44, 30.48, 2.54, 1 / 8.983152841195214E-4};
338

    
339
    /* Do not alter the order and the values of this array, if you need append values.*/
340
    /**
341
     * <p>
342
     * Gets the name of all distance measurements supported by
343
     * <code>MapContext</code>.</p>
344
     */
345
//        public static final String[] NAMES= {
346
//                Messages.getString("Kilometros"),
347
//                Messages.getString("Metros"),
348
//                Messages.getString("Centimetros"),
349
//                Messages.getString("Milimetros"),
350
//                Messages.getString("Millas"),
351
//                Messages.getString("Yardas"),
352
//                Messages.getString("Pies"),
353
//                Messages.getString("Pulgadas"),
354
//                Messages.getString("Grados"),
355
//        };
356
    public static final int EQUALS = 0;
357

    
358
    public static final int DISJOINT = 1;
359

    
360
    public static final int INTERSECTS = 2;
361

    
362
    public static final int TOUCHES = 3;
363

    
364
    public static final int CROSSES = 4;
365

    
366
    public static final int WITHIN = 5;
367

    
368
    public static final int CONTAINS = 6;
369

    
370
    public static final int OVERLAPS = 7;
371

    
372
    /**
373
     * A hierarchy of {@link FLayers FLayers} nodes.
374
     *
375
     * @see #getLayers()
376
     * @see #print(Graphics2D, double, PrintAttributes)
377
     */
378
    protected FLayers layers;
379

    
380
    /**
381
     * A layer with graphical items: geometries and symbols.
382
     *
383
     * @see #getGraphicsLayer()
384
     * @see #setGraphicsLayer(GraphicLayer)
385
     * @see #print(Graphics2D, double, PrintAttributes)
386
     */
387
//    private GraphicLayer tracLayer = null;
388
    private static final String DEFAULT_TRACTLAYER = "Default";
389
    private Map<String, GraphicLayer> tracLayers;
390
    //MapContextLocator.getMapContextManager().createGraphicsLayer(getProjection());
391

    
392
    /**
393
     * Information for draw layers in a view.
394
     *
395
     * @see #getViewPort()
396
     * @see #setViewPort(ViewPort)
397
     */
398
    private ViewPort viewPort;
399

    
400
        // private ArrayList invalidationListeners = new ArrayList();
401
    /**
402
     * Array list with all {@link LegendListener LegendListener} registered to
403
     * this map.
404
     *
405
     * @see #addLayerListener(LegendListener)
406
     * @see #removeLayerListener(LegendListener)
407
     * @see #callLegendChanged()
408
     */
409
    private ArrayList legendListeners = new ArrayList();
410

    
411
    /**
412
     * Array list with all {@link LayerDrawingListener LayerDrawingListener}
413
     * registered to this map.
414
     *
415
     * @see #addLayerDrawingListener(LayerDrawingListener)
416
     * @see #removeLayerDrawListener(LayerDrawingListener)
417
     * @see #fireLayerDrawingEvent(LayerDrawEvent)
418
     */
419
    private ArrayList layerDrawingListeners = new ArrayList();
420

    
421
    /**
422
     * <p>
423
     * Buffer that is used to store and eject events produced on this map:
424
     * <ul>
425
     * <li>Layer collection events.
426
     * <li>View port events.
427
     * <li>Atomic events.
428
     * <li>Layer events.
429
     * <li>Legend events on a {@link Classificable Classificable} layer.
430
     * <li>Selection events on an {@link AlphanumericData AlphanumericData} data
431
     * layer.
432
     * </ul>
433
     * </p>
434
     *
435
     * @see #addAtomicEventListener(AtomicEventListener)
436
     * @see #removeAtomicEventListener(AtomicEventListener)
437
     * @see #beginAtomicEvent()
438
     * @see #endAtomicEvent()
439
     */
440
    private EventBuffer eventBuffer = new EventBuffer();
441

    
442
    /**
443
     * Event listener for the collection of layers of this map.
444
     */
445
    private LayerEventListener layerEventListener = null;
446

    
447
    /**
448
     * List with information of all errors produced on all layers.
449
     *
450
     * @see #addLayerError(String)
451
     * @see #getLayersError()
452
     * @see #clearErrors()
453
     */
454
    private ArrayList layersError = new ArrayList();
455

    
456
    /**
457
     * Array list with all {@link ErrorListener ErrorListener} registered to
458
     * this map.
459
     *
460
     * @see #addErrorListener(ErrorListener)
461
     * @see #removeErrorListener(LegendListener)
462
     * @see #reportDriverExceptions(String, List)
463
     */
464
    private ArrayList errorListeners = new ArrayList();
465

    
466
    /**
467
     * Layer order manager decides position of layers added to this map context.
468
     */
469
    private LayerOrderManager orderManager = null;
470

    
471
        // public static ResourceBundle myResourceBundle =
472
    // ResourceBundle.getBundle("FMap");
473
    /**
474
     * <p>
475
     * Default <i>zoom in</i> factor.</p>
476
     * <p>
477
     * Doing a <i>zoom in</i> operation, decreases the focal distance and
478
     * increases the eyesight angle to the surface. This allows view an smaller
479
     * area but with the items bigger.</p>
480
     */
481
    public static double ZOOMINFACTOR = 2;
482

    
483
    /**
484
     * <p>
485
     * Default <i>zoom out</i> factor.</p>
486
     * <p>
487
     * Doing a <i>zoom out</i> operation, increases the focal distance and
488
     * decreases the eyesight angle to the surface. This allows view a bigger
489
     * area but with the items smaller.</p>
490
     */
491
    public static double ZOOMOUTFACTOR = 0.5;
492

    
493
    /**
494
     *          * Draw version of the context. It's used for know when de componend has
495
     * changed any visualization property
496
     *
497
     * @see getDrawVersion
498
     * @see updateDrawVersion
499
     */
500
    private long drawVersion = 0L;
501

    
502
    private long layersVersion = 0L;
503
    private long viewPortVersion = 0L;
504
    private long graphicsLayerVersion = 0L;
505

    
506
    /**
507
     * Object to Manage Draw of MapContext
508
     */
509
    private MapContextDrawer mapContextDrawer = null;
510

    
511
    /**
512
     * Object to Manage Draw of MapContext
513
     */
514
    private Class mapContextDrawerClass = null;
515

    
516
    /**
517
     * <p>
518
     * Color used to represent the selections.</p>
519
     */
520
    private static Color selectionColor = Color.YELLOW;
521
    private ArrayList layersToSnap = new ArrayList();
522

    
523
    /**
524
     * <p>
525
     * Gets the color used to represent the selections.</p>
526
     *
527
     * @return color used to represent the selections
528
     */
529
    public static Color getSelectionColor() {
530
        return selectionColor;
531
    }
532

    
533
    /**
534
     * <p>
535
     * Sets the color used to represent the selections.</p>
536
     *
537
     * @param selectionColor color used to represent the selections
538
     */
539
    public static void setSelectionColor(Color selectionColor) {
540
        MapContext.selectionColor = selectionColor;
541
    }
542

    
543
    /**
544
     * <p>
545
     * Creates a new map context with the drawing information defined in the
546
     * view port argument, and without layers.</p>
547
     *
548
     * @param vp information for drawing the layers of this map in the available
549
     * rectangular area according a projection
550
     */
551
    public MapContext(ViewPort vp) {
552
        this(new FLayers(), vp);
553
    }
554

    
555
    public MapContext() {
556
        this.tracLayers = new LinkedHashMap<>();
557
        layerEventListener = new LayerEventListener();
558
    }
559

    
560
    /**
561
     * <p>
562
     * Creates a new map context with the layers and the drawing information
563
     * defined in the view port arguments.</p>
564
     *
565
     * @param fLayers the initial hierarchy of nodes of layers that this map
566
     * will have
567
     * @param vp information for drawing the layers of this map in the available
568
     * rectangular area according a projection
569
     */
570
    public MapContext(FLayers fLayers, ViewPort vp) {
571
        this();
572
        this.layers = fLayers;
573
        if (layers != null) {
574
            layers.setMapContext(this);
575
            layers.addLayerCollectionListener(layerEventListener);
576
            layers.addLayerCollectionListener(eventBuffer);
577
        }
578
        setViewPort(vp);
579
    }
580

    
581
    /**
582
     * <p>
583
     * Reports to all driver error listeners registered of a bundle of driver
584
     * exceptions caused in the same map atomic transaction.</p>
585
     *
586
     * @param introductoryText introductory text specified by developer. If
587
     * <code>null</code>, use ""
588
     * @param driverExceptions list with a bundle of driver exceptions caught
589
     * during an atomic event
590
     *
591
     * @see #addErrorListener(ErrorListener)
592
     * @see #removeErrorListener(LegendListener)
593
     */
594
    public synchronized void reportDriverExceptions(String introductoryText,
595
            List driverExceptions) {
596
        for (int i = 0; i < errorListeners.size(); i++) {
597
            ((ErrorListener) errorListeners.get(i)).
598
                    reportDriverExceptions(introductoryText, driverExceptions);
599
        }
600
    }
601

    
602
    /**
603
     * <p>
604
     * Adds the specified legend listener (if didn't exist) to receive legend
605
     * events from this map.</p>
606
     *
607
     * @param listener the legend listener
608
     *
609
     * @see #removeLayerListener(LegendListener)
610
     * @see #callLegendChanged()
611
     */
612
    public void addLayerListener(LegendListener listener) {
613
        if (!legendListeners.contains(listener)) {
614
            legendListeners.add(listener);
615
        }
616
    }
617
        // SUGERENCIA DE PABLO
618
    //        public void addLegendListener(LegendListener listener) {
619
    //                if (!legendListeners.contains(listener))
620
    //                        legendListeners.add(listener);
621
    //        }
622

    
623
    /**
624
     * <p>
625
     * Adds the specified layer drawing listener to catch and handle drawing
626
     * events from layers of this map.</p>
627
     *
628
     * @param listener the listener to add
629
     *
630
     * @see #removeLayerDrawListener(LayerDrawingListener)
631
     * @see #fireLayerDrawingEvent(LayerDrawEvent)
632
     */
633
    public void addLayerDrawingListener(LayerDrawingListener listener) {
634
        layerDrawingListeners.add(listener);
635
    }
636

    
637
    /**
638
     * <p>
639
     * Removes the specified layer drawing listener from this map.</p>
640
     *
641
     * @param listener the listener to remove
642
     *
643
     * @see #addLayerDrawingListener(LayerDrawingListener)
644
     * @see #fireLayerDrawingEvent(LayerDrawEvent)
645
     */
646
    public void removeLayerDrawListener(LayerDrawingListener listener) {
647
        layerDrawingListeners.remove(listener);
648
    }
649

    
650
    /**
651
     * <p>
652
     * Adds the specified error listener to receive error events from this
653
     * map.</p>
654
     *
655
     * @param listener the listener to add
656
     *
657
     * @see #removeErrorListener(LegendListener)
658
     * @see #reportDriverExceptions(String, List)
659
     */
660
    public void addErrorListener(ErrorListener listener) {
661
        errorListeners.add(listener);
662
    }
663

    
664
    /**
665
     * <p>
666
     * Removes the specified error listener from this map.</p>
667
     *
668
     * @param listener the listener to remove
669
     *
670
     * @see #addErrorListener(ErrorListener)
671
     * @see #reportDriverExceptions(String, List)
672
     */
673
    public void removeErrorListener(LegendListener listener) {
674
        legendListeners.remove(listener);
675
    }
676

    
677
        // SUGERENCIA DE PABLO:
678
    //public void removeErrorListener(ErrorListener listener) {
679
    //        errorListeners.remove(listener);
680
    //}
681
    /**
682
     * <p>
683
     * Notifies to all legend listeners registered, that one legend has
684
     * changed.</p>
685
     * <p>
686
     * This method must be called only if it's wanted to reflect a legend
687
     * change.</p>
688
     *
689
     * @see #addLayerListener(LegendListener)
690
     * @see #removeLayerListener(LegendListener)
691
     */
692
    public synchronized void callLegendChanged() {
693
        for (int i = 0; i < legendListeners.size(); i++) {
694
            ((LegendListener) legendListeners.get(i)).legendChanged(null);
695
        }
696
        // getLayers().moveTo(0,0);
697
    }
698

    
699
    /**
700
     * <p>
701
     * Fires a layer drawing event to all
702
     * {@link LayerDrawingListener LayerDrawingListener} listeners registered,
703
     * distinguishing the kind of event.</p>
704
     *
705
     * @param e the event
706
     *
707
     * @see #addLayerDrawingListener(LayerDrawingListener)
708
     * @see #removeLayerDrawListener(LayerDrawingListener)
709
     */
710
    public synchronized void fireLayerDrawingEvent(LayerDrawEvent e) {
711
        for (int i = 0; i < layerDrawingListeners.size(); i++) {
712
            LayerDrawingListener listener = (LayerDrawingListener) layerDrawingListeners.get(i);
713
            switch (e.getEventType()) {
714
                case LayerDrawEvent.LAYER_BEFORE_DRAW:
715
                    listener.beforeLayerDraw(e);
716
                    break;
717
                case LayerDrawEvent.LAYER_AFTER_DRAW:
718
                    listener.afterLayerDraw(e);
719
                    break;
720
                case LayerDrawEvent.GRAPHICLAYER_BEFORE_DRAW:
721
                    listener.beforeGraphicLayerDraw(e);
722
                    break;
723
                case LayerDrawEvent.GRAPHICLAYER_AFTER_DRAW:
724
                    listener.afterLayerGraphicDraw(e);
725
                    break;
726
            }
727
        }
728
        // getLayers().moveTo(0,0);
729
    }
730

    
731
    /**
732
     * <p>
733
     * Notifies to all error listeners registered, that one error has been
734
     * produced.</p>
735
     *
736
     * @param e the event with information of the error
737
     *
738
     * @see #addErrorListener(ErrorListener)
739
     * @see #removeErrorListener(LegendListener)
740
     * @see #reportDriverExceptions(String, List)
741
     */
742
    public synchronized void callNewErrorEvent(ErrorEvent e) {
743
        for (int i = 0; i < errorListeners.size(); i++) {
744
            ((ErrorListener) errorListeners.get(i)).errorThrown(e);
745
        }
746
        errorListeners.clear();
747
        // getLayers().moveTo(0,0);
748
    }
749

    
750
    /**
751
     * <p>
752
     * Removes the specified layer listener from this map.</p>
753
     *
754
     * @param listener the listener to remove
755
     *
756
     * @see #addLayerListener(LegendListener)
757
     * @see #callLegendChanged()
758
     */
759
    public void removeLayerListener(LegendListener listener) {
760
        legendListeners.remove(listener);
761
    }
762

    
763
        // SUGERENCIA DE PABLO:
764
    // public void removeLegendListener(LegendListener listener) {
765
    //         legendListeners.remove(listener);
766
    // }
767
    /**
768
     * <p>
769
     * Returns the hierarchy of {@link FLayers FLayers} nodes stored in this
770
     * map.</p>
771
     *
772
     * @return the hierarchy of nodes of layers stored in this map
773
     */
774
    public FLayers getLayers() {
775
        return layers;
776
    }
777

    
778
    /**
779
     * <p>
780
     * Draws the visible layers of this map according its view port, on the
781
     * image parameter.</p>
782
     *
783
     * @param b image with an accessible buffer of image data
784
     */
785
    public void drawLabels(BufferedImage b) {
786
    }
787

    
788
    /**
789
     * @see #redraw()
790
     */
791
    public void invalidate() {
792
        updateDrawVersion();
793
        // Small hack to let the MapControl receive an event and repaint
794
        FLayer layer;
795
        if (layers.getLayersCount() > 0) {
796
            layer = layers.getLayer(layers.getLayersCount() - 1);
797
        } else {
798
            layer = getGraphicsLayer();
799
        }
800
        LayerPositionEvent layerMovedEvent = LayerPositionEvent
801
                .createLayerMovedEvent(
802
                        layer, 0, 0);
803
        eventBuffer.layerMoved(layerMovedEvent);
804
    }
805

    
806
    /**
807
     * <p>
808
     * Prints the layers of this map using the {@link Graphics2D Graphics2D}
809
     * argument, that usually is the {@link Graphics Graphics} of the printer.
810
     * </p>
811
     *
812
     * @param g for rendering 2-dimensional shapes, text and images on the
813
     * Java(tm) platform
814
     * @param scale the scale of the view. Must be between
815
     * {@linkplain FLayer#getMinScale()} and {@linkplain FLayer#getMaxScale()}.
816
     * @param properties a set with the settings to be applied to a whole print
817
     * job and to all the documents in the print job
818
     * @throws MapContextException if there is an error getting the instance of
819
     * MapContextDrawer
820
     *
821
     * @throws ReadDriverException if fails reading with driver.
822
     *
823
     * @see GraphicLayer#draw(BufferedImage, Graphics2D, ViewPort, Cancellable,
824
     * double)
825
     */
826
    public void print(Graphics2D g, double scale,
827
            PrintAttributes properties) throws ReadException,
828
            MapContextException {
829

    
830
        CompatLocator.getGraphicsUtils().setRenderingHintsForPrinting(g);
831

    
832
        Cancellable cancel = new Cancellable() {
833
            public boolean isCanceled() {
834
                return false;
835
            }
836

    
837
            public void setCanceled(boolean canceled) {
838
                // No queremos que se pueda cancelar la impresi?n.
839

    
840
            }
841
        };
842
        this.getMapContextDrawer().print(this.layers, g, cancel, scale, properties);
843
        for (GraphicLayer tracLayer : this.tracLayers.values()) {
844
            if (tracLayer != null) {
845
                tracLayer.draw(null, g, viewPort, cancel, scale);
846
            }
847
        }
848
    }
849

    
850
    /**
851
     * <p>
852
     * Returns a new <code>MapContext</code> instance with the information of
853
     * the <code>vp</code> argument, and the layers of this map.</p>
854
     *
855
     * @param vp information for drawing the layers of this map in the available
856
     * rectangular area according a projection
857
     *
858
     * @return a new <code>MapContext</code> instance projected by
859
     * <code>vp</code>
860
     */
861
    public MapContext createNewFMap(ViewPort vp) {
862
        MapContext ret = new MapContext(vp);
863
        ret.layers = this.layers;
864

    
865
        return ret;
866
    }
867

    
868
    /**
869
     * <p>
870
     * Creates a new independent <code>MapContext</code> instance, that has a
871
     * clone of the layers and the view port of this one.</p>
872
     * <p>
873
     * The new map will have the same data source drivers to avoid waste memory,
874
     * and work faster.</p>
875
     *
876
     * @return the new <code>MapContext</code> instance
877
     *
878
     * @throws XMLException if fails cloning the view port or a layer
879
     *
880
     * @see FLayer#cloneLayer()
881
     * @see ViewPort#cloneViewPort()
882
     */
883
    public MapContext cloneFMap() {
884
        ViewPort vp;
885
        try {
886
            vp = (ViewPort) getViewPort().clone();
887
        } catch (CloneNotSupportedException e) {
888
            throw new RuntimeException(e);
889
        }
890
        FLayers antLayers = getLayers();
891
        MapContext ret = new MapContext(vp);
892

    
893
        /*
894
         * Cloning order manager
895
         */
896
        LayerOrderManager lom = this.getOrderManager();
897
        try {
898
            lom = (LayerOrderManager) lom.clone();
899
            ret.setOrderManager(lom);
900
        } catch (CloneNotSupportedException e1) {
901
            logger.error("While cloning order manager", e1);
902
        }
903

    
904
        FLayers aux = new FLayers();//(ret,null);
905
        aux.setMapContext(ret);
906
        for (int i = 0; i < antLayers.getLayersCount(); i++) {
907
            FLayer lyr = antLayers.getLayer(i);
908
            try {
909
                FLayer auxLayer = lyr.cloneLayer();
910
                aux.addLayer(auxLayer);
911
                auxLayer.dispose();
912
            } catch (Exception e) {
913
                throw new RuntimeException(e);
914
            }
915
        }
916
        ret.layers = aux;
917
        return ret;
918

    
919
    }
920

    
921
    /**
922
     * Like {@linkplain #cloneFMap()}, but now doesn't clone the layers, rather
923
     * copies them.
924
     *
925
     * @return the new map
926
     */
927
    public MapContext cloneToDraw() {
928
        ViewPort vp;
929
        try {
930
            vp = (ViewPort) getViewPort().clone();
931
            MapContext mapContext = new MapContext(getLayers(), vp);
932
            return mapContext;
933
        } catch (CloneNotSupportedException e) {
934
            throw new RuntimeException(e);
935
        }
936
    }
937

    
938
    /**
939
     * <p>
940
     * Adds a layer to the group of layers that are at a upper level in the
941
     * tree.</p>
942
     *
943
     * @param vectorial the layer to add
944
     */
945
    public void addToTrackLayer(FLayer vectorial) {
946
    }
947

    
948
    /**
949
     * <p>
950
     * Returns the scale of the view in the screen.</p>
951
     *
952
     * @return one of this values:
953
     * <ul>
954
     * <li>the scale of the adjusted extent scale of the view in the screen
955
     * <li><code>-1</code> if there is no image
956
     * <li><code>0</code> if there is no extent defined for the image
957
     * </ul>
958
     *
959
     * @see #setScaleView(long)
960
     * @see ViewPort#getAdjustedExtent()
961
     * @see IProjection#getScale(double, double, double, double)
962
     */
963
    public long getScaleView() {
964
        double dpi = this.getViewPort().getDPI();
965
        IProjection proj = viewPort.getProjection();
966

    
967
        if (viewPort.getImageSize() == null) {
968
            return -1;
969
        }
970

    
971
        if (viewPort.getAdjustedEnvelope() == null) {
972
            return 0;
973
        }
974
        double[] trans2Meter = getDistanceTrans2Meter();
975
        int mUnits = getViewPort().getMapUnits();
976

    
977
        if (proj == null) {
978
            double w = ((viewPort.getImageSize().width / dpi) * 0.0254);
979
            return (long) (viewPort.getAdjustedEnvelope().getLength(0)
980
                    / w * trans2Meter[mUnits]);
981
        }
982

    
983
        return Math.round(proj.getScale(
984
                viewPort.getAdjustedEnvelope().getMinimum(0) * trans2Meter[mUnits],
985
                viewPort.getAdjustedEnvelope().getMaximum(0) * trans2Meter[mUnits],
986
                viewPort.getImageSize().width,
987
                dpi));
988

    
989
    }
990

    
991
    /**
992
     * <p>
993
     * Sets the new extent of the view, calculated using the scale argument.</p>
994
     * <p>
995
     * Doesn't updates the scale if there isn't information about the dimension
996
     * of the image or the adjusted extent.</p>
997
     *
998
     * @param scale the new scale for the view
999
     *
1000
     * @see ViewPort#setProjection(IProjection)
1001
     * @see #getScaleView()
1002
     */
1003
    public void setScaleView(long scale) {
1004
        double dpi = this.getViewPort().getDPI();
1005
        if (viewPort.getImageSize() == null) {
1006
            return;
1007
        }
1008
        IProjection proj = viewPort.getProjection();
1009
        if (viewPort.getAdjustedExtent() == null) {
1010
            return;
1011
        }
1012
        double[] trans2Meter = getDistanceTrans2Meter();
1013
        Envelope env = viewPort.getAdjustedExtent();
1014
        Rectangle2D r = new Rectangle2D.Double(env.getMinimum(0), env.getMinimum(1), env.getLength(0), env.getLength(1));
1015
        Rectangle2D rec = proj.getExtent(r, scale, viewPort.getImageWidth(), viewPort.getImageHeight(), 100 * getDistanceTrans2Meter()[getViewPort().getMapUnits()], trans2Meter[getViewPort().getDistanceUnits()], dpi);
1016
        try {
1017
            getViewPort().setEnvelope(geomManager.createEnvelope(rec.getX(), rec.getY(), rec.getMaxX(), rec.getMaxY(), SUBTYPES.GEOM2D));
1018
        } catch (CreateEnvelopeException e) {
1019
            logger.error("Error seting the bounding box");
1020
        }
1021
    }
1022

    
1023
    /**
1024
     * <p>
1025
     * Returns the screen resolution (Dots Per Inch) as it was defined by the
1026
     * user's preference, or by default as it is defined in the default
1027
     * Toolkit.</p>
1028
     *
1029
     * Be care, use ViewPort#getDPI to ensure are using the corrects DPI.
1030
     *
1031
     * @return double with the screen's dpi
1032
     */
1033
    public static double getScreenDPI() {
1034
        return CompatLocator.getGraphicsUtils().getScreenDPI();
1035
    }
1036

    
1037
    /**
1038
     * @see
1039
     * org.gvsig.fmap.mapcontext.rendering.strategies.Strategy#process(com.iver.cit.gvsig.fmap.FeatureSelectorVisitor)
1040
     */
1041
    public void process(Visitor visitor) {
1042
    }
1043

    
1044
    /**
1045
     * @see
1046
     * org.gvsig.fmap.mapcontext.rendering.strategies.Strategy#processSelected(com.iver.cit.gvsig.fmap.FeatureVisitor)
1047
     */
1048
    public void processSelected(Visitor visitor) {
1049
    }
1050

    
1051
    /**
1052
     * @see
1053
     * org.gvsig.fmap.mapcontext.rendering.strategies.Strategy#select(com.iver.cit.gvsig.fmap.FeatureSelectorVisitor,
1054
     * VectorialSubSet)
1055
     */
1056
    public void select(Visitor visitor) {
1057
    }
1058

    
1059
    /**
1060
     * @see
1061
     * org.gvsig.fmap.mapcontext.rendering.strategies.Strategy#selectFromSelection()
1062
     */
1063
    public void selectFromSelection() {
1064
    }
1065

    
1066
    /**
1067
     * @see
1068
     * org.gvsig.fmap.mapcontext.rendering.strategies.Strategy#createIndex()
1069
     */
1070
    public void createIndex() {
1071
    }
1072

    
1073
    /**
1074
     * @see org.cresques.geo.Projected#getProjection()
1075
     *
1076
     * @see ViewPort#getProjection()
1077
     * @see #setProjection(IProjection)
1078
     * @see #reProject(ICoordTrans)
1079
     */
1080
    public IProjection getProjection() {
1081
        return getViewPort().getProjection();
1082
    }
1083

    
1084
    /**
1085
     * <p>
1086
     * Sets the new projection.</p>
1087
     *
1088
     * @param proj the new projection
1089
     *
1090
     * @see #getProjection()
1091
     * @see ViewPort#setProjection(IProjection)
1092
     * @see #reProject(ICoordTrans)
1093
     */
1094
    public void setProjection(IProjection proj) {
1095
        if (getViewPort() != null) {
1096
            getViewPort().setProjection(proj);
1097
        }
1098
    }
1099

    
1100
    /**
1101
     * @see org.cresques.geo.Projected#reProject(org.cresques.cts.ICoordTrans)
1102
     */
1103
    public void reProject(ICoordTrans arg0) {
1104
        // TODO implementar reprojecci?n (lo que sea eso)
1105
    }
1106

    
1107
    public Envelope getSelectionBounds() throws BaseException {
1108

    
1109
        SelectedEnvelopeVisitor visitor = new SelectedEnvelopeVisitor();
1110

    
1111
        layers.accept(visitor);
1112
        Envelope env_in_data_crs = visitor.getSelectioEnvelope();
1113
        return env_in_data_crs;
1114
    }
1115

    
1116
    /**
1117
     * <p>
1118
     * Draws this map if its {@link ViewPort ViewPort} has an extent
1119
     * defined:<br>
1120
     * <ol>
1121
     * <li>Selects only the layers that have to be drawn:
1122
     * {@linkplain #prepareDrawing(BufferedImage, Graphics2D, double)}.
1123
     * <li>Sets quality: antialiasing by text and images, and quality rendering.
1124
     * <li>Draws the layers.
1125
     * <li>Fires a <code>LayerDrawEvent.GRAPHICLAYER_BEFORE_DRAW</code>.
1126
     * <li>Draws the graphic layer.
1127
     * <li>Fires a <code>LayerDrawEvent.GRAPHICLAYER_AFTER_DRAW</code>.
1128
     * <li>Invokes the garbage collector and memory clean.
1129
     * </ol>
1130
     * </p>
1131
     *
1132
     * @param image buffer used sometimes instead <code>g</code> to accelerate
1133
     * the draw. For example, if two points are as closed that can't be
1134
     * distinguished, draws only one.
1135
     * @param g for rendering 2-dimensional shapes, text and images on the
1136
     * Java(tm) platform
1137
     * @param cancel shared object that determines if this layer can continue
1138
     * being drawn
1139
     * @param scale the scale of the view. Must be between
1140
     * {@linkplain FLayer#getMinScale()} and {@linkplain FLayer#getMaxScale()}.
1141
     * @throws MapContextException if there is an error getting the instance of
1142
     * MapContextDrawer
1143
     * @throws ReadDriverException if fails reading with the driver.
1144
     */
1145
    public void draw(BufferedImage image, Graphics2D g, Cancellable cancel,
1146
            double scale) throws ReadException, MapContextException {
1147
        if (viewPort.getEnvelope() == null) {
1148
            return;
1149
        }
1150

    
1151
        CompatLocator.getGraphicsUtils().setRenderingHintsForDrawing(g);
1152

    
1153
        this.getMapContextDrawer().draw(this.layers, image, g, cancel, scale);
1154
    }
1155

    
1156
    /**
1157
     * <p>
1158
     * Draws only the internal graphic layer using the information of the
1159
     * {@link ViewPort ViewPort} of this map.</p>
1160
     *
1161
     * @param image image used to accelerate the screen draw
1162
     * @param g for rendering 2-dimensional shapes, text and images on the
1163
     * Java(tm) platform
1164
     * @param cancel shared object that determines if this layer can continue
1165
     * being drawn
1166
     * @param scale value that represents the scale
1167
     * @throws ReadDriverException if fails reading with the driver.
1168
     * @deprecated use
1169
     * {@link #draw(BufferedImage, Graphics2D, Cancellable, double)} instead
1170
     * @see GraphicLayer#draw(BufferedImage, Graphics2D, ViewPort, Cancellable,
1171
     * double)
1172
     */
1173
    public void drawGraphics(BufferedImage image, Graphics2D g,
1174
            Cancellable cancel, double scale) throws ReadException {
1175

    
1176
                // From now on the graphics layer is handled by the MapContextDrawer,
1177
        // so call the draw method instead.
1178
        try {
1179
            draw(image, g, cancel, scale);
1180
        } catch (MapContextException e) {
1181
            throw new RuntimeException(e);
1182
        }
1183
    }
1184

    
1185
    /**
1186
     * <p>
1187
     * Like
1188
     * {@linkplain MapContext#draw(BufferedImage, Graphics2D, Cancellable, double)}
1189
     * , but creating the task as cancellable.
1190
     * </p>
1191
     *
1192
     * @param image buffer used sometimes instead <code>g</code> to accelerate
1193
     * the draw. For example, if two points are as closed that can't be
1194
     * distinguished, draws only one.
1195
     * @param g for rendering 2-dimensional shapes, text and images on the
1196
     * Java(tm) platform
1197
     * @param scale the scale of the view. Must be between
1198
     * {@linkplain FLayer#getMinScale()} and {@linkplain FLayer#getMaxScale()}.
1199
     * @throws MapContextException if there is an error getting the instance of
1200
     * MapContextDrawer
1201
     *
1202
     * @throws ReadDriverException if the driver fails reading.
1203
     *
1204
     * @see #draw(BufferedImage, Graphics2D, Cancellable, double)
1205
     */
1206
    public void draw(BufferedImage image, Graphics2D g, double scale)
1207
            throws ReadException, MapContextException {
1208
        draw(image, g, new Cancellable() {
1209
            /**
1210
             * @see org.gvsig.utils.swing.threads.Cancellable#isCanceled()
1211
             */
1212
            public boolean isCanceled() {
1213
                return false;
1214
            }
1215

    
1216
            public void setCanceled(boolean canceled) {
1217
                // Do nothing
1218
            }
1219
        }, scale);
1220
    }
1221

    
1222
    /**
1223
     * <p>
1224
     * Gets the {@link ViewPort ViewPort} associated to this map.</p>
1225
     *
1226
     * @return the view port
1227
     *
1228
     * @see #setViewPort(ViewPort)
1229
     */
1230
    public ViewPort getViewPort() {
1231
        return viewPort;
1232
    }
1233

    
1234
    /**
1235
     * <p>
1236
     * Sets a {@link ViewPort ViewPort} with the drawing information of this
1237
     * map.</p>
1238
     * <p>
1239
     * If there was a previous view port, removes its
1240
     * {@link EventBuffer EventBuffer} and adds the new one.</p>
1241
     *
1242
     * @param viewPort the viewPort
1243
     *
1244
     * @see #getViewPort()
1245
     */
1246
    public void setViewPort(ViewPort viewPort) {
1247
        if (this.viewPort != null) {
1248
            this.viewPort.removeViewPortListener(eventBuffer);
1249
        }
1250

    
1251
        if (this.mapContextDrawer != null) {
1252
            this.mapContextDrawer.setViewPort(viewPort);
1253
        }
1254

    
1255
        this.viewPort = viewPort;
1256
        if (viewPort != null) {
1257
            viewPort.addViewPortListener(eventBuffer);
1258
        }
1259
    }
1260

    
1261
    /**
1262
     * <p>
1263
     * Sets the given extent to the {@link ViewPort ViewPort} and updates the
1264
     * view with the new zoom.</p>
1265
     *
1266
     * @param extent the extent of the new zoom
1267
     */
1268
    public void zoomToEnvelope(Envelope extent) {
1269
        if (extent != null && !extent.isEmpty()) {
1270
            getViewPort().setEnvelope(extent);
1271
        }
1272
    }
1273

    
1274
    /**
1275
     * <p>
1276
     * Returns the union of all extents of all layers of this map.</p>
1277
     *
1278
     * @return full extent of layers of this map
1279
     * @throws ReadDriverException if the driver fails reading.
1280
     *
1281
     * @see FLayers#getFullEnvelope()
1282
     */
1283
    public Envelope getFullEnvelope() throws ReadException {
1284
        Envelope envelope = layers.getFullEnvelope();
1285

    
1286
        for (GraphicLayer tracLayer : this.tracLayers.values()) {
1287
            if (tracLayer != null) {
1288
                Envelope graphicsEnvelope = tracLayer.getFullEnvelope();
1289
                if( graphicsEnvelope==null ) {
1290
                    continue;
1291
                }
1292
                if (envelope == null) {
1293
                    try {
1294
                        envelope =  (Envelope) graphicsEnvelope.clone();
1295
                    } catch (CloneNotSupportedException ex) {
1296
                    }
1297
                } else if (graphicsEnvelope != null) {
1298
                    envelope.add(graphicsEnvelope);
1299
                }
1300
            }
1301
        }
1302
        return envelope;
1303
    }
1304

    
1305
    /**
1306
     * <p>
1307
     * Adds a listener of atomic events to the internal
1308
     * {@link EventBuffer EventBuffer}.</p>
1309
     *
1310
     * @param listener the new listener
1311
     *
1312
     * @return <code>true</code> if has added the listener successfully
1313
     *
1314
     * @see #removeAtomicEventListener(AtomicEventListener)
1315
     * @see EventBuffer#addAtomicEventListener(AtomicEventListener)
1316
     */
1317
    public boolean addAtomicEventListener(AtomicEventListener listener) {
1318
        return eventBuffer.addAtomicEventListener(listener);
1319
    }
1320

    
1321
    /**
1322
     * <p>
1323
     * Removes a listener of atomic events from the internal
1324
     * {@link EventBuffer EventBuffer}.</p>
1325
     *
1326
     * @param listener the listener to remove
1327
     *
1328
     * @return <tt>true</tt> if the list contained the specified element
1329
     *
1330
     * @see #addAtomicEventListener(AtomicEventListener)
1331
     * @see EventBuffer#removeAtomicEventListener(AtomicEventListener)
1332
     */
1333
    public boolean removeAtomicEventListener(AtomicEventListener listener) {
1334
        return eventBuffer.removeAtomicEventListener(listener);
1335
    }
1336

    
1337
    /**
1338
     * @see EventBuffer#beginAtomicEvent()
1339
     *
1340
     * @see #endAtomicEvent()
1341
     */
1342
    public void beginAtomicEvent() {
1343
        eventBuffer.beginAtomicEvent();
1344
    }
1345

    
1346
    /**
1347
     * @see EventBuffer#endAtomicEvent()
1348
     *
1349
     * @see #beginAtomicEvent()
1350
     */
1351
    public void endAtomicEvent() {
1352
        eventBuffer.endAtomicEvent();
1353
    }
1354

    
1355
    /**
1356
     * <p>
1357
     * The class <code>LayerEventListener</code> implements the methods of
1358
     * {@link LayerCollectionListener LayerCollectionListener} that handles the
1359
     * "layer added" or "layer removed" events in a map.</p>
1360
     * <p>
1361
     * Is designed as a listener for all layers in a
1362
     * {@link MapContext MapContext}.</p>
1363
     *
1364
     * @author Fernando Gonz?lez Cort?s
1365
     */
1366
    public class LayerEventListener extends BaseLayerCollectionListener {
1367

    
1368
        @Override
1369
        public void layerAdded(LayerCollectionEvent e) {
1370
            // Voy a mover todo esto a la vista
1371
//            // Si aun no tenemos envelope, problablemente sera la primera capa,
1372
//            // asi que asignamos el envelope de la capa al mapcontext.
1373
//            if (getViewPort().getEnvelope() == null) {
1374
//                FLayer lyr = e.getAffectedLayer();
1375
//                if (lyr.isAvailable()) {
1376
//                    try {
1377
//                        getViewPort().setEnvelope(lyr.getFullEnvelope());
1378
//                    } catch (Exception ex) {
1379
//                        logger.warn(
1380
//                                MessageFormat.format(
1381
//                                    "Can''t set envelope to view port from layer ''{0}''",
1382
//                                    new Object[]{lyr.getName()}
1383
//                                ),
1384
//                                ex
1385
//                        );
1386
//                    }
1387
//                }
1388
//            }
1389

    
1390
            // Registramos al FMap como listener del legend de las capas
1391
            FLayer lyr = e.getAffectedLayer();
1392
            addSelectionListener(lyr);
1393
        }
1394

    
1395
        @Override
1396
        public void layerRemoved(LayerCollectionEvent e) {
1397
            FLayer lyr = e.getAffectedLayer();
1398

    
1399
            lyr.removeLayerListener(eventBuffer);
1400

    
1401
            if (lyr instanceof Classifiable) {
1402
                Classifiable c = (Classifiable) lyr;
1403
                c.removeLegendListener(eventBuffer);
1404
            }
1405

    
1406
            if (lyr instanceof SingleLayer && ((SingleLayer) lyr).getDataStore() != null) {
1407
                ((SingleLayer) lyr).getDataStore().deleteObserver(
1408
                        MapContext.this);
1409
            }
1410

    
1411
        }
1412

    
1413
    }
1414

    
1415
    /**
1416
     * <p>
1417
     * Adds the {@link LayerEventListener LayerEventListener} of this map to the
1418
     * collection of layers argument.</p>
1419
     *
1420
     * @param a collection of layers
1421
     */
1422
    public void addAsCollectionListener(FLayers layers2) {
1423
        layers2.addLayerCollectionListener(layerEventListener);
1424
    }
1425

    
1426
    public GraphicLayer getGraphicsLayer(String name) {
1427
        return this.tracLayers.get(name);
1428
    }
1429
    
1430
    public void setGraphicsLayer(String name, GraphicLayer layer) {
1431
        this.tracLayers.put(name, layer);
1432
    }
1433
    
1434
    public void removeGraphicsLayer(String name) {
1435
        this.tracLayers.remove(name);
1436
    }
1437
    
1438
    /**
1439
     * <p>
1440
     * Returns the internal {@link GraphicLayer GraphicLayer}.</p>
1441
     *
1442
     * @return the graphic layer of this map
1443
     *
1444
     * @see #setGraphicsLayer(GraphicLayer)
1445
     */
1446
    public GraphicLayer getGraphicsLayer() {
1447
        GraphicLayer tracLayer = this.tracLayers.get(DEFAULT_TRACTLAYER);
1448
        if (tracLayer == null) {
1449
            if (getViewPort() != null) {
1450
                tracLayer
1451
                        = MapContextLocator.getMapContextManager()
1452
                        .createGraphicsLayer(
1453
                                getViewPort().getProjection());
1454
            } else {
1455
                tracLayer
1456
                        = MapContextLocator.getMapContextManager()
1457
                        .createGraphicsLayer(null);
1458
            }
1459
            this.tracLayers.put(DEFAULT_TRACTLAYER, tracLayer);
1460
        }
1461
        return tracLayer;
1462
    }
1463

    
1464
    /**
1465
     * <p>
1466
     * Sets a new {@link GraphicLayer GraphicLayer} to this map.</p>
1467
     *
1468
     * @param graphicLayer the new graphic layer
1469
     *
1470
     * @see #getGraphicsLayer()
1471
     */
1472
    public void setGraphicsLayer(GraphicLayer graphicLayer) {
1473
        this.tracLayers.put(DEFAULT_TRACTLAYER, graphicLayer);
1474
    }
1475

    
1476
    /**
1477
     * <p>
1478
     * Indicates whether some other object is "equal to" this map.</p>
1479
     * <p>
1480
     * Returns <code>true</code> if success one of this options:
1481
     * <ul>
1482
     * <li>Both objects are equal according to
1483
     * {@linkplain Object#equals(Object)}.
1484
     * <li>Both maps have the same layers.
1485
     * <li>Both maps have the same number of layers and with the same name.
1486
     * </ul>
1487
     * </p>
1488
     *
1489
     * @param obj the reference object with which to compare.
1490
     * @return <code>true</code> if this object is the same as the
1491
     * <code>arg0</code> argument; otherwise <code>false</code>.
1492
     *
1493
     * @see Object#equals(Object)
1494
     */
1495
    public boolean equals(Object arg0) {
1496
        if (!(arg0 instanceof MapContext)) {
1497
            return false;
1498
        }
1499
        MapContext map = (MapContext) arg0;
1500
        if (super.equals(arg0)) {
1501
            return true;
1502
        }
1503
        if (getLayers() == map.getLayers()) {
1504
            return true;
1505
        }
1506
        boolean isEqual = true;
1507
        if (map.getLayers().getLayersCount() == getLayers().getLayersCount()) {
1508
            for (int i = 0; i < getLayers().getLayersCount(); i++) {
1509

    
1510
                if (!getLayers().getLayer(i).getName().equals(
1511
                        map.getLayers().getLayer(i).getName())) {
1512
                    isEqual = false;
1513
                }
1514

    
1515
            }
1516
        } else {
1517
            isEqual = false;
1518
        }
1519
        return isEqual;
1520
    }
1521

    
1522
    /**
1523
     * <p>
1524
     * Registers the message of an error associated to this map.</p>
1525
     *
1526
     * @param stringProperty the error message
1527
     *
1528
     * @see #getLayersError()
1529
     * @see #clearErrors()
1530
     */
1531
    public void addLayerError(String stringProperty) {
1532
        layersError.add(stringProperty);
1533
    }
1534

    
1535
    /**
1536
     * <p>
1537
     * Gets the list with all error messages registered to this map.</p>
1538
     *
1539
     * @return the list of errors registered to this map
1540
     *
1541
     * @see #addLayerError(String)
1542
     * @see #clearErrors()
1543
     */
1544
    public ArrayList getLayersError() {
1545
        return layersError;
1546
    }
1547

    
1548
    /**
1549
     * <p>
1550
     * Removes all error messages associated to this map.</p>
1551
     *
1552
     * @see #addLayerError(String)
1553
     * @see #getLayersError()
1554
     */
1555
    public void clearErrors() {
1556
        layersError.clear();
1557
    }
1558

    
1559
    /**
1560
     * <p>
1561
     * Creates and returns a new group of layers that belongs to this
1562
     * <code>MapContext</code>.</p>
1563
     *
1564
     * @param parent layer node in this <code>MapContexte</code> that will be
1565
     * the parent of the new node
1566
     * @return the new layer node
1567
     */
1568
    public FLayers getNewGroupLayer(FLayers parent) {
1569
        FLayers group1 = new FLayers();//(this,parent);
1570
        group1.setMapContext(this);
1571
        group1.setParentLayer(parent);
1572
        return group1;
1573
    }
1574

    
1575
    public String getClassName() {
1576
        return null;
1577
    }
1578

    
1579
    public ArrayList getLayersToSnap() {
1580
        return layersToSnap;
1581
    }
1582

    
1583
    public void setLayersToSnap(ArrayList layersToSnap) {
1584
        this.layersToSnap = layersToSnap;
1585

    
1586
    }
1587

    
1588
    public void update(Observable observable, Object notification) {
1589
        // TODO REVISAR ESTO!!!
1590
        String ntype = null;
1591
        if (notification instanceof FeatureStoreNotification) {
1592
            FeatureStoreNotification fsNotification = (FeatureStoreNotification) notification;
1593
            ntype = fsNotification.getType();
1594
            if (ntype.equals(FeatureStoreNotification.LOAD_FINISHED)
1595
                    || ntype.equals(FeatureStoreNotification.SELECTION_CHANGE)) {
1596
                getLayers().moveTo(0, 0);
1597
            }
1598
        }
1599
    }
1600

    
1601
    public long getDrawVersion() {
1602
        if (getViewPort().getDrawVersion() > this.viewPortVersion
1603
                || getLayers().getDrawVersion() > this.layersVersion
1604
                || getGraphicsLayer().getDrawVersion() > graphicsLayerVersion) {
1605
            updateDrawVersion();
1606
        }
1607
        return this.drawVersion;
1608
    }
1609

    
1610
    protected void updateDrawVersion() {
1611
        this.layersVersion = getLayers().getDrawVersion();
1612
        this.viewPortVersion = getViewPort().getDrawVersion();
1613
        this.graphicsLayerVersion = getGraphicsLayer().getDrawVersion();
1614
        this.drawVersion++;
1615
    }
1616

    
1617
    public MapContextDrawer getMapContextDrawer() throws ReadException,
1618
            MapContextException {
1619
        if (this.mapContextDrawer == null) {
1620
            if (mapContextDrawerClass == null) {
1621
                this.mapContextDrawer = mapContextManager
1622
                        .createDefaultMapContextDrawerInstance();
1623
            } else {
1624
                this.mapContextDrawer = mapContextManager
1625
                        .createMapContextDrawerInstance(mapContextDrawerClass);
1626
            }
1627
            this.mapContextDrawer.setMapContext(this);
1628
            this.mapContextDrawer.setViewPort(viewPort);
1629
        }
1630

    
1631
        return this.mapContextDrawer;
1632
    }
1633

    
1634
    public void setMapContextDrawerClass(Class mapContextDrawerClass)
1635
            throws MapContextException {
1636
        mapContextManager.validateMapContextDrawer(mapContextDrawerClass);
1637
        this.mapContextDrawerClass = mapContextDrawerClass;
1638
        if (this.mapContextDrawer != null) {
1639
            this.mapContextDrawer.dispose();
1640
            this.mapContextDrawer = null;
1641
        }
1642
    }
1643

    
1644
    public void setMapContextDrawer(MapContextDrawer drawer) {
1645
        if (this.mapContextDrawer != null) {
1646
            this.mapContextDrawer.dispose();
1647
            this.mapContextDrawer = null;
1648
        }
1649
        this.mapContextDrawer = drawer;
1650
        if (this.mapContextDrawer != null) {
1651
            this.mapContextDrawer.setMapContext(this);
1652
            this.mapContextDrawer.setViewPort(viewPort);
1653
        }
1654
    }
1655

    
1656
    public void loadFromState(PersistentState state)
1657
            throws PersistenceException {
1658

    
1659
        ViewPort vp = (ViewPort) state.get("ViewPort");
1660
        setViewPort(vp);
1661

    
1662
        layers = (FLayers) state.get("layers");
1663
        layers.setName("root layer");
1664
        loadLayers(layers);
1665
        layers.setMapContext(this);
1666

    
1667
        layerEventListener = new LayerEventListener();
1668
        layers.addLayerCollectionListener(layerEventListener);
1669

    
1670
        layers.addLayerCollectionListener(eventBuffer);
1671
        layers.setProjection(vp.getProjection());
1672

    
1673
        //Add the listener for the selection
1674
        addSelectionListener(layers);
1675

    
1676
        // ======================
1677
        if (state.hasValue("orderManager")) {
1678
            LayerOrderManager lom = (LayerOrderManager) state.get("orderManager");
1679
            this.setOrderManager(lom);
1680
        }
1681
        DefaultMapContextManager manager = (DefaultMapContextManager) MapContextLocator.getMapContextManager();
1682
        manager.notifyLoadMapContext(this);
1683
    }
1684

    
1685
    private void loadLayers(FLayers lyrs) {
1686

    
1687
        int sz = lyrs.getLayersCount();
1688
        for (int i = 0; i < sz; i++) {
1689
            try {
1690
                lyrs.getLayer(i).load();
1691
            } catch (LoadLayerException e) {
1692
                logger.error("While loading layer: " + lyrs.getLayer(i).getName());
1693
            }
1694
        }
1695
    }
1696

    
1697
    public void saveToState(PersistentState state) throws PersistenceException {
1698
        state.set("ViewPort", viewPort);
1699
        state.set("layers", (Persistent)layers);
1700
        state.set("orderManager", this.getOrderManager());
1701
    }
1702

    
1703
    public static class RegisterPersistence implements Callable {
1704

    
1705
        public Object call() {
1706
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
1707
            DynStruct definition = manager.addDefinition(
1708
                    MapContext.class,
1709
                    "MapContext",
1710
                    "MapContext Persistence definition",
1711
                    null,
1712
                    null
1713
            );
1714
            definition.addDynFieldObject("ViewPort")
1715
                    .setClassOfValue(ViewPort.class)
1716
                    .setMandatory(true);
1717

    
1718
            definition.addDynFieldObject("layers")
1719
                    .setClassOfValue(FLayers.class)
1720
                    .setMandatory(true);
1721

    
1722
            definition.addDynFieldObject("orderManager")
1723
                    .setClassOfValue(LayerOrderManager.class)
1724
                    .setMandatory(false);
1725

    
1726
            return Boolean.TRUE;
1727
        }
1728
    }
1729

    
1730
    protected void doDispose() throws BaseException {
1731
        dispose(layers);
1732
        for (GraphicLayer tracLayer : this.tracLayers.values()) {
1733
            dispose(tracLayer);
1734
        }
1735
    }
1736

    
1737
    /**
1738
     * <p>
1739
     * Registers an event buffer as a listener for all layers as argument.</p>
1740
     *
1741
     * <p>
1742
     * Each {@link FLayer FLayer} of this map must have an event buffer for all
1743
     * kind of specific listeners of that layer. This method distinguish between {@link Classifiable Classifiable},
1744
     * {@link AlphanumericData AlphanumericData}, and {@link FLayers FLayers}
1745
     * layers, and for each one, registers, for their specific listeners, the
1746
     * <code>eventBuffer</code> as a listener.</p>
1747
     *
1748
     * @param the layer or layers
1749
     */
1750
    private void addSelectionListener(FLayer lyr) {
1751
        lyr.addLayerListener(eventBuffer);
1752

    
1753
        if (lyr instanceof Classifiable) {
1754
            Classifiable c = (Classifiable) lyr;
1755
            c.addLegendListener(eventBuffer);
1756
        }
1757

    
1758
        if (lyr instanceof FLayers) {
1759
            FLayers lyrs = (FLayers) lyr;
1760
            for (int i = 0; i < lyrs.getLayersCount(); i++) {
1761
                addSelectionListener(lyrs.getLayer(i));
1762
            }
1763
        }
1764
        if (lyr instanceof SingleLayer) {
1765
            if (((SingleLayer) lyr).getDataStore() != null) {
1766
                ((SingleLayer) lyr).getDataStore().addObserver(
1767
                        MapContext.this);
1768
            }
1769
        }
1770
    }
1771

    
1772
    public void setOrderManager(LayerOrderManager lom) {
1773
        orderManager = lom;
1774
    }
1775

    
1776
    public LayerOrderManager getOrderManager() {
1777

    
1778
        if (orderManager == null) {
1779
            orderManager = MapContextLocator.getDefaultOrderManager();
1780
        }
1781
        return orderManager;
1782
    }
1783

    
1784
    public boolean hasVectorLayers() {
1785
        return this.hasVectorLayers(this.getLayers());
1786
    }
1787

    
1788
    public boolean hasActiveVectorLayers() {
1789
        FLayer[] layers = this.getLayers().getActives();
1790
        for (int i = 0; i < layers.length; i++) {
1791
            FLayer layer = layers[i];
1792
            if (layer.isAvailable() && layer instanceof FLyrVect) {
1793
                return true;
1794
            }
1795
        }
1796
        return false;
1797
    }
1798

    
1799
    public boolean hasActiveLayers() {
1800
        FLayer[] layers = this.getLayers().getActives();
1801
        return !ArrayUtils.isEmpty(layers);
1802
    }
1803

    
1804
    public boolean hasLayers() {
1805
        return !this.getLayers().isEmpty();
1806
    }
1807
    
1808
    private boolean hasVectorLayers(FLayers layers) {
1809
        for (int i = 0; i < layers.getLayersCount(); i++) {
1810
            FLayer lyr = layers.getLayer(i);
1811
            if (lyr instanceof FLayers) {
1812
                if (hasVectorLayers((FLayers) lyr)) {
1813
                    return true;
1814
                }
1815
            } else if (lyr instanceof FLyrVect) {
1816
                return true;
1817
            }
1818
        }
1819
        return false;
1820
    }
1821
    
1822
    @Override
1823
    public Iterator<FLayer> iterator() {
1824
        return this.layers.iterator();
1825
    }
1826

    
1827
    public Iterator deepiterator() {
1828
        return this.layers.deepiterator();
1829
    }
1830

    
1831
    public MapTimeContext getTimeContext() {
1832
        TimeSupportManager timeSupportManager = TimeSupportLocator.getManager();
1833
        Interval interval = null;
1834
        final List<Instant> times = new ArrayList<>();
1835
        Instant minInstant = null;
1836
        Instant maxInstant = null;
1837

    
1838
        //TODO Separate absolute and relative time
1839
        FLayers layers = this.getLayers();
1840
        for( Iterator<FLayer> iterator = layers.deepiterator(); iterator.hasNext(); ) {
1841
            FLayer layer = iterator.next();
1842
            if( layer instanceof SingleLayer ) {
1843
                DataStore dataStore = ((SingleLayer) layer).getDataStore();
1844
                if( dataStore.getInterval() != null ) {
1845
                    Instant startInstant = dataStore.getInterval().getStart();
1846
                    Instant endInstant = dataStore.getInterval().getEnd();
1847
                    times.addAll(dataStore.getTimes());
1848
                    if( minInstant == null ) {
1849
                        minInstant = startInstant;
1850
                        maxInstant = endInstant;
1851
                    } else {
1852
                        if( minInstant.isAfter(startInstant) ) {
1853
                            minInstant = startInstant;
1854
                        }
1855
                        if( maxInstant.isBefore(endInstant) ) {
1856
                            maxInstant = endInstant;
1857
                        }
1858
                    }
1859
                }
1860
            }
1861
        }
1862

    
1863
        if( minInstant != null ) {
1864
            if( minInstant.isAbsolute() ) {
1865
                try {
1866
                    interval = timeSupportManager.createAbsoluteInterval((AbsoluteInstant) minInstant, (AbsoluteInstant) maxInstant);
1867
                } catch (AbsoluteIntervalTypeNotRegisteredException e) {
1868
                    logger.warn("Error creating the time interval", e);
1869
                }
1870
            } else {
1871
                interval = timeSupportManager.createRelativeInterval(((RelativeInstant) minInstant).toMillis(), ((RelativeInstant) maxInstant).toMillis());
1872
            }
1873
        }
1874
        final Interval tmp_interval = interval;
1875
        return new MapTimeContext() {
1876
            @Override
1877
            public Interval getInterval() {
1878
                return tmp_interval;
1879
            }
1880

    
1881
            @Override
1882
            public List<Instant> getTimes() {
1883
                return times;
1884
            }
1885
        };
1886
    }
1887

    
1888
}