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 @ 44224

History | View | Annotate | Download (63.5 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
    }
557

    
558
    /**
559
     * <p>
560
     * Creates a new map context with the layers and the drawing information
561
     * defined in the view port arguments.</p>
562
     *
563
     * @param fLayers the initial hierarchy of nodes of layers that this map
564
     * will have
565
     * @param vp information for drawing the layers of this map in the available
566
     * rectangular area according a projection
567
     */
568
    public MapContext(FLayers fLayers, ViewPort vp) {
569
        this.layers = fLayers;
570
        this.tracLayers = new LinkedHashMap<>();
571

    
572
        layerEventListener = new LayerEventListener();
573

    
574
        if (layers != null) {
575
            layers.setMapContext(this);
576
            layers.addLayerCollectionListener(layerEventListener);
577
            layers.addLayerCollectionListener(eventBuffer);
578
        }
579

    
580
        setViewPort(vp);
581
    }
582

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
832
        CompatLocator.getGraphicsUtils().setRenderingHintsForPrinting(g);
833

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

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

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

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

    
867
        return ret;
868
    }
869

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

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

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

    
921
    }
922

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

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

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

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

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

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

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

    
991
    }
992

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

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

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

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

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

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

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

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

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

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

    
1109
    public Envelope getSelectionBounds() throws BaseException {
1110

    
1111
        SelectedEnvelopeVisitor visitor = new SelectedEnvelopeVisitor();
1112

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

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

    
1153
        CompatLocator.getGraphicsUtils().setRenderingHintsForDrawing(g);
1154

    
1155
        this.getMapContextDrawer().draw(this.layers, image, g, cancel, scale);
1156
    }
1157

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1401
            lyr.removeLayerListener(eventBuffer);
1402

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

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

    
1413
        }
1414

    
1415
    }
1416

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

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

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

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

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

    
1517
            }
1518
        } else {
1519
            isEqual = false;
1520
        }
1521
        return isEqual;
1522
    }
1523

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

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

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

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

    
1577
    public String getClassName() {
1578
        return null;
1579
    }
1580

    
1581
    public ArrayList getLayersToSnap() {
1582
        return layersToSnap;
1583
    }
1584

    
1585
    public void setLayersToSnap(ArrayList layersToSnap) {
1586
        this.layersToSnap = layersToSnap;
1587

    
1588
    }
1589

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

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

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

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

    
1633
        return this.mapContextDrawer;
1634
    }
1635

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

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

    
1658
    public void loadFromState(PersistentState state)
1659
            throws PersistenceException {
1660

    
1661
        ViewPort vp = (ViewPort) state.get("ViewPort");
1662
        setViewPort(vp);
1663

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

    
1669
        layerEventListener = new LayerEventListener();
1670
        layers.addLayerCollectionListener(layerEventListener);
1671

    
1672
        layers.addLayerCollectionListener(eventBuffer);
1673
        layers.setProjection(vp.getProjection());
1674

    
1675
        //Add the listener for the selection
1676
        addSelectionListener(layers);
1677

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

    
1687
    private void loadLayers(FLayers lyrs) {
1688

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

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

    
1705
    public static class RegisterPersistence implements Callable {
1706

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

    
1720
            definition.addDynFieldObject("layers")
1721
                    .setClassOfValue(FLayers.class)
1722
                    .setMandatory(true);
1723

    
1724
            definition.addDynFieldObject("orderManager")
1725
                    .setClassOfValue(LayerOrderManager.class)
1726
                    .setMandatory(false);
1727

    
1728
            return Boolean.TRUE;
1729
        }
1730
    }
1731

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

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

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

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

    
1774
    public void setOrderManager(LayerOrderManager lom) {
1775
        orderManager = lom;
1776
    }
1777

    
1778
    public LayerOrderManager getOrderManager() {
1779

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

    
1786
    public boolean hasVectorLayers() {
1787
        return this.hasVectorLayers(this.getLayers());
1788
    }
1789

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

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

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

    
1829
    public Iterator deepiterator() {
1830
        return this.layers.deepiterator();
1831
    }
1832

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

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

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

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

    
1890
}