Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libFMap_mapcontext / src / org / gvsig / fmap / mapcontext / layers / FLayers.java @ 33281

History | View | Annotate | Download (44.1 KB)

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

    
43
import java.awt.Graphics2D;
44
import java.awt.Point;
45
import java.awt.image.BufferedImage;
46
import java.util.ArrayList;
47
import java.util.Collections;
48
import java.util.Iterator;
49
import java.util.List;
50
import java.util.Set;
51
import java.util.TreeSet;
52

    
53
import org.cresques.cts.ICoordTrans;
54
import org.cresques.cts.IProjection;
55
import org.gvsig.compat.print.PrintAttributes;
56
import org.gvsig.fmap.dal.exception.DataException;
57
import org.gvsig.fmap.dal.exception.ReadException;
58
import org.gvsig.fmap.geom.primitive.Envelope;
59
import org.gvsig.fmap.mapcontext.MapContext;
60
import org.gvsig.fmap.mapcontext.Messages;
61
import org.gvsig.fmap.mapcontext.ViewPort;
62
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
63
import org.gvsig.fmap.mapcontext.layers.operations.ComposedLayer;
64
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
65
import org.gvsig.fmap.mapcontext.layers.operations.LayerCollection;
66
import org.gvsig.fmap.mapcontext.layers.operations.LayersVisitable;
67
import org.gvsig.fmap.mapcontext.layers.operations.LayersVisitor;
68
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelable;
69
import org.gvsig.metadata.exceptions.MetadataException;
70
import org.gvsig.tools.ToolsLocator;
71
import org.gvsig.tools.dispose.Disposable;
72
import org.gvsig.tools.dynobject.DynStruct;
73
import org.gvsig.tools.exception.BaseException;
74
import org.gvsig.tools.persistence.PersistenceManager;
75
import org.gvsig.tools.persistence.PersistentState;
76
import org.gvsig.tools.persistence.exception.PersistenceException;
77
import org.gvsig.tools.task.Cancellable;
78
import org.gvsig.tools.visitor.NotSupportedOperationException;
79
import org.gvsig.tools.visitor.Visitor;
80
import org.slf4j.Logger;
81
import org.slf4j.LoggerFactory;
82

    
83

    
84
/**
85
 * <p>Represents a generic collection of layers, that can be represented as a node in a tree of nodes of layers.</p>
86
 *
87
 * <p>Adapts the basic functionality implemented for a layer in the abstract class <code>FLyrDefault</code>, to
88
 *  a collection of layers, implementing, as well, specific methods for this kind of object, defined in the
89
 *  interfaces <code>VectorialData</code>, <code>LayerCollection</code>, and <code>InfoByPoint</code>.</p>
90
 *
91
 * @see FLyrDefault
92
 */
93
public class FLayers extends FLyrDefault implements LayerCollection,
94
InfoByPoint {
95
        /**
96
         * List with all listeners registered for this kind of node.
97
         *
98
         * @see #addLayerCollectionListener(LayerCollectionListener)
99
         * @see #removeLayerCollectionListener(LayerCollectionListener)
100
         * @see #callLayerAdded(LayerCollectionEvent)
101
         * @see #callLayerAdding(LayerCollectionEvent)
102
         * @see #callLayerMoved(LayerPositionEvent)
103
         * @see #callLayerMoving(LayerPositionEvent)
104
         * @see #callLayerRemoved(LayerCollectionEvent)
105
         * @see #callLayerRemoving(LayerCollectionEvent)
106
         */
107
        protected ArrayList layerCollectionListeners = null;
108

    
109
        /**
110
         * A synchronized list with the layers.
111
         *
112
         * @see #setAllVisibles(boolean)
113
         * @see #addLayer(FLayer)
114
         * @see #addLayer(int, FLayer)
115
         * @see #moveTo(int, int)
116
         * @see #removeLayer(FLayer)
117
         * @see #removeLayer(int)
118
         * @see #removeLayer(String)
119
         * @see #replaceLayer(String, FLayer)
120
         * @see #getVisibles()
121
         * @see #getLayer(int)
122
         * @see #getLayer(String)
123
         * @see #getLayersCount()
124
         * @see #getFullEnvelope()
125
         */
126
        protected List layers = null;
127

    
128
        /**
129
         * The model of the layer.
130
         *
131
         * @see #getMapContext()
132
         */
133
        protected MapContext fmap;
134

    
135
        /**
136
         * Useful for debug the problems during the implementation.
137
         */
138
        private static Logger logger = LoggerFactory.getLogger(FLayers.class);
139

    
140
        public FLayers() {
141
                super();
142
                layerCollectionListeners = new ArrayList();
143
                layers = Collections.synchronizedList(new ArrayList());
144
                
145
                logger = LoggerFactory.getLogger(FLayers.class);
146
        }
147
        /*
148
         * (non-Javadoc)
149
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#addLayerCollectionListener(com.iver.cit.gvsig.fmap.layers.LayerCollectionListener)
150
         */
151
        public void addLayerCollectionListener(LayerCollectionListener listener) {
152
                if (!layerCollectionListeners.contains(listener)) {
153
                        layerCollectionListeners.add(listener);
154
                }
155
        }
156

    
157
        /*
158
         * (non-Javadoc)
159
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#setAllVisibles(boolean)
160
         */
161
        public void setAllVisibles(boolean visible) {
162
                FLayer lyr;
163

    
164
                for (int i = 0; i < layers.size(); i++) {
165
                        lyr = ((FLayer) layers.get(i));
166
                        lyr.setVisible(visible);
167

    
168
                        if (lyr instanceof LayerCollection) {
169
                                ((LayerCollection) lyr).setAllVisibles(visible);
170
                        }
171
                }
172
        }
173

    
174
        /*
175
         * (non-Javadoc)
176
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayerCollectionListener(com.iver.cit.gvsig.fmap.layers.LayerCollectionListener)
177
         */
178
        public void removeLayerCollectionListener(LayerCollectionListener listener) {
179
                layerCollectionListeners.remove(listener);
180
        }
181

    
182
        /**
183
         * Adds a layer on an specified position in this node.
184
         *
185
         * @param pos position in the inner list where the layer will be added
186
         * @param layer a layer
187
         */
188
        private void doAddLayer(int pos,FLayer layer) {
189
                layers.add(pos,layer);
190
                layer.setParentLayer(this);
191
                IProjection layerProj = layer.getProjection();
192
                if(layerProj != null && fmap != null) {
193
                        IProjection mapContextProj = fmap.getProjection();
194
                        // TODO REVISAR ESTO !!!!
195
                        // Esta condici?n puede que no fuese exacta para todos los casos
196
                        if (!layerProj.getAbrev().equals(mapContextProj.getAbrev())) {
197
                                ICoordTrans ct = layerProj.getCT(mapContextProj);
198
                                layer.setCoordTrans(ct);
199
                        } else {
200
                                layer.setCoordTrans(null);
201
                        }
202
                }
203
                this.updateDrawVersion();
204
        }
205

    
206
        /*
207
         * (non-Javadoc)
208
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#addLayer(com.iver.cit.gvsig.fmap.layers.FLayer)
209
         */
210
        public void addLayer(FLayer layer) {
211
                addLayer(layers.size(),layer);
212
        }
213

    
214
        /**
215
         * Adds a layer in an specified position in this node.
216
         *
217
         * @param layer a layer
218
         */
219
        public void addLayer(int pos,FLayer layer) {
220
                try {
221
                        //Notificamos a la capa que va a ser a?adida
222
                        if (layer instanceof FLyrDefault) {
223
                                ((FLyrDefault)layer).wakeUp();
224
                        }
225

    
226
                        if (layer instanceof FLayers){
227
                                FLayers layers=(FLayers)layer;
228
                                fmap.addAsCollectionListener(layers);
229
                        }
230
                        callLayerAdding(LayerCollectionEvent.createLayerAddingEvent(layer));
231

    
232
                        doAddLayer(pos,layer);
233

    
234
                        callLayerAdded(LayerCollectionEvent.createLayerAddedEvent(layer));
235
                } catch (CancelationException e) {
236
                        logger.warn(e.getMessage());
237
                } catch (LoadLayerException e) {
238
                        layer.setAvailable(false);
239
                        layer.addError(e);
240
                }
241
        }
242

    
243
        /*
244
         * (non-Javadoc)
245
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#moveTo(int, int)
246
         */
247
        public void moveTo(int from, int to) throws CancelationException {
248
                int newfrom=layers.size()-from-1;
249
                int newto=layers.size()-to-1;
250
                if ( newfrom < 0 || newfrom >=layers.size() || newto < 0 || newto >= layers.size()) {
251
                        return;
252
                }
253
                FLayer aux = (FLayer) layers.get(newfrom);
254
                callLayerMoving(LayerPositionEvent.createLayerMovingEvent(aux, newfrom, newto));
255
                layers.remove(newfrom);
256
                layers.add(newto, aux);
257
                this.updateDrawVersion();
258
                callLayerMoved(LayerPositionEvent.createLayerMovedEvent(aux, newfrom, newto));
259
        }
260

    
261
        /**
262
         * Removes an inner layer.
263
         *
264
         * @param lyr a layer
265
         */
266
        private void doRemoveLayer(FLayer lyr) {
267
                layers.remove(lyr);
268
                lyr.dispose();
269
                this.updateDrawVersion();
270
        }
271

    
272
        /*
273
         * (non-Javadoc)
274
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(com.iver.cit.gvsig.fmap.layers.FLayer)
275
         */
276
        public void removeLayer(FLayer lyr) throws CancelationException {
277
                callLayerRemoving(LayerCollectionEvent.createLayerRemovingEvent(lyr));
278
                doRemoveLayer(lyr);
279
                callLayerRemoved(LayerCollectionEvent.createLayerRemovedEvent(lyr));
280
        }
281

    
282
        /*
283
         * (non-Javadoc)
284
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(int)
285
         */
286
        public void removeLayer(int idLayer) {
287
                FLayer lyr = (FLayer) layers.get(idLayer);
288
                callLayerRemoving(LayerCollectionEvent.createLayerRemovingEvent(lyr));
289
                layers.remove(idLayer);
290
                this.updateDrawVersion();
291
                callLayerRemoved(LayerCollectionEvent.createLayerRemovedEvent(lyr));
292
        }
293

    
294
        /*
295
         * (non-Javadoc)
296
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(java.lang.String)
297
         */
298
        public void removeLayer(String layerName) {
299
                FLayer lyr;
300

    
301
                for (int i = 0; i < layers.size(); i++) {
302
                        lyr = ((FLayer) layers.get(i));
303

    
304
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
305
                                removeLayer(i);
306

    
307
                                break;
308
                        }
309
                }
310
        }
311

    
312
        /**
313
         * Replace a layer identified by its name, by another.
314
         *
315
         * @param layerName the name of the layer to be replaced
316
         * @param layer the new layer
317
         */
318
        public void replaceLayer(String layerName, FLayer layer) throws LoadLayerException
319
        {
320
                FLayer lyr;
321
                FLayer parent;
322
                for (int i = 0; i < layers.size(); i++) {
323
                        lyr = ((FLayer) layers.get(i));
324

    
325
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
326
                                parent = lyr.getParentLayer();
327
                                removeLayer(i);
328
                                if (parent != null) {
329
                                        //Notificamos a la capa que va a ser a?adida
330
                                        if (layer instanceof FLyrDefault) {
331
                                                ((FLyrDefault)layer).wakeUp();
332
                                        }
333
                                }
334

    
335
                                if (layer instanceof FLayers){
336
                                        FLayers layers=(FLayers)layer;
337
                                        fmap.addAsCollectionListener(layers);
338
                                }
339
                                callLayerAdding(LayerCollectionEvent.createLayerAddingEvent(layer));
340

    
341
                                layers.add(i,layer);
342
                                layer.setParentLayer(this);
343

    
344
                                callLayerAdded(LayerCollectionEvent.createLayerAddedEvent(layer));
345
                                break;
346
                        }
347
                }
348
        }
349

    
350
        /*
351
         * (non-Javadoc)
352
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getVisibles()
353
         */
354
        public FLayer[] getVisibles() {
355
                ArrayList array = new ArrayList();
356
                LayersIterator iter = new LayersIterator(this) {
357
                        public boolean evaluate(FLayer layer) {
358
                                return layer.isVisible();
359
                        }
360

    
361
                };
362

    
363
                while (iter.hasNext()) {
364
                        array.add(iter.nextLayer());
365
                }
366

    
367
                return (FLayer[]) array.toArray(new FLayer[0]);
368
        }
369

    
370
        /*
371
         * (non-Javadoc)
372
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayer(int)
373
         */
374
        public FLayer getLayer(int index) {
375
                return (FLayer) layers.get(index);
376
        }
377

    
378
        /*
379
         * (non-Javadoc)
380
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayer(java.lang.String)
381
         */
382
        public FLayer getLayer(String layerName) {
383
                FLayer lyr;
384
                FLayer lyr2;
385
                ArrayList layerList;
386

    
387
                for (int i = 0; i < layers.size(); i++) {
388
                        lyr = ((FLayer) layers.get(i));
389

    
390
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
391
                                return lyr;
392
                        }
393

    
394
                        layerList = new ArrayList();
395
                        splitLayerGroup(lyr,layerList);
396
                        for(int j = 0; j<layerList.size(); j++ )
397
                        {
398
                                lyr2 = ((FLayer)layerList.get(j));
399
                                if (lyr2.getName().compareToIgnoreCase(layerName) == 0) {
400
                                        return lyr2;
401
                                }
402
                        }
403
                }
404

    
405
                return null;
406
        }
407

    
408
        /**
409
         * <p> Splits up a layer group in order to get a layer by name when there are layer groups</p>
410
         *
411
         * <p>In <code>result</code> always will be at least one layer.</p>
412
         *
413
         * @param layer the layer we are looking for
414
         * @param result an array list that will have the results of the search
415
         */
416
        private void splitLayerGroup(FLayer layer, ArrayList result)
417
        {
418
                int i;
419
                FLayers layerGroup;
420
                if (layer instanceof FLayers)
421
                {
422
                        layerGroup = (FLayers)layer;
423
                        for (i=0; i < layerGroup.getLayersCount(); i++ )
424
                        {
425
                                splitLayerGroup(layerGroup.getLayer(i),result);
426
                        }
427
                }
428
                else
429
                {
430
                        result.add(layer);
431
                }
432
        }
433

    
434
        /*
435
         * (non-Javadoc)
436
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayersCount()
437
         */
438
        public int getLayersCount() {
439
                return layers.size();
440
        }
441

    
442
        /*
443
         * (non-Javadoc)
444
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#draw(java.awt.image.BufferedImage, java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort, com.iver.utiles.swing.threads.Cancellable, double)
445
         */
446
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
447
                        Cancellable cancel, double scale) throws ReadException {
448
                // FIXME Arreglar este error
449
                throw new RuntimeException("Esto no deberia de llamarse");
450
        }
451

    
452
        /*
453
         * (non-Javadoc)
454
         *
455
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
456
         * com.iver.cit.gvsig.fmap.ViewPort,
457
         * com.iver.utiles.swing.threads.Cancellable, double,
458
         * javax.print.attribute.PrintAttributes)
459
         */
460
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
461
                        double scale, PrintAttributes properties)
462
        throws ReadException {
463
                throw new RuntimeException("No deberia pasar por aqui");
464
        }
465

    
466
        public void print_old(Graphics2D g, ViewPort viewPort, Cancellable cancel,
467
                        double scale, PrintAttributes properties)
468
        throws ReadException {
469
                this.print_old(g, viewPort, cancel, scale, properties, null);
470
        }
471

    
472
        /**
473
         * <p>Checks all layers (each one as a sub-node of this node <i>collection of layers</i>) of this collection and draws their requested properties. If a node is
474
         *  a group of layers (<code>ComposedLayer</code>), executes it's drawn.</p>
475
         *
476
         * <p>All nodes which could group with the composed layer <code>group</code>, will be drawn together. And once the <code>
477
         * group</code> is drawn, will be set to <code>null</code> if hasn't a parent layer.</p>
478
         *
479
         * <p>The particular implementation depends on the kind of each layer and composed layer. And this process can be cancelled at any
480
         *  time by the shared object <code>cancel</code>.</p>
481
         *
482
         * <p>According the print quality, labels will be printed in different resolution:
483
         *  <ul>
484
         *   <li><b>PrintQuality.DRAFT</b>: 72 dpi (dots per inch).</li>
485
         *   <li><b>PrintQuality.NORMAL</b>: 300 dpi (dots per inch).</li>
486
         *   <li><b>PrintQuality.HIGH</b>: 600 dpi (dots per inch).</li>
487
         *  </ul>
488
         * </p>
489
         *
490
         * @param g for rendering 2-dimensional shapes, text and images on the Java(tm) platform
491
         * @param viewPort the information for drawing the layers
492
         * @param cancel shared object that determines if this layer can continue being drawn
493
         * @param scale the scale of the view. Must be between {@linkplain FLayer#getMinScale()} and {@linkplain FLayer#getMaxScale()}.
494
         * @param properties properties that will be print
495
         * @param group a composed layer pending to paint; if this parameter is <code>null</code>, the composed layer
496
         *
497
         * @return <code>null</code> if the layers in <code>group</code> had been drawn or were <code>null</code>; otherwise, the <code>group</code>
498
         *
499
         * @see FLayer#print(Graphics2D, ViewPort, Cancellable, double, PrintAttributes)
500
         *
501
         * @throws ReadDriverException if fails the driver reading the data.
502
         */
503
        public ComposedLayer print_old(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintAttributes properties, ComposedLayer group)
504
        throws ReadException {
505
                double dpi = 72;
506

    
507
                int resolution = properties.getPrintQuality();
508
                if (resolution == PrintAttributes.PRINT_QUALITY_NORMAL) {
509
                        dpi = 300;
510
                } else if (resolution == PrintAttributes.PRINT_QUALITY_HIGH){
511
                        dpi = 600;
512
                } else if (resolution == PrintAttributes.PRINT_QUALITY_DRAFT){
513
                        dpi = 72;
514
                }
515

    
516
                // TODO: A la hora de imprimir, isWithinScale falla, porque est?
517
                // calculando la escala en pantalla, no para el layout.
518
                // Revisar esto.
519

    
520
                // TODO: We have to check when we have to call the drawLabels method when exists a ComposedLayer group.
521
                for (int i=0; i < layers.size(); i++) {
522
                        FLayer lyr = (FLayer) layers.get(i);
523
                        if (!lyr.isVisible() || !lyr.isWithinScale(scale)) {
524
                                continue;
525
                        }
526

    
527
                        try{
528

    
529
                                ///// CHEMA ComposedLayer
530
                                // Checks for draw group (ComposedLayer)
531
                                if (group != null) {
532
                                        if (lyr instanceof FLayers){
533
                                                group = ((FLayers)lyr).print_old(g, viewPort, cancel,scale,properties,group);
534
                                        } else {
535
                                                // If layer can be added to the group, does it
536
                                                if (lyr instanceof ILabelable
537
                                                                && ((ILabelable) lyr).isLabeled()
538
                                                                && ((ILabelable) lyr).getLabelingStrategy() != null
539
                                                                && ((ILabelable) lyr).getLabelingStrategy().shouldDrawLabels(scale)) {
540
                                                        group.add(lyr);
541
                                                } else {
542
                                                        // draw the 'pending to draw' layer group
543
                                                        group.print(g,viewPort,cancel,scale,properties);
544

    
545
                                                        // gets a new group instance
546
                                                        if (lyr instanceof ILabelable
547
                                                                        && ((ILabelable) lyr).isLabeled()
548
                                                                        && ((ILabelable) lyr).getLabelingStrategy() != null
549
                                                                        && ((ILabelable) lyr).getLabelingStrategy().shouldDrawLabels(scale)) {
550
                                                                group = lyr.newComposedLayer();
551
                                                        } else {
552
                                                                group = null;
553
                                                        }
554
                                                        // if layer hasn't group, draws it inmediately
555
                                                        if (group == null) {
556
                                                                if (lyr instanceof FLayers){
557
                                                                        group = ((FLayers)lyr).print_old(g, viewPort, cancel,scale,properties,group);
558
                                                                } else {
559
                                                                        lyr.print(g, viewPort, cancel,scale,properties);
560
                                                                        if (lyr instanceof ILabelable
561
                                                                                        && ((ILabelable) lyr).isLabeled()
562
                                                                                        && ((ILabelable) lyr).getLabelingStrategy() != null
563
                                                                                        && ((ILabelable) lyr).getLabelingStrategy().shouldDrawLabels(scale)) {
564
                                                                                ILabelable lLayer = (ILabelable) lyr;
565
                                                                                lLayer.drawLabels(null, g, viewPort, cancel, scale, dpi);
566
                                                                        }
567
                                                                }
568
                                                        } else {
569
                                                                // add the layer to the group
570
                                                                group.setMapContext(fmap);
571
                                                                group.add(lyr);
572

    
573
                                                        }
574

    
575
                                                }
576
                                        }
577
                                } else {
578
                                        // gets a new group instance
579
                                        group = lyr.newComposedLayer();
580
                                        // if layer hasn't group, draws it inmediately
581
                                        if (group == null) {
582
                                                if (lyr instanceof FLayers){
583
                                                        group = ((FLayers)lyr).print_old(g, viewPort, cancel,scale,properties,group);
584
                                                } else {
585
                                                        lyr.print(g, viewPort, cancel,scale,properties);
586
                                                        if (lyr instanceof ILabelable && ((ILabelable) lyr).isLabeled()) {
587
                                                                ILabelable lLayer = (ILabelable) lyr;
588

    
589
                                                                lLayer.drawLabels(null, g, viewPort, cancel, scale, dpi);
590
                                                        }
591
                                                }
592
                                        } else {
593
                                                // add the layer to the group
594
                                                group.setMapContext(fmap);
595
                                                group.add(lyr);
596

    
597
                                        }
598
                                }
599
                                ///// CHEMA ComposedLayer
600

    
601
                        } catch (Exception e){
602
                                String mesg = Messages.getString("error_printing_layer")+" "+ lyr.getName() + ": " + e.getMessage();
603
                                fmap.addLayerError(mesg);
604
                                logger.error(mesg, e);
605
                        }
606

    
607
                }
608

    
609
                ///// CHEMA ComposedLayer
610
                if (group != null && this.getParentLayer() == null) {
611
                        //si tenemos un grupo pendiente de pintar, pintamos
612
                        group.print(g, viewPort, cancel,scale,properties);
613
                        group = null;
614

    
615
                }
616
                ///// CHEMA ComposedLayer
617

    
618
                //                if (getVirtualLayers() != null) {
619
                //                        getVirtualLayers().print( g, viewPort, cancel, scale, properties);
620
                //                }
621

    
622
                ///// CHEMA ComposedLayer
623
                return group;
624
                ///// CHEMA ComposedLayer
625
        }
626

    
627
        /*
628
         * (non-Javadoc)
629
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
630
         */
631
        public Envelope getFullEnvelope() {
632
                Envelope rAux = null;
633
                boolean first = true;
634

    
635

    
636
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
637
                        FLayer capa = (FLayer) iter.next();
638
                        try{
639
                                if (first) {
640
                                        rAux = capa.getFullEnvelope();
641
                                        first=false;
642
                                } else {
643
                                        rAux.add(capa.getFullEnvelope());
644
                                }
645
                        }catch (Exception e) {
646
                                e.printStackTrace();//TODO hay que revisar para determinar el comportamiento que espera el usuario.
647
                        }
648
                }
649

    
650
                return rAux;
651
        }
652

    
653
        /**
654
         * Notifies all listeners associated to this collection of layers,
655
         *  that another layer is going to be added or replaced in the internal
656
         *  list of layers.
657
         *
658
         * @param e a layer collection event with the new layer
659
         */
660
        protected void callLayerAdding(LayerCollectionEvent event)
661
        throws CancelationException {
662
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
663
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
664
                        ((LayerCollectionListener) iter.next()).layerAdding(event);
665
                }
666
        }
667

    
668
        /**
669
         * Notifies all listeners associated to this collection of layers,
670
         *  that a layer is going to be removed from the internal list of layers.
671
         *
672
         * @param event a layer collection event with the layer being removed
673
         *
674
         * @throws CancelationException any exception produced during the cancellation of the driver.
675
         */
676
        protected void callLayerRemoving(LayerCollectionEvent event)
677
        throws CancelationException {
678
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
679
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
680
                        ((LayerCollectionListener) iter.next()).layerRemoving(event);
681
                }
682
        }
683

    
684
        /**
685
         * Notifies all listeners associated to this collection of layers,
686
         *  that a layer is going to be moved in the internal list of layers.
687
         *
688
         * @param event a layer collection event with the layer being moved, and the initial and final positions
689
         *
690
         * @throws CancelationException any exception produced during the cancellation of the driver.
691
         */
692
        protected void callLayerMoving(LayerPositionEvent event)
693
        throws CancelationException {
694
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
695
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
696
                        ((LayerCollectionListener) iter.next()).layerMoving(event);
697
                }
698
        }
699

    
700
        /**
701
         * Notifies all listeners associated to this collection of layers,
702
         *  that another layer has been added or replaced in the internal
703
         *  list of layers.
704
         *
705
         * @param e a layer collection event with the new layer
706
         */
707
        protected void callLayerAdded(LayerCollectionEvent event) {
708
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
709
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
710
                        ((LayerCollectionListener) iter.next()).layerAdded(event);
711
                }
712
        }
713

    
714
        /**
715
         * Notifies all listeners associated to this collection of layers,
716
         *  that another layer has been removed from the internal list of layers.
717
         *
718
         * @param e a layer collection event with the layer removed
719
         */
720
        protected void callLayerRemoved(LayerCollectionEvent event) {
721
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
722
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
723
                        ((LayerCollectionListener) iter.next()).layerRemoved(event);
724
                }
725
        }
726

    
727
        /**
728
         * Notifies all listeners associated to this collection of layers,
729
         *  that another layer has been moved in the internal list of layers.
730
         *
731
         * @param e a layer collection event with the layer moved, and the initial and final positions
732
         */
733
        protected void callLayerMoved(LayerPositionEvent event) {
734
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
735
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
736
                        ((LayerCollectionListener) iter.next()).layerMoved(event);
737
                }
738
        }
739

    
740
        public void saveToState(PersistentState state) throws PersistenceException {
741
                
742
                super.saveToState(state);
743
                
744
                state.set("mapContext", fmap);
745
                state.set("layers", layers);
746
        }
747

    
748
        public void loadFromState(PersistentState state) throws PersistenceException {
749

    
750
                super.loadFromState(state);
751

    
752
                setMapContext((MapContext) state.get("mapContext"));
753
                Iterator iter = state.getIterator("layers");
754
                while (iter.hasNext()) {
755
                        FLayer item = (FLayer) iter.next();
756
                        layers.add(item); 
757
                }
758
        }
759
        
760
        /*
761
         * (non-Javadoc)
762
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getMapContext()
763
         */
764
        public MapContext getMapContext() {
765
                return fmap;
766
        }
767
        /*
768
         * (non-Javadoc)
769
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setCoordTrans(org.cresques.cts.ICoordTrans)
770
         */
771
        public void setCoordTrans(ICoordTrans ct) {
772
                super.setCoordTrans(ct);
773

    
774
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
775
                        FLayer layer = (FLayer) iter.next();
776
                        layer.setCoordTrans(ct);
777
                }
778
        }
779
        /*
780
         * (non-Javadoc)
781
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#setAllActives(boolean)
782
         */
783
        public void setAllActives(boolean active) {
784
                FLayer lyr;
785

    
786
                for (int i = 0; i < layers.size(); i++) {
787
                        lyr = ((FLayer) layers.get(i));
788
                        lyr.setActive(active);
789

    
790
                        if (lyr instanceof LayerCollection) {
791
                                ((LayerCollection) lyr).setAllActives(active);
792
                        }
793
                }
794
        }
795

    
796
        /*
797
         * (non-Javadoc)
798
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getActives()
799
         */
800
        public FLayer[] getActives() {
801
                ArrayList ret = new ArrayList();
802
                LayersIterator it = new LayersIterator(this) {
803

    
804
                        public boolean evaluate(FLayer layer) {
805
                                return layer.isActive();
806
                        }
807

    
808
                };
809

    
810
                while (it.hasNext())
811
                {
812
                        ret.add(it.next());
813
                }
814
                return (FLayer[]) ret.toArray(new FLayer[0]);
815
        }
816

    
817
        /*
818
         * (non-Javadoc)
819
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getMinScale()
820
         */
821
        public double getMinScale() {
822
                return -1; // La visibilidad o no la controla cada capa
823
                // dentro de una colecci?n
824
        }
825
        /*
826
         * (non-Javadoc)
827
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getMaxScale()
828
         */
829
        public double getMaxScale() {
830
                return -1;
831
        }
832
        /*
833
         * (non-Javadoc)
834
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setMinScale(double)
835
         */
836
        public void setMinScale(double minScale)
837
        {
838
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
839
                        FLayer lyr = (FLayer) iter.next();
840
                        lyr.setMinScale(minScale);
841
                }
842
        }
843
        /*
844
         * (non-Javadoc)
845
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setMaxScale(double)
846
         */
847
        public void setMaxScale(double maxScale)
848
        {
849
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
850
                        FLayer lyr = (FLayer) iter.next();
851
                        lyr.setMinScale(maxScale);
852
                }
853
        }
854
        /*
855
         * (non-Javadoc)
856
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setActive(boolean)
857
         */
858
        public void setActive(boolean b){
859
                super.setActive(b);
860
                for (int i=0;i<layers.size();i++){
861
                        ((FLayer)layers.get(i)).setActive(b);
862
                }
863
        }
864
        /* (non-Javadoc)
865
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#addLayerListener(com.iver.cit.gvsig.fmap.layers.LayerListener)
866
         */
867
        public boolean addLayerListener(LayerListener o) {
868
                for (int i = 0; i < layers.size(); i++) {
869
                        ((FLayer) layers.get(i)).addLayerListener(o);
870
                }
871
                return true;
872
        }
873
        /*
874
         * (non-Javadoc)
875
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
876
         */
877
//        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws LoadLayerException, DataException {
878
//                int i;
879
//                Vector items = new Vector();
880
//                FLayer layer;
881
//                XMLItem[] aux;
882
//                for (i = 0; i < this.layers.size(); i++){
883
//                        layer = (FLayer)layers.get(i);
884
//                        if (layer instanceof InfoByPoint){
885
//                                InfoByPoint queryable_layer = (InfoByPoint) layer;
886
//                                aux = queryable_layer.getInfo(p, tolerance, null);
887
//                                if (!(queryable_layer instanceof FLayers)){
888
//                                        for(int j = 0; j < aux.length; j++){
889
//                                                items.add(aux[j]);
890
//                                        }
891
//                                }
892
//                        }
893
//                }
894
//                return (XMLItem[])items.toArray(new XMLItem[0]);
895
//
896
//        }
897
        public Iterator getInfo(Point p, double tolerance,
898
                        Cancellable cancel) throws LoadLayerException, DataException {
899
                int i;
900
                FLayer layer;
901
                ArrayList res = new ArrayList();
902
                for (i = 0; i < this.layers.size(); i++){
903
                        layer = (FLayer)layers.get(i);
904
                        if (layer instanceof InfoByPoint){
905
                                InfoByPoint queryable_layer = (InfoByPoint) layer;
906
                                Iterator it = queryable_layer.getInfo(p, tolerance, null);
907
                                // Please be careful we add iterators, not the Dynobjects
908
                                // we don't make the list flat so trees are supported
909
                                res.add(it);
910
                        }
911
                }
912
                return res.iterator();
913
                
914
        }
915
        
916
        
917
        /*
918
         * (non-Javadoc)
919
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
920
         */
921
        public String getTocImageIcon() {
922
                return "toc-layer-group";
923
        }
924

    
925
        /**
926
         * <p>Adds the layer with the information in an XML entity and the specified name, to this collection of layers. And
927
         *  returns <code>true</code> if there hasn't been errors.</p>
928
         *
929
         * @see CopyOfFLayers#addLayerFromXML(XMLEntity, String)
930
         *
931
         * @param xml tree-node structure with information about layers
932
         * @param name name of the layer to add
933
         * @return <code>true</code> if there were no errors adding the layer, <code>false</code> otherwise
934
         *
935
         * @throws LoadLayerException if fails loading this layer.
936
         */
937
        //        public boolean addLayerFromXMLEntity(XMLEntity xml, String name) throws LoadLayerException {
938
        //                fmap.clearErrors();
939
        //                this.addLayerFromXML(xml,name);
940
        //
941
        //                return (fmap.getLayersError().size() == 0);
942
        //
943
        //        }
944

    
945
//        /**
946
//         * <p>Adds the layer with the information in an XML entity and the specified name, to this collection of layers.</p>
947
//         *
948
//         * <p>This method really executes the addition, considering the kind of layer (<code>FLyrVect</code>,
949
//         *  <code>FLyrAnnotation</code>, <code>FLyrRaster</code>, a collection of layers (<code>FLayers</code>),
950
//         *  or another kind of layer (<code>FLayer</code>)), and the driver in the layer.</p>
951
//         *
952
//         * @param xml tree-node structure with information about layers
953
//         * @param name name of the layer to add
954
//         *
955
//         * @throws LoadLayerException if fails loading this layer.
956
//         */
957
//        private void addLayerFromXML(XMLEntity xml, String name) throws LoadLayerException {
958
//                FLayer layer = null;
959
//
960
//                try {
961
//                        if (name == null) {
962
//                                name = xml.getName();
963
//                        }
964
//
965
//
966
//                        String className = xml.getStringProperty("className");
967
//                        Class clase = Class.forName(className);
968
//                        layer = (FLayer) clase.newInstance();
969
//                        if (FLayers.class.isAssignableFrom(clase)) {
970
//                                ((FLayers)layer).setMapContext(getMapContext());
971
//                                ((FLayers)layer).setParentLayer(this);
972
//                                //                        layer = new FLayers(getMapContext(),this);
973
//                                layer.setXMLEntity(xml);
974
//                        } else {
975
//                                // Capas Nuevas (externas)
976
//                                layer.setName(name);
977
//                                layer.setXMLEntity(xml);
978
//                                layer.load();
979
//                        }
980
//
981
//                        //                //TODO VCN FLyrAnnotation es un parche para no tener que duplicar todo el c?digo de aq? y de los diferentes m?todos de LayerFactory,
982
//                        //                //ya que los drivers de una FLyrAnnotation no sabemos cual es puede ser cualquier Driver Vectorial.
983
//                        //                if (className.equals(FLyrVect.class.getName())){// || className.equals(FLyrAnnotation.class.getName())) {
984
//                        //                        String type = xml.getStringProperty("type");
985
//                        //                        if ("vectorial".equals(type)){
986
//                        //                                //String recordsetName = xml.getChild(i).getStringProperty("recordset-name");
987
//                        //                                IProjection proj = null;
988
//                        //                                if (xml.contains("proj")) {
989
//                        //                                        proj = CRSFactory.getCRS(xml.getStringProperty("proj"));
990
//                        //                                }
991
//                        //                                else
992
//                        //                                {
993
//                        //                                        proj = this.getMapContext().getViewPort().getProjection();
994
//                        //                                }
995
//                        //                                if (xml.contains("file")) {
996
//                        //                                        Driver d;
997
//                        //                                        try {
998
//                        //                                                d = LayerFactory.getDM().getDriver(xml.getStringProperty("driverName"));
999
//                        //                                        } catch (DriverLoadException e1) {
1000
//                        //                                                throw new DriverLayerException(name,e1);
1001
//                        //                                        }
1002
//                        //                                        layer = LayerFactory.createLayer(name, (VectorialFileDriver) d,
1003
//                        //                                                        new File(xml.getStringProperty("file")),
1004
//                        //                                                        proj);
1005
//                        //
1006
//                        //
1007
//                        //                                }
1008
//                        //                                if (xml.contains("db")) {
1009
//                        //
1010
//                        //                                        String driverName = xml.getStringProperty("db");
1011
//                        //                                        IVectorialDatabaseDriver driver;
1012
//                        //                                        try {
1013
//                        //                                                driver = (IVectorialDatabaseDriver) LayerFactory.getDM().getDriver(driverName);
1014
//                        //                                                //Hay que separar la carga de los datos del XMLEntity del load.
1015
//                        //                                                driver.setXMLEntity(xml.getChild(2));
1016
//                        //
1017
//                        //                                                boolean loadOk = false;
1018
//                        //                                                ((DefaultJDBCDriver)driver).load();
1019
//                        //                                                if (((DefaultJDBCDriver)driver).getConnection() != null) {
1020
//                        //                                                        loadOk = true;
1021
//                        //                                                }
1022
//                        //                                                layer = LayerFactory.createDBLayer(driver, name, proj);
1023
//                        //                                                if (!loadOk) {
1024
//                        //                                                        layer.setAvailable(false);
1025
//                        //                                                }
1026
//                        //
1027
//                        //                                        } catch (DriverLoadException e) {
1028
//                        //                                                throw new DriverLayerException(name,e);
1029
//                        //                                        } catch (XMLException e) {
1030
//                        //                                                throw new DriverLayerException(name,e);
1031
//                        //                                        } catch (ReadException e) {
1032
//                        //                                                throw new DriverLayerException(name,e);
1033
//                        //                                        }
1034
//                        //
1035
//                        //                                }
1036
//                        //                                // Clases con algun driver gen?rico creado por otro
1037
//                        //                                // programador
1038
//                        //                                if (xml.contains("other")) {
1039
//                        //
1040
//                        //                                        String driverName = xml.getStringProperty("other");
1041
//                        //                                        VectorialDriver driver = null;
1042
//                        //                                        try {
1043
//                        //                                                driver = (VectorialDriver) LayerFactory.getDM().getDriver(driverName);
1044
//                        //                                        } catch (DriverLoadException e) {
1045
//                        //                                                // Si no existe ese driver, no pasa nada.
1046
//                        //                                                // Puede que el desarrollador no quiera que
1047
//                        //                                                // aparezca en el cuadro de di?logo y ha metido
1048
//                        //                                                // el jar con sus clases en nuestro directorio lib.
1049
//                        //                                                // Intentamos cargar esa clase "a pelo".
1050
//                        //                                                if (xml.getChild(2).contains("className"))
1051
//                        //                                                {
1052
//                        //                                                        String className2 = xml.getChild(2).getStringProperty("className");
1053
//                        //                                                        try {
1054
//                        //                                                                driver = (VectorialDriver) Class.forName(className2).newInstance();
1055
//                        //                                                        } catch (Exception e1) {
1056
//                        //                                                                throw new DriverLayerException(name,e);
1057
//                        //                                                        }
1058
//                        //                                                }
1059
//                        //                                        } catch (NullPointerException npe) {
1060
//                        //                                                // Si no existe ese driver, no pasa nada.
1061
//                        //                                                // Puede que el desarrollador no quiera que
1062
//                        //                                                // aparezca en el cuadro de di?logo y ha metido
1063
//                        //                                                // el jar con sus clases en nuestro directorio lib.
1064
//                        //                                                // Intentamos cargar esa clase "a pelo".
1065
//                        //                                                if (xml.getChild(2).contains("className"))
1066
//                        //                                                {
1067
//                        //                                                        String className2 = xml.getChild(2).getStringProperty("className");
1068
//                        //                                                        try {
1069
//                        //                                                                driver = (VectorialDriver) Class.forName(className2).newInstance();
1070
//                        //                                                        } catch (Exception e1) {
1071
//                        //                                                                throw new DriverLayerException(name,e1);
1072
//                        //                                                        }
1073
//                        //                                                }
1074
//                        //                                        }
1075
//                        //                                        if (driver instanceof IPersistence)
1076
//                        //                                        {
1077
//                        //                                                IPersistence persist = (IPersistence) driver;
1078
//                        //                                                persist.setXMLEntity(xml.getChild(2));
1079
//                        //                                        }
1080
//                        //                                        layer = LayerFactory.createLayer(name, driver, proj);
1081
//                        //                                }
1082
//                        //
1083
//                        //                        }
1084
//                        //
1085
//                        //                        //TODO VCN FLyrAnnotation es un parche para no tener que duplicar todo el c?digo de aq? y de los diferentes m?todos de LayerFactory,
1086
//                        //                        //ya que los drivers de una FLyrAnnotation no sabemos cual es puede ser cualquier Driver Vectorial.
1087
//                        //                        if (className.equals(FLyrAnnotation.class.getName())){
1088
//                        //                                layer=FLyrAnnotation.createLayerFromVect((FLyrVect)layer);
1089
//                        //                        }
1090
//                        //
1091
//                        //
1092
//                        //                        layer.setXMLEntity(xml);
1093
//                        //
1094
//                        //                } else {
1095
//                        //                        Class clase = LayerFactory.getLayerClassForLayerClassName(className);
1096
//                        //                        layer = (FLayer) clase.newInstance();
1097
//                        //                        if (clase.isAssignableFrom(FLayers.class)) {
1098
//                        //                                ((FLayers)layer).setMapContext(getMapContext());
1099
//                        //                                ((FLayers)layer).setParentLayer(this);
1100
//                        ////                                layer = new FLayers(getMapContext(),this);
1101
//                        //                                layer.setXMLEntity(xml);
1102
//                        //                        } else {
1103
//                        //                                // Capas Nuevas (externas)
1104
//                        //                                layer.setName(name);
1105
//                        //                                layer.setXMLEntity(xml);
1106
//                        //                                layer.load();
1107
//                        //                        }
1108
//                        //                }
1109
//                        this.addLayer(layer);
1110
//                        logger.debug("layer: "+ layer.getName() +" loaded");
1111
//                        // Comprobar que la proyecci?n es la misma que la de FMap
1112
//                        // Si no lo es, es una capa que est? reproyectada al vuelo
1113
//                        IProjection proj = layer.getProjection();
1114
//                        if ((proj != null)) {
1115
//                                if (!proj.getFullCode().equals(getMapContext().getProjection().getFullCode()))
1116
//                                {
1117
//                                        ICoordTrans ct = proj.getCT(getMapContext().getProjection());
1118
//                                        // TODO: REVISAR CON LUIS
1119
//                                        // Se lo fijamos a todas, luego cada una que se reproyecte
1120
//                                        // si puede, o que no haga nada
1121
//
1122
//                                        layer.setCoordTrans(ct);
1123
//                                }
1124
//                        }
1125
//                } catch (XMLException e) {
1126
//                        fmap.addLayerError(xml.getStringProperty("name"));
1127
//                        throw new LoadLayerException(name,e);
1128
//                } catch (ClassNotFoundException e) {
1129
//                        fmap.addLayerError(xml.getStringProperty("name"));
1130
//                        throw new LoadLayerException(name,e);
1131
//                } catch (InstantiationException e) {
1132
//                        fmap.addLayerError(xml.getStringProperty("name"));
1133
//                        throw new LoadLayerException(name,e);
1134
//                } catch (IllegalAccessException e) {
1135
//                        fmap.addLayerError(xml.getStringProperty("name"));
1136
//                        throw new LoadLayerException(name,e);
1137
//                } catch (LoadLayerException e){
1138
//                        fmap.addLayerError(xml.getStringProperty("name"));
1139
//                        throw e;
1140
//                }
1141
//        }
1142

    
1143
        /**
1144
         * <p>Sets the <code>MapContext</code> that contains this layer node.</p>
1145
         *
1146
         * @param mapContext the <code>MapContext</code> that contains this layer node
1147
         */
1148
        public void setMapContext(MapContext mapContext) {
1149
                this.fmap = mapContext;
1150
        }
1151

    
1152
//        /**
1153
//         * <p>Creates a new layer of the same class as the property <i>className</i> of the XML, after, adds the XML entity to that layer
1154
//         *  and loads the layer. Then, adds the layer to this collection of layers, and if there is a projection defined,
1155
//         *  inserts the transformation coordinates to the layer.</p>
1156
//         *
1157
//         * <p>If the new layer is an instance of <code>FLyrVect</code>, and has a label field, creates a label layer on the layer.</p>
1158
//         *
1159
//         * @param xml tree-node structure with information about layers
1160
//         * @param name name of the layer to add
1161
//         */
1162
//        private void addLayerFromXMLNew(XMLEntity xml, String name) {
1163
//                //                FLayer layer = null;
1164
//                //
1165
//                //
1166
//                //                try {
1167
//                //                        String className = xml.getStringProperty("className");
1168
//                //                        Class clazz = Class.forName(className);
1169
//                //                        if (clazz.isAssignableFrom(FLayers.class)) {
1170
//                //                                layer = (FLayer) clazz.newInstance();
1171
//                //                                ((FLayers)layer).setMapContext(getMapContext());
1172
//                //                                ((FLayers)layer).setParentLayer(this);
1173
//                //        //                if (className.equals((FLayers.class.getName()))){
1174
//                //        //                        layer = new FLayers(getMapContext(),this);
1175
//                //                        } else {
1176
//                //        //                        Por compatibilidad
1177
//                //                                if (className.equals(FLyrVect.class.getName())) {
1178
//                //                                        if (xml.contains("file")) {
1179
//                //                                                layer = new FLayerFileVectorial();
1180
//                //                                        } else if (xml.contains("db")) {
1181
//                //                                                try {
1182
//                //                                                        layer = (FLayer)((ExtensionPoint)ExtensionPointsSingleton.getInstance().get("Layers")).create("com.iver.cit.gvsig.fmap.layers.FLayerJDBCVectorial");
1183
//                //                                                } catch (Exception e) {
1184
//                //                                                        throw new XMLException(new Exception("No se tiene registrada la capa de tipo JDBC"));
1185
//                //                                                }
1186
//                //                                                //className = FLayerJDBCVectorial.class.getName();
1187
//                //                                        } else if (xml.contains("other")){
1188
//                //                                                layer = new FLayerGenericVectorial();
1189
//                //                                        } else {
1190
//                //                                                throw new XMLException(new Exception("Capa vectorial de tipo no reconocido"));
1191
//                //                                        }
1192
//                //        //                                Fin por compatibilidad
1193
//                //                                } else {
1194
//                //                                        try {
1195
//                //                                                layer = (FLayer)(((ExtensionPoint)ExtensionPointsSingleton.getInstance().get("Layers")).create(className));
1196
//                //                                        } catch (Exception e) {
1197
//                //                                                //puende que no este registrada como punto de extension
1198
//                //                                                Class clase = Class.forName(className);
1199
//                //                                                layer = (FLayer) clase.newInstance();
1200
//                //                                                // FIXME: Hacemos algo aqui o dejamos que suba el error?
1201
//                //                                        }
1202
//                //                                }
1203
//                //
1204
//                //                        }
1205
//                //                        layer.setXMLEntity(xml);
1206
//                //                        if (name != null) layer.setName(name);
1207
//                //                        layer.load();
1208
//                //
1209
//                //                        this.addLayer(layer);
1210
//                //                        logger.debug("layer: "+ layer.getName() +" loaded");
1211
//                //                        // Comprobar que la proyecci?n es la misma que la de FMap
1212
//                //                        // Si no lo es, es una capa que est? reproyectada al vuelo
1213
//                //                        IProjection proj = layer.getProjection();
1214
//                //                        if ((proj != null))
1215
//                //                                if (proj != getMapContext().getProjection())
1216
//                //                                {
1217
//                //                                        ICoordTrans ct = proj.getCT(getMapContext().getProjection());
1218
//                //                                        // TODO: REVISAR CON LUIS
1219
//                //                                        // Se lo fijamos a todas, luego cada una que se reproyecte
1220
//                //                                        // si puede, o que no haga nada
1221
//                //                                        layer.setCoordTrans(ct);
1222
//                //
1223
//                //                                }
1224
//                //                }catch (Exception e) {
1225
//                //                        fmap.addLayerError(xml.getStringProperty("name"));
1226
//                //                        logger.debug(Messages.getString("could_not_load_layer")+": "+xml.getStringProperty("name") + ".\n"
1227
//                //                                        +Messages.getString("reason")+":", e);
1228
//                //                }
1229
//        }
1230

    
1231
        public void accept(Visitor visitor) throws BaseException {
1232
                throw new NotSupportedOperationException(visitor, this);
1233
        }
1234

    
1235
        public void accept(LayersVisitor visitor) throws BaseException {
1236
                for (int i = 0; i < this.getLayersCount(); i++) {
1237
                        FLayer layer = this.getLayer(i);
1238
                        if (layer instanceof LayersVisitable) {
1239
                                ((LayersVisitable) layer).accept(visitor);
1240
                        } else {
1241
                                visitor.visit(layer);
1242
                        }
1243
                }
1244
        }
1245

    
1246
        /*
1247
         * (non-Javadoc)
1248
         *
1249
         * @see org.gvsig.metadata.Metadata#getMetadataID()
1250
         */
1251
        public Object getMetadataID() throws MetadataException {
1252
                StringBuffer strb = new StringBuffer();
1253
                strb.append("Layers(");
1254
                strb.append(this.getName());
1255
                strb.append("):{");
1256
                Iterator iter = this.layers.iterator();
1257
                while (iter.hasNext()) {
1258
                        strb.append(((FLayer) iter.next()).getMetadataID());
1259
                        strb.append(",");
1260
                }
1261
                strb.append("}");
1262
                return strb.toString();
1263

    
1264
        }
1265

    
1266
        /*
1267
         * (non-Javadoc)
1268
         *
1269
         * @see org.gvsig.metadata.Metadata#getMetadataChildren()
1270
         */
1271
        public Set getMetadataChildren() {
1272
                Set ret = new TreeSet();
1273
                Iterator iter = this.layers.iterator();
1274
                while (iter.hasNext()) {
1275
                        ret.add(iter.next());
1276
                }
1277
                return ret;
1278
        }
1279

    
1280
        /*
1281
         * (non-Javadoc)
1282
         *
1283
         * @see org.gvsig.metadata.Metadata#getMetadataName()
1284
         */
1285
        public String getMetadataName() throws MetadataException {
1286
                StringBuffer strb = new StringBuffer();
1287
                strb.append("Layer Group '");
1288
                strb.append(this.getName());
1289
                strb.append("': {");
1290
                Iterator iter = this.layers.iterator();
1291
                while (iter.hasNext()) {
1292
                        strb.append(((FLayer) iter.next()).getMetadataName());
1293
                        strb.append(",");
1294
                }
1295
                strb.append("}");
1296
                return strb.toString();
1297
        }
1298

    
1299

    
1300
        public void beginDraw(Graphics2D g, ViewPort viewPort) {
1301
                LayerDrawEvent beforeEvent = new LayerDrawEvent(this, g, viewPort, LayerDrawEvent.LAYER_BEFORE_DRAW);
1302
                fmap.fireLayerDrawingEvent(beforeEvent);
1303
        }
1304

    
1305
        public void endDraw(Graphics2D g, ViewPort viewPort) {
1306
                LayerDrawEvent afterEvent = new LayerDrawEvent(this, g, viewPort, LayerDrawEvent.LAYER_AFTER_DRAW);
1307
                fmap.fireLayerDrawingEvent(afterEvent);
1308
        }
1309

    
1310
        public static void registerPersistent() {
1311
                
1312
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
1313
                if( manager.getDefinition(FLyrDefault.class) == null ) {
1314
                        FLyrDefault.registerPersistent();
1315
                }
1316
                DynStruct definition = manager.addDefinition(
1317
                                FLayers.class,
1318
                                "FLayers",
1319
                                "FLayers Persistence definition",
1320
                                null, 
1321
                                null
1322
                );
1323
                definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE, "FLyrDefault");
1324
                
1325
                definition.addDynFieldObject("mapContext").setClassOfValue(MapContext.class).setMandatory(true);
1326
                definition.addDynFieldList("layers").setClassOfItems(FLayer.class).setMandatory(true);
1327
        }
1328

    
1329
        protected void doDispose() throws BaseException {
1330
                if (layers != null) {
1331
                        for (int i = 0; i < layers.size(); i++) {
1332
                                dispose((Disposable) layers.get(i));
1333
                        }
1334
                }
1335
        }
1336
}