Statistics
| Revision:

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

History | View | Annotate | Download (44 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
import java.util.Vector;
53

    
54
import javax.print.attribute.PrintRequestAttributeSet;
55
import javax.print.attribute.standard.PrintQuality;
56
import javax.swing.ImageIcon;
57

    
58
import org.cresques.cts.ICoordTrans;
59
import org.cresques.cts.IProjection;
60
import org.gvsig.fmap.dal.exception.DataException;
61
import org.gvsig.fmap.dal.exception.ReadException;
62
import org.gvsig.fmap.geom.primitive.Envelope;
63
import org.gvsig.fmap.mapcontext.MapContext;
64
import org.gvsig.fmap.mapcontext.Messages;
65
import org.gvsig.fmap.mapcontext.ViewPort;
66
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
67
import org.gvsig.fmap.mapcontext.exceptions.XMLLayerException;
68
import org.gvsig.fmap.mapcontext.layers.operations.ComposedLayer;
69
import org.gvsig.fmap.mapcontext.layers.operations.ILabelable;
70
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
71
import org.gvsig.fmap.mapcontext.layers.operations.LayerCollection;
72
import org.gvsig.fmap.mapcontext.layers.operations.LayersVisitable;
73
import org.gvsig.fmap.mapcontext.layers.operations.LayersVisitor;
74
import org.gvsig.fmap.mapcontext.layers.operations.XMLItem;
75
import org.gvsig.tools.exception.BaseException;
76
import org.gvsig.tools.task.Cancellable;
77
import org.gvsig.tools.visitor.NotSupportedOperationException;
78
import org.gvsig.tools.visitor.Visitor;
79
import org.slf4j.Logger;
80
import org.slf4j.LoggerFactory;
81

    
82
import com.iver.utiles.XMLEntity;
83
import com.iver.utiles.XMLException;
84

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

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

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

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

    
141
        /*
142
         * (non-Javadoc)
143
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#addLayerCollectionListener(com.iver.cit.gvsig.fmap.layers.LayerCollectionListener)
144
         */
145
        public void addLayerCollectionListener(LayerCollectionListener listener) {
146
                if (!layerCollectionListeners.contains(listener)) {
147
                        layerCollectionListeners.add(listener);
148
                }
149
        }
150

    
151
        /*
152
         * (non-Javadoc)
153
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#setAllVisibles(boolean)
154
         */
155
        public void setAllVisibles(boolean visible) {
156
                FLayer lyr;
157

    
158
                for (int i = 0; i < layers.size(); i++) {
159
                        lyr = ((FLayer) layers.get(i));
160
                        lyr.setVisible(visible);
161

    
162
                        if (lyr instanceof LayerCollection) {
163
                                ((LayerCollection) lyr).setAllVisibles(visible);
164
                        }
165
                }
166
        }
167

    
168
        /*
169
         * (non-Javadoc)
170
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayerCollectionListener(com.iver.cit.gvsig.fmap.layers.LayerCollectionListener)
171
         */
172
        public void removeLayerCollectionListener(LayerCollectionListener listener) {
173
                layerCollectionListeners.remove(listener);
174
        }
175

    
176
        /**
177
         * Adds a layer on an specified position in this node.
178
         *
179
         * @param pos position in the inner list where the layer will be added
180
         * @param layer a layer
181
         */
182
        private void doAddLayer(int pos,FLayer layer) {
183
                layers.add(pos,layer);
184
                layer.setParentLayer(this);
185
                if(layer.getProjection() != null && fmap != null) {
186
                        layer.setCoordTrans(layer.getProjection().getCT(fmap.getProjection()));
187
                }
188
                this.updateDrawVersion();
189
        }
190

    
191
        /*
192
         * (non-Javadoc)
193
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#addLayer(com.iver.cit.gvsig.fmap.layers.FLayer)
194
         */
195
        public void addLayer(FLayer layer) {
196
                addLayer(layers.size(),layer);
197
        }
198

    
199
        /**
200
         * Adds a layer in an specified position in this node.
201
         *
202
         * @param layer a layer
203
         */
204
        public void addLayer(int pos,FLayer layer) {
205
                try {
206
                        //Notificamos a la capa que va a ser a?adida
207
                        if (layer instanceof FLyrDefault) {
208
                                ((FLyrDefault)layer).wakeUp();
209
                        }
210

    
211
                        if (layer instanceof FLayers){
212
                                FLayers layers=(FLayers)layer;
213
                                fmap.addAsCollectionListener(layers);
214
                        }
215
                        callLayerAdding(LayerCollectionEvent.createLayerAddingEvent(layer));
216

    
217
                        doAddLayer(pos,layer);
218

    
219
                        callLayerAdded(LayerCollectionEvent.createLayerAddedEvent(layer));
220
                } catch (CancelationException e) {
221
                        logger.warn(e.getMessage());
222
                } catch (LoadLayerException e) {
223
                        layer.setAvailable(false);
224
                        layer.addError(e);
225
                }
226
        }
227

    
228
        /*
229
         * (non-Javadoc)
230
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#moveTo(int, int)
231
         */
232
        public void moveTo(int from, int to) throws CancelationException {
233
                int newfrom=layers.size()-from-1;
234
                int newto=layers.size()-to-1;
235
                if ( newfrom < 0 || newfrom >=layers.size() || newto < 0 || newto >= layers.size()) {
236
                        return;
237
                }
238
                FLayer aux = (FLayer) layers.get(newfrom);
239
                callLayerMoving(LayerPositionEvent.createLayerMovingEvent(aux, newfrom, newto));
240
                layers.remove(newfrom);
241
                layers.add(newto, aux);
242
                this.updateDrawVersion();
243
                callLayerMoved(LayerPositionEvent.createLayerMovedEvent(aux, newfrom, newto));
244
        }
245

    
246
        /**
247
         * Removes an inner layer.
248
         *
249
         * @param lyr a layer
250
         */
251
        private void doRemoveLayer(FLayer lyr) {
252
                layers.remove(lyr);
253
                this.updateDrawVersion();
254
        }
255

    
256
        /*
257
         * (non-Javadoc)
258
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(com.iver.cit.gvsig.fmap.layers.FLayer)
259
         */
260
        public void removeLayer(FLayer lyr) throws CancelationException {
261
                callLayerRemoving(LayerCollectionEvent.createLayerRemovingEvent(lyr));
262
                doRemoveLayer(lyr);
263
                callLayerRemoved(LayerCollectionEvent.createLayerRemovedEvent(lyr));
264
        }
265

    
266
        /*
267
         * (non-Javadoc)
268
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(int)
269
         */
270
        public void removeLayer(int idLayer) {
271
                FLayer lyr = (FLayer) layers.get(idLayer);
272
                callLayerRemoving(LayerCollectionEvent.createLayerRemovingEvent(lyr));
273
                layers.remove(idLayer);
274
                this.updateDrawVersion();
275
                callLayerRemoved(LayerCollectionEvent.createLayerRemovedEvent(lyr));
276
        }
277

    
278
        /*
279
         * (non-Javadoc)
280
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(java.lang.String)
281
         */
282
        public void removeLayer(String layerName) {
283
                FLayer lyr;
284

    
285
                for (int i = 0; i < layers.size(); i++) {
286
                        lyr = ((FLayer) layers.get(i));
287

    
288
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
289
                                removeLayer(i);
290

    
291
                                break;
292
                        }
293
                }
294
        }
295

    
296
        /**
297
         * Replace a layer identified by its name, by another.
298
         *
299
         * @param layerName the name of the layer to be replaced
300
         * @param layer the new layer
301
         */
302
        public void replaceLayer(String layerName, FLayer layer) throws LoadLayerException
303
        {
304
                FLayer lyr;
305
                FLayer parent;
306
                for (int i = 0; i < layers.size(); i++) {
307
                        lyr = ((FLayer) layers.get(i));
308

    
309
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
310
                                parent = lyr.getParentLayer();
311
                                removeLayer(i);
312
                                if (parent != null) {
313
                                        //Notificamos a la capa que va a ser a?adida
314
                                        if (layer instanceof FLyrDefault) {
315
                                                ((FLyrDefault)layer).wakeUp();
316
                                        }
317
                                }
318

    
319
                                if (layer instanceof FLayers){
320
                                        FLayers layers=(FLayers)layer;
321
                                        fmap.addAsCollectionListener(layers);
322
                                }
323
                                callLayerAdding(LayerCollectionEvent.createLayerAddingEvent(layer));
324

    
325
                                layers.add(i,layer);
326
                                layer.setParentLayer(this);
327

    
328
                                callLayerAdded(LayerCollectionEvent.createLayerAddedEvent(layer));
329
                                break;
330
                        }
331
                }
332
        }
333

    
334
        /*
335
         * (non-Javadoc)
336
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getVisibles()
337
         */
338
        public FLayer[] getVisibles() {
339
                ArrayList array = new ArrayList();
340
                LayersIterator iter = new LayersIterator(this) {
341
                        public boolean evaluate(FLayer layer) {
342
                                return layer.isVisible();
343
                        }
344

    
345
                };
346

    
347
                while (iter.hasNext()) {
348
                        array.add(iter.nextLayer());
349
                }
350

    
351
                return (FLayer[]) array.toArray(new FLayer[0]);
352
        }
353

    
354
        /*
355
         * (non-Javadoc)
356
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayer(int)
357
         */
358
        public FLayer getLayer(int index) {
359
                return (FLayer) layers.get(index);
360
        }
361

    
362
        /*
363
         * (non-Javadoc)
364
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayer(java.lang.String)
365
         */
366
        public FLayer getLayer(String layerName) {
367
                FLayer lyr;
368
                FLayer lyr2;
369
                ArrayList layerList;
370

    
371
                for (int i = 0; i < layers.size(); i++) {
372
                        lyr = ((FLayer) layers.get(i));
373

    
374
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
375
                                return lyr;
376
                        }
377

    
378
                        layerList = new ArrayList();
379
                        splitLayerGroup(lyr,layerList);
380
                        for(int j = 0; j<layerList.size(); j++ )
381
                        {
382
                                lyr2 = ((FLayer)layerList.get(j));
383
                                if (lyr2.getName().compareToIgnoreCase(layerName) == 0) {
384
                                        return lyr2;
385
                                }
386
                        }
387
                }
388

    
389
                return null;
390
        }
391

    
392
        /**
393
         * <p> Splits up a layer group in order to get a layer by name when there are layer groups</p>
394
         *
395
         * <p>In <code>result</code> always will be at least one layer.</p>
396
         *
397
         * @param layer the layer we are looking for
398
         * @param result an array list that will have the results of the search
399
         */
400
        private void splitLayerGroup(FLayer layer, ArrayList result)
401
        {
402
                int i;
403
                FLayers layerGroup;
404
                if (layer instanceof FLayers)
405
                {
406
                        layerGroup = (FLayers)layer;
407
                        for (i=0; i < layerGroup.getLayersCount(); i++ )
408
                        {
409
                                splitLayerGroup(layerGroup.getLayer(i),result);
410
                        }
411
                }
412
                else
413
                {
414
                        result.add(layer);
415
                }
416
        }
417

    
418
        /*
419
         * (non-Javadoc)
420
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayersCount()
421
         */
422
        public int getLayersCount() {
423
                return layers.size();
424
        }
425

    
426
        /*
427
         * (non-Javadoc)
428
         * @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)
429
         */
430
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
431
                        Cancellable cancel, double scale) throws ReadException {
432
                // FIXME Arreglar este error
433
                throw new RuntimeException("Esto no deberia de llamarse");
434
        }
435

    
436
        /*
437
         * (non-Javadoc)
438
         * 
439
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
440
         * com.iver.cit.gvsig.fmap.ViewPort,
441
         * com.iver.utiles.swing.threads.Cancellable, double,
442
         * javax.print.attribute.PrintRequestAttributeSet)
443
         */
444
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
445
                        double scale, PrintRequestAttributeSet properties)
446
        throws ReadException {
447
                throw new RuntimeException("No deberia pasar por aqui");
448
        }
449

    
450
        public void print_old(Graphics2D g, ViewPort viewPort, Cancellable cancel,
451
                        double scale, PrintRequestAttributeSet properties)
452
        throws ReadException {
453
                this.print_old(g, viewPort, cancel, scale, properties, null);
454
        }
455

    
456
        /**
457
         * <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
458
         *  a group of layers (<code>ComposedLayer</code>), executes it's drawn.</p>
459
         *
460
         * <p>All nodes which could group with the composed layer <code>group</code>, will be drawn together. And once the <code>
461
         * group</code> is drawn, will be set to <code>null</code> if hasn't a parent layer.</p>
462
         *
463
         * <p>The particular implementation depends on the kind of each layer and composed layer. And this process can be cancelled at any
464
         *  time by the shared object <code>cancel</code>.</p>
465
         *
466
         * <p>According the print quality, labels will be printed in different resolution:
467
         *  <ul>
468
         *   <li><b>PrintQuality.DRAFT</b>: 72 dpi (dots per inch).</li>
469
         *   <li><b>PrintQuality.NORMAL</b>: 300 dpi (dots per inch).</li>
470
         *   <li><b>PrintQuality.HIGH</b>: 600 dpi (dots per inch).</li>
471
         *  </ul>
472
         * </p>
473
         *
474
         * @param g for rendering 2-dimensional shapes, text and images on the Java(tm) platform
475
         * @param viewPort the information for drawing the layers
476
         * @param cancel shared object that determines if this layer can continue being drawn
477
         * @param scale the scale of the view. Must be between {@linkplain FLayer#getMinScale()} and {@linkplain FLayer#getMaxScale()}.
478
         * @param properties properties that will be print
479
         * @param group a composed layer pending to paint; if this parameter is <code>null</code>, the composed layer
480
         *
481
         * @return <code>null</code> if the layers in <code>group</code> had been drawn or were <code>null</code>; otherwise, the <code>group</code>
482
         *
483
         * @see FLayer#print(Graphics2D, ViewPort, Cancellable, double, PrintRequestAttributeSet)
484
         *
485
         * @throws ReadDriverException if fails the driver reading the data.
486
         */
487
        public ComposedLayer print_old(Graphics2D g, ViewPort viewPort, Cancellable cancel, double scale, PrintRequestAttributeSet properties, ComposedLayer group)
488
        throws ReadException {
489
                double dpi = 72;
490

    
491
                PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
492
                if (resolution.equals(PrintQuality.NORMAL)){
493
                        dpi = 300;
494
                } else if (resolution.equals(PrintQuality.HIGH)){
495
                        dpi = 600;
496
                } else if (resolution.equals(PrintQuality.DRAFT)){
497
                        dpi = 72;
498
                }
499

    
500
                // TODO: A la hora de imprimir, isWithinScale falla, porque est?
501
                // calculando la escala en pantalla, no para el layout.
502
                // Revisar esto.
503

    
504
                // TODO: We have to check when we have to call the drawLabels method when exists a ComposedLayer group.
505
                for (int i=0; i < layers.size(); i++) {
506
                        FLayer lyr = (FLayer) layers.get(i);
507
                        if (!lyr.isVisible() || !lyr.isWithinScale(scale)) {
508
                                continue;
509
                        }
510

    
511
                        try{
512

    
513
                                ///// CHEMA ComposedLayer
514
                                // Checks for draw group (ComposedLayer)
515
                                if (group != null) {
516
                                        if (lyr instanceof FLayers){
517
                                                group = ((FLayers)lyr).print_old(g, viewPort, cancel,scale,properties,group);
518
                                        } else {
519
                                                // If layer can be added to the group, does it
520
                                                if (lyr instanceof ILabelable
521
                                                                && ((ILabelable) lyr).isLabeled()
522
                                                                && ((ILabelable) lyr).getLabelingStrategy() != null
523
                                                                && ((ILabelable) lyr).getLabelingStrategy().shouldDrawLabels(scale)) {
524
                                                        group.add(lyr);
525
                                                } else {
526
                                                        // draw the 'pending to draw' layer group
527
                                                        group.print(g,viewPort,cancel,scale,properties);
528

    
529
                                                        // gets a new group instance
530
                                                        if (lyr instanceof ILabelable
531
                                                                        && ((ILabelable) lyr).isLabeled()
532
                                                                        && ((ILabelable) lyr).getLabelingStrategy() != null
533
                                                                        && ((ILabelable) lyr).getLabelingStrategy().shouldDrawLabels(scale)) {
534
                                                                group = lyr.newComposedLayer();
535
                                                        } else {
536
                                                                group = null;
537
                                                        }
538
                                                        // if layer hasn't group, draws it inmediately
539
                                                        if (group == null) {
540
                                                                if (lyr instanceof FLayers){
541
                                                                        group = ((FLayers)lyr).print_old(g, viewPort, cancel,scale,properties,group);
542
                                                                } else {
543
                                                                        lyr.print(g, viewPort, cancel,scale,properties);
544
                                                                        if (lyr instanceof ILabelable
545
                                                                                        && ((ILabelable) lyr).isLabeled()
546
                                                                                        && ((ILabelable) lyr).getLabelingStrategy() != null
547
                                                                                        && ((ILabelable) lyr).getLabelingStrategy().shouldDrawLabels(scale)) {
548
                                                                                ILabelable lLayer = (ILabelable) lyr;
549
                                                                                lLayer.drawLabels(null, g, viewPort, cancel, scale, dpi);
550
                                                                        }
551
                                                                }
552
                                                        } else {
553
                                                                // add the layer to the group
554
                                                                group.setMapContext(fmap);
555
                                                                group.add(lyr);
556

    
557
                                                        }
558

    
559
                                                }
560
                                        }
561
                                } else {
562
                                        // gets a new group instance
563
                                        group = lyr.newComposedLayer();
564
                                        // if layer hasn't group, draws it inmediately
565
                                        if (group == null) {
566
                                                if (lyr instanceof FLayers){
567
                                                        group = ((FLayers)lyr).print_old(g, viewPort, cancel,scale,properties,group);
568
                                                } else {
569
                                                        lyr.print(g, viewPort, cancel,scale,properties);
570
                                                        if (lyr instanceof ILabelable && ((ILabelable) lyr).isLabeled()) {
571
                                                                ILabelable lLayer = (ILabelable) lyr;
572

    
573
                                                                lLayer.drawLabels(null, g, viewPort, cancel, scale, dpi);
574
                                                        }
575
                                                }
576
                                        } else {
577
                                                // add the layer to the group
578
                                                group.setMapContext(fmap);
579
                                                group.add(lyr);
580

    
581
                                        }
582
                                }
583
                                ///// CHEMA ComposedLayer
584

    
585
                        } catch (Exception e){
586
                                String mesg = Messages.getString("error_printing_layer")+" "+ lyr.getName() + ": " + e.getMessage();
587
                                fmap.addLayerError(mesg);
588
                                logger.error(mesg, e);
589
                        }
590

    
591
                }
592

    
593
                ///// CHEMA ComposedLayer
594
                if (group != null && this.getParentLayer() == null) {
595
                        //si tenemos un grupo pendiente de pintar, pintamos
596
                        group.print(g, viewPort, cancel,scale,properties);
597
                        group = null;
598

    
599
                }
600
                ///// CHEMA ComposedLayer
601

    
602
                //                if (getVirtualLayers() != null) {
603
                //                        getVirtualLayers().print( g, viewPort, cancel, scale, properties);
604
                //                }
605

    
606
                ///// CHEMA ComposedLayer
607
                return group;
608
                ///// CHEMA ComposedLayer
609
        }
610

    
611
        /*
612
         * (non-Javadoc)
613
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
614
         */
615
        public Envelope getFullEnvelope() {
616
                Envelope rAux = null;
617
                boolean first = true;
618

    
619

    
620
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
621
                        FLayer capa = (FLayer) iter.next();
622
                        try{
623
                                if (first) {
624
                                        rAux = capa.getFullEnvelope();
625
                                        first=false;
626
                                } else {
627
                                        rAux.add(capa.getFullEnvelope());
628
                                }
629
                        }catch (Exception e) {
630
                                e.printStackTrace();//TODO hay que revisar para determinar el comportamiento que espera el usuario.
631
                        }
632
                }
633

    
634
                return rAux;
635
        }
636

    
637
        /**
638
         * Notifies all listeners associated to this collection of layers,
639
         *  that another layer is going to be added or replaced in the internal
640
         *  list of layers.
641
         *
642
         * @param e a layer collection event with the new layer
643
         */
644
        protected void callLayerAdding(LayerCollectionEvent event)
645
        throws CancelationException {
646
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
647
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
648
                        ((LayerCollectionListener) iter.next()).layerAdding(event);
649
                }
650
        }
651

    
652
        /**
653
         * Notifies all listeners associated to this collection of layers,
654
         *  that a layer is going to be removed from the internal list of layers.
655
         *
656
         * @param event a layer collection event with the layer being removed
657
         *
658
         * @throws CancelationException any exception produced during the cancellation of the driver.
659
         */
660
        protected void callLayerRemoving(LayerCollectionEvent event)
661
        throws CancelationException {
662
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
663
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
664
                        ((LayerCollectionListener) iter.next()).layerRemoving(event);
665
                }
666
        }
667

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

    
684
        /**
685
         * Notifies all listeners associated to this collection of layers,
686
         *  that another layer has been added or replaced in the internal
687
         *  list of layers.
688
         *
689
         * @param e a layer collection event with the new layer
690
         */
691
        protected void callLayerAdded(LayerCollectionEvent event) {
692
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
693
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
694
                        ((LayerCollectionListener) iter.next()).layerAdded(event);
695
                }
696
        }
697

    
698
        /**
699
         * Notifies all listeners associated to this collection of layers,
700
         *  that another layer has been removed from the internal list of layers.
701
         *
702
         * @param e a layer collection event with the layer removed
703
         */
704
        protected void callLayerRemoved(LayerCollectionEvent event) {
705
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
706
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
707
                        ((LayerCollectionListener) iter.next()).layerRemoved(event);
708
                }
709
        }
710

    
711
        /**
712
         * Notifies all listeners associated to this collection of layers,
713
         *  that another layer has been moved in the internal list of layers.
714
         *
715
         * @param e a layer collection event with the layer moved, and the initial and final positions
716
         */
717
        protected void callLayerMoved(LayerPositionEvent event) {
718
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
719
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
720
                        ((LayerCollectionListener) iter.next()).layerMoved(event);
721
                }
722
        }
723

    
724
        /**
725
         * <p>Returns an entity that represents this collection of layers stored as a tree-node with children that are also layers.</p>
726
         *
727
         * <p>The root node has the same properties that <code>FlyrDefault#getXMLEntity()</code> returns, and adds:
728
         *  <ul>
729
         *          <li> <i>numLayers</i> : number of layers of this collection (direct children of this node)
730
         *   <li> <i>LayerNames</i> : an array list with the name of the layers of this collection (direct children of this node)
731
         *    <code>FLayer.getXMLEntity()</code>
732
         *  </ul>
733
         * </p>
734
         *
735
         * <p>All XML elements returned represent the information about this layer.</p>
736
         *
737
         * @return an XML entity with information to this collection of layers
738
         * @throws XMLException if there is any error creating the XML from the layers.
739
         */
740
        public XMLEntity getXMLEntity() throws XMLException {
741
                XMLEntity xml = super.getXMLEntity();
742
                xml.putProperty("numLayers", layers.size());
743

    
744
                String[] s = new String[layers.size()];
745

    
746
                for (int i = 0; i < layers.size(); i++) {
747
                        s[i] = ((FLayer) layers.get(i)).getName();
748
                }
749

    
750
                xml.putProperty("LayerNames", s);
751

    
752
                for (int i = 0; i < layers.size(); i++) {
753
                        try {
754
                                XMLEntity xmlLayer=((FLayer) layers.get(i)).getXMLEntity();
755
                                xmlLayer.putProperty("tagName", "layer");
756
                                xml.addChild(xmlLayer);
757
                        }catch (XMLException e) {
758
                                e.printStackTrace();
759
                        }
760
                }
761

    
762
                return xml;
763
        }
764

    
765
        /**
766
         * <p>Inserts layers and properties to this collection of layers.</p>
767
         *
768
         * <p>This root node has the same properties that return <code>FlyrDefault#getXMLEntity()</code> adding:
769
         *  <ul>
770
         *          <li> <i>numLayers</i> : number of first-level layers of this collection
771
         *   <li> <i>LayerNames</i> : an array list with the name of the first-level layers of this collection
772
         *    <code>FLayer.getXMLEntity()</code>
773
         *  </ul>
774
         * </p>
775
         *
776
         * @see FLyrDefault#setXMLEntity()
777
         * @see FLyrDefault#getXMLEntity()
778
         * @see CopyOfFLayers#addLayerFromXML(XMLEntity, String)
779
         *
780
         * @param xml an <code>XMLEntity</code> with the information
781
         *
782
         * @throws XMLException if there is an error setting the object.
783
         */
784
        public void setXMLEntity(XMLEntity xml) throws XMLException{
785
                super.setXMLEntity(xml);
786
                //LoadLayerException loadLayerException=new LoadLayerException();
787

    
788
                String[] s = xml.getStringArrayProperty("LayerNames");
789
                // try {
790
                fmap.clearErrors();
791
                int numLayers=xml.getIntProperty("numLayers");
792
                Iterator iter = xml.findChildren("tagName","layer");
793
                XMLEntity xmlLayer;
794
                while (iter.hasNext()) {
795
                        xmlLayer=(XMLEntity) iter.next();
796
                        try {
797
                                this.addLayerFromXML(xmlLayer, null);
798
                        } catch (LoadLayerException e) {
799
                                throw new XMLLayerException(getName(),e);
800
                        }
801
                }
802
                if (numLayers != this.layers.size()) {
803
                        logger.warn(this.getName() + ": layer count no match");
804
                }
805
        }
806
        /*
807
         * (non-Javadoc)
808
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getMapContext()
809
         */
810
        public MapContext getMapContext() {
811
                return fmap;
812
        }
813
        /*
814
         * (non-Javadoc)
815
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setCoordTrans(org.cresques.cts.ICoordTrans)
816
         */
817
        public void setCoordTrans(ICoordTrans ct) {
818
                super.setCoordTrans(ct);
819

    
820
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
821
                        FLayer layer = (FLayer) iter.next();
822
                        layer.setCoordTrans(ct);
823
                }
824
        }
825
        /*
826
         * (non-Javadoc)
827
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#setAllActives(boolean)
828
         */
829
        public void setAllActives(boolean active) {
830
                FLayer lyr;
831

    
832
                for (int i = 0; i < layers.size(); i++) {
833
                        lyr = ((FLayer) layers.get(i));
834
                        lyr.setActive(active);
835

    
836
                        if (lyr instanceof LayerCollection) {
837
                                ((LayerCollection) lyr).setAllActives(active);
838
                        }
839
                }
840
        }
841

    
842
        /*
843
         * (non-Javadoc)
844
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getActives()
845
         */
846
        public FLayer[] getActives() {
847
                ArrayList ret = new ArrayList();
848
                LayersIterator it = new LayersIterator(this) {
849

    
850
                        public boolean evaluate(FLayer layer) {
851
                                return layer.isActive();
852
                        }
853

    
854
                };
855

    
856
                while (it.hasNext())
857
                {
858
                        ret.add(it.next());
859
                }
860
                return (FLayer[]) ret.toArray(new FLayer[0]);
861
        }
862

    
863
        /*
864
         * (non-Javadoc)
865
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getMinScale()
866
         */
867
        public double getMinScale() {
868
                return -1; // La visibilidad o no la controla cada capa
869
                // dentro de una colecci?n
870
        }
871
        /*
872
         * (non-Javadoc)
873
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getMaxScale()
874
         */
875
        public double getMaxScale() {
876
                return -1;
877
        }
878
        /*
879
         * (non-Javadoc)
880
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setMinScale(double)
881
         */
882
        public void setMinScale(double minScale)
883
        {
884
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
885
                        FLayer lyr = (FLayer) iter.next();
886
                        lyr.setMinScale(minScale);
887
                }
888
        }
889
        /*
890
         * (non-Javadoc)
891
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setMaxScale(double)
892
         */
893
        public void setMaxScale(double maxScale)
894
        {
895
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
896
                        FLayer lyr = (FLayer) iter.next();
897
                        lyr.setMinScale(maxScale);
898
                }
899
        }
900
        /*
901
         * (non-Javadoc)
902
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setActive(boolean)
903
         */
904
        public void setActive(boolean b){
905
                super.setActive(b);
906
                for (int i=0;i<layers.size();i++){
907
                        ((FLayer)layers.get(i)).setActive(b);
908
                }
909
        }
910
        /* (non-Javadoc)
911
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#addLayerListener(com.iver.cit.gvsig.fmap.layers.LayerListener)
912
         */
913
        public boolean addLayerListener(LayerListener o) {
914
                for (int i = 0; i < layers.size(); i++) {
915
                        ((FLayer) layers.get(i)).addLayerListener(o);
916
                }
917
                return true;
918
        }
919
        /*
920
         * (non-Javadoc)
921
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint#getInfo(java.awt.Point, double, com.iver.utiles.swing.threads.Cancellable)
922
         */
923
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws LoadLayerException, DataException {
924
                int i;
925
                Vector items = new Vector();
926
                FLayer layer;
927
                XMLItem[] aux;
928
                for (i = 0; i < this.layers.size(); i++){
929
                        layer = (FLayer)layers.get(i);
930
                        if (layer instanceof InfoByPoint){
931
                                InfoByPoint queryable_layer = (InfoByPoint) layer;
932
                                aux = queryable_layer.getInfo(p, tolerance, null);
933
                                if (!(queryable_layer instanceof FLayers)){
934
                                        for(int j = 0; j < aux.length; j++){
935
                                                items.add(aux[j]);
936
                                        }
937
                                }
938
                        }
939
                }
940
                return (XMLItem[])items.toArray(new XMLItem[0]);
941

    
942
        }
943

    
944
        /*
945
         * (non-Javadoc)
946
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
947
         */
948
        public ImageIcon getTocImageIcon() {
949
                return new ImageIcon(MapContext.class.getResource("images/layerGroup.png"));
950
        }
951

    
952
        /**
953
         * <p>Adds the layer with the information in an XML entity and the specified name, to this collection of layers. And
954
         *  returns <code>true</code> if there hasn't been errors.</p>
955
         *
956
         * @see CopyOfFLayers#addLayerFromXML(XMLEntity, String)
957
         *
958
         * @param xml tree-node structure with information about layers
959
         * @param name name of the layer to add
960
         * @return <code>true</code> if there were no errors adding the layer, <code>false</code> otherwise
961
         *
962
         * @throws LoadLayerException if fails loading this layer.
963
         */
964
        //        public boolean addLayerFromXMLEntity(XMLEntity xml, String name) throws LoadLayerException {
965
        //                fmap.clearErrors();
966
        //                this.addLayerFromXML(xml,name);
967
        //
968
        //                return (fmap.getLayersError().size() == 0);
969
        //
970
        //        }
971

    
972
        /**
973
         * <p>Adds the layer with the information in an XML entity and the specified name, to this collection of layers.</p>
974
         *
975
         * <p>This method really executes the addition, considering the kind of layer (<code>FLyrVect</code>,
976
         *  <code>FLyrAnnotation</code>, <code>FLyrRaster</code>, a collection of layers (<code>FLayers</code>),
977
         *  or another kind of layer (<code>FLayer</code>)), and the driver in the layer.</p>
978
         *
979
         * @param xml tree-node structure with information about layers
980
         * @param name name of the layer to add
981
         *
982
         * @throws LoadLayerException if fails loading this layer.
983
         */
984
        private void addLayerFromXML(XMLEntity xml, String name) throws LoadLayerException {
985
                FLayer layer = null;
986

    
987
                try {
988
                        if (name == null) {
989
                                name = xml.getName();
990
                        }
991

    
992

    
993
                        String className = xml.getStringProperty("className");
994
                        Class clase = Class.forName(className);
995
                        layer = (FLayer) clase.newInstance();
996
                        if (FLayers.class.isAssignableFrom(clase)) {
997
                                ((FLayers)layer).setMapContext(getMapContext());
998
                                ((FLayers)layer).setParentLayer(this);
999
                                //                        layer = new FLayers(getMapContext(),this);
1000
                                layer.setXMLEntity(xml);
1001
                        } else {
1002
                                // Capas Nuevas (externas)
1003
                                layer.setName(name);
1004
                                layer.setXMLEntity(xml);
1005
                                layer.load();
1006
                        }
1007

    
1008
                        //                //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,
1009
                        //                //ya que los drivers de una FLyrAnnotation no sabemos cual es puede ser cualquier Driver Vectorial.
1010
                        //                if (className.equals(FLyrVect.class.getName())){// || className.equals(FLyrAnnotation.class.getName())) {
1011
                        //                        String type = xml.getStringProperty("type");
1012
                        //                        if ("vectorial".equals(type)){
1013
                        //                                //String recordsetName = xml.getChild(i).getStringProperty("recordset-name");
1014
                        //                                IProjection proj = null;
1015
                        //                                if (xml.contains("proj")) {
1016
                        //                                        proj = CRSFactory.getCRS(xml.getStringProperty("proj"));
1017
                        //                                }
1018
                        //                                else
1019
                        //                                {
1020
                        //                                        proj = this.getMapContext().getViewPort().getProjection();
1021
                        //                                }
1022
                        //                                if (xml.contains("file")) {
1023
                        //                                        Driver d;
1024
                        //                                        try {
1025
                        //                                                d = LayerFactory.getDM().getDriver(xml.getStringProperty("driverName"));
1026
                        //                                        } catch (DriverLoadException e1) {
1027
                        //                                                throw new DriverLayerException(name,e1);
1028
                        //                                        }
1029
                        //                                        layer = LayerFactory.createLayer(name, (VectorialFileDriver) d,
1030
                        //                                                        new File(xml.getStringProperty("file")),
1031
                        //                                                        proj);
1032
                        //
1033
                        //
1034
                        //                                }
1035
                        //                                if (xml.contains("db")) {
1036
                        //
1037
                        //                                        String driverName = xml.getStringProperty("db");
1038
                        //                                        IVectorialDatabaseDriver driver;
1039
                        //                                        try {
1040
                        //                                                driver = (IVectorialDatabaseDriver) LayerFactory.getDM().getDriver(driverName);
1041
                        //                                                //Hay que separar la carga de los datos del XMLEntity del load.
1042
                        //                                                driver.setXMLEntity(xml.getChild(2));
1043
                        //
1044
                        //                                                boolean loadOk = false;
1045
                        //                                                ((DefaultJDBCDriver)driver).load();
1046
                        //                                                if (((DefaultJDBCDriver)driver).getConnection() != null) {
1047
                        //                                                        loadOk = true;
1048
                        //                                                }
1049
                        //                                                layer = LayerFactory.createDBLayer(driver, name, proj);
1050
                        //                                                if (!loadOk) {
1051
                        //                                                        layer.setAvailable(false);
1052
                        //                                                }
1053
                        //
1054
                        //                                        } catch (DriverLoadException e) {
1055
                        //                                                throw new DriverLayerException(name,e);
1056
                        //                                        } catch (XMLException e) {
1057
                        //                                                throw new DriverLayerException(name,e);
1058
                        //                                        } catch (ReadException e) {
1059
                        //                                                throw new DriverLayerException(name,e);
1060
                        //                                        }
1061
                        //
1062
                        //                                }
1063
                        //                                // Clases con algun driver gen?rico creado por otro
1064
                        //                                // programador
1065
                        //                                if (xml.contains("other")) {
1066
                        //
1067
                        //                                        String driverName = xml.getStringProperty("other");
1068
                        //                                        VectorialDriver driver = null;
1069
                        //                                        try {
1070
                        //                                                driver = (VectorialDriver) LayerFactory.getDM().getDriver(driverName);
1071
                        //                                        } catch (DriverLoadException e) {
1072
                        //                                                // Si no existe ese driver, no pasa nada.
1073
                        //                                                // Puede que el desarrollador no quiera que
1074
                        //                                                // aparezca en el cuadro de di?logo y ha metido
1075
                        //                                                // el jar con sus clases en nuestro directorio lib.
1076
                        //                                                // Intentamos cargar esa clase "a pelo".
1077
                        //                                                if (xml.getChild(2).contains("className"))
1078
                        //                                                {
1079
                        //                                                        String className2 = xml.getChild(2).getStringProperty("className");
1080
                        //                                                        try {
1081
                        //                                                                driver = (VectorialDriver) Class.forName(className2).newInstance();
1082
                        //                                                        } catch (Exception e1) {
1083
                        //                                                                throw new DriverLayerException(name,e);
1084
                        //                                                        }
1085
                        //                                                }
1086
                        //                                        } catch (NullPointerException npe) {
1087
                        //                                                // Si no existe ese driver, no pasa nada.
1088
                        //                                                // Puede que el desarrollador no quiera que
1089
                        //                                                // aparezca en el cuadro de di?logo y ha metido
1090
                        //                                                // el jar con sus clases en nuestro directorio lib.
1091
                        //                                                // Intentamos cargar esa clase "a pelo".
1092
                        //                                                if (xml.getChild(2).contains("className"))
1093
                        //                                                {
1094
                        //                                                        String className2 = xml.getChild(2).getStringProperty("className");
1095
                        //                                                        try {
1096
                        //                                                                driver = (VectorialDriver) Class.forName(className2).newInstance();
1097
                        //                                                        } catch (Exception e1) {
1098
                        //                                                                throw new DriverLayerException(name,e1);
1099
                        //                                                        }
1100
                        //                                                }
1101
                        //                                        }
1102
                        //                                        if (driver instanceof IPersistence)
1103
                        //                                        {
1104
                        //                                                IPersistence persist = (IPersistence) driver;
1105
                        //                                                persist.setXMLEntity(xml.getChild(2));
1106
                        //                                        }
1107
                        //                                        layer = LayerFactory.createLayer(name, driver, proj);
1108
                        //                                }
1109
                        //
1110
                        //                        }
1111
                        //
1112
                        //                        //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,
1113
                        //                        //ya que los drivers de una FLyrAnnotation no sabemos cual es puede ser cualquier Driver Vectorial.
1114
                        //                        if (className.equals(FLyrAnnotation.class.getName())){
1115
                        //                                layer=FLyrAnnotation.createLayerFromVect((FLyrVect)layer);
1116
                        //                        }
1117
                        //
1118
                        //
1119
                        //                        layer.setXMLEntity(xml);
1120
                        //
1121
                        //                } else {
1122
                        //                        Class clase = LayerFactory.getLayerClassForLayerClassName(className);
1123
                        //                        layer = (FLayer) clase.newInstance();
1124
                        //                        if (clase.isAssignableFrom(FLayers.class)) {
1125
                        //                                ((FLayers)layer).setMapContext(getMapContext());
1126
                        //                                ((FLayers)layer).setParentLayer(this);
1127
                        ////                                layer = new FLayers(getMapContext(),this);
1128
                        //                                layer.setXMLEntity(xml);
1129
                        //                        } else {
1130
                        //                                // Capas Nuevas (externas)
1131
                        //                                layer.setName(name);
1132
                        //                                layer.setXMLEntity(xml);
1133
                        //                                layer.load();
1134
                        //                        }
1135
                        //                }
1136
                        this.addLayer(layer);
1137
                        logger.debug("layer: "+ layer.getName() +" loaded");
1138
                        // Comprobar que la proyecci?n es la misma que la de FMap
1139
                        // Si no lo es, es una capa que est? reproyectada al vuelo
1140
                        IProjection proj = layer.getProjection();
1141
                        if ((proj != null)) {
1142
                                if (!proj.getFullCode().equals(getMapContext().getProjection().getFullCode()))
1143
                                {
1144
                                        ICoordTrans ct = proj.getCT(getMapContext().getProjection());
1145
                                        // TODO: REVISAR CON LUIS
1146
                                        // Se lo fijamos a todas, luego cada una que se reproyecte
1147
                                        // si puede, o que no haga nada
1148

    
1149
                                        layer.setCoordTrans(ct);
1150
                                }
1151
                        }
1152
                } catch (XMLException e) {
1153
                        fmap.addLayerError(xml.getStringProperty("name"));
1154
                        throw new LoadLayerException(name,e);
1155
                } catch (ClassNotFoundException e) {
1156
                        fmap.addLayerError(xml.getStringProperty("name"));
1157
                        throw new LoadLayerException(name,e);
1158
                } catch (InstantiationException e) {
1159
                        fmap.addLayerError(xml.getStringProperty("name"));
1160
                        throw new LoadLayerException(name,e);
1161
                } catch (IllegalAccessException e) {
1162
                        fmap.addLayerError(xml.getStringProperty("name"));
1163
                        throw new LoadLayerException(name,e);
1164
                } catch (LoadLayerException e){
1165
                        fmap.addLayerError(xml.getStringProperty("name"));
1166
                        throw e;
1167
                }
1168
        }
1169

    
1170
        /**
1171
         * <p>Sets the <code>MapContext</code> that contains this layer node.</p>
1172
         *
1173
         * @param mapContext the <code>MapContext</code> that contains this layer node
1174
         */
1175
        public void setMapContext(MapContext mapContext) {
1176
                this.fmap = mapContext;
1177
        }
1178

    
1179
        /**
1180
         * <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
1181
         *  and loads the layer. Then, adds the layer to this collection of layers, and if there is a projection defined,
1182
         *  inserts the transformation coordinates to the layer.</p>
1183
         *
1184
         * <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>
1185
         *
1186
         * @param xml tree-node structure with information about layers
1187
         * @param name name of the layer to add
1188
         */
1189
        private void addLayerFromXMLNew(XMLEntity xml, String name) {
1190
                //                FLayer layer = null;
1191
                //
1192
                //
1193
                //                try {
1194
                //                        String className = xml.getStringProperty("className");
1195
                //                        Class clazz = Class.forName(className);
1196
                //                        if (clazz.isAssignableFrom(FLayers.class)) {
1197
                //                                layer = (FLayer) clazz.newInstance();
1198
                //                                ((FLayers)layer).setMapContext(getMapContext());
1199
                //                                ((FLayers)layer).setParentLayer(this);
1200
                //        //                if (className.equals((FLayers.class.getName()))){
1201
                //        //                        layer = new FLayers(getMapContext(),this);
1202
                //                        } else {
1203
                //        //                        Por compatibilidad
1204
                //                                if (className.equals(FLyrVect.class.getName())) {
1205
                //                                        if (xml.contains("file")) {
1206
                //                                                layer = new FLayerFileVectorial();
1207
                //                                        } else if (xml.contains("db")) {
1208
                //                                                try {
1209
                //                                                        layer = (FLayer)((ExtensionPoint)ExtensionPointsSingleton.getInstance().get("Layers")).create("com.iver.cit.gvsig.fmap.layers.FLayerJDBCVectorial");
1210
                //                                                } catch (Exception e) {
1211
                //                                                        throw new XMLException(new Exception("No se tiene registrada la capa de tipo JDBC"));
1212
                //                                                }
1213
                //                                                //className = FLayerJDBCVectorial.class.getName();
1214
                //                                        } else if (xml.contains("other")){
1215
                //                                                layer = new FLayerGenericVectorial();
1216
                //                                        } else {
1217
                //                                                throw new XMLException(new Exception("Capa vectorial de tipo no reconocido"));
1218
                //                                        }
1219
                //        //                                Fin por compatibilidad
1220
                //                                } else {
1221
                //                                        try {
1222
                //                                                layer = (FLayer)(((ExtensionPoint)ExtensionPointsSingleton.getInstance().get("Layers")).create(className));
1223
                //                                        } catch (Exception e) {
1224
                //                                                //puende que no este registrada como punto de extension
1225
                //                                                Class clase = Class.forName(className);
1226
                //                                                layer = (FLayer) clase.newInstance();
1227
                //                                                // FIXME: Hacemos algo aqui o dejamos que suba el error?
1228
                //                                        }
1229
                //                                }
1230
                //
1231
                //                        }
1232
                //                        layer.setXMLEntity(xml);
1233
                //                        if (name != null) layer.setName(name);
1234
                //                        layer.load();
1235
                //
1236
                //                        this.addLayer(layer);
1237
                //                        logger.debug("layer: "+ layer.getName() +" loaded");
1238
                //                        // Comprobar que la proyecci?n es la misma que la de FMap
1239
                //                        // Si no lo es, es una capa que est? reproyectada al vuelo
1240
                //                        IProjection proj = layer.getProjection();
1241
                //                        if ((proj != null))
1242
                //                                if (proj != getMapContext().getProjection())
1243
                //                                {
1244
                //                                        ICoordTrans ct = proj.getCT(getMapContext().getProjection());
1245
                //                                        // TODO: REVISAR CON LUIS
1246
                //                                        // Se lo fijamos a todas, luego cada una que se reproyecte
1247
                //                                        // si puede, o que no haga nada
1248
                //                                        layer.setCoordTrans(ct);
1249
                //
1250
                //                                }
1251
                //                }catch (Exception e) {
1252
                //                        fmap.addLayerError(xml.getStringProperty("name"));
1253
                //                        logger.debug(Messages.getString("could_not_load_layer")+": "+xml.getStringProperty("name") + ".\n"
1254
                //                                        +Messages.getString("reason")+":", e);
1255
                //                }
1256
        }
1257

    
1258
        public void accept(Visitor visitor) throws BaseException {
1259
                throw new NotSupportedOperationException(visitor, this);
1260
        }
1261

    
1262
        public void accept(LayersVisitor visitor) throws BaseException {
1263
                for (int i = 0; i < this.getLayersCount(); i++) {
1264
                        FLayer layer = this.getLayer(i);
1265
                        if (layer instanceof LayersVisitable) {
1266
                                ((LayersVisitable) layer).accept(visitor);
1267
                        } else {
1268
                                visitor.visit(layer);
1269
                        }
1270
                }
1271
        }
1272

    
1273
        /*
1274
         * (non-Javadoc)
1275
         * 
1276
         * @see org.gvsig.metadata.Metadata#getMetadataID()
1277
         */
1278
        public Object getMetadataID() {
1279
                StringBuilder strb = new StringBuilder();
1280
                strb.append("Layers(");
1281
                strb.append(this.getName());
1282
                strb.append("):{");
1283
                Iterator iter = this.layers.iterator();
1284
                while (iter.hasNext()) {
1285
                        strb.append(((FLayer) iter.next()).getMetadataID());
1286
                        strb.append(",");
1287
                }
1288
                strb.append("}");
1289
                return strb.toString();
1290

    
1291
        }
1292

    
1293
        /*
1294
         * (non-Javadoc)
1295
         * 
1296
         * @see org.gvsig.metadata.Metadata#getMetadataChildren()
1297
         */
1298
        public Set getMetadataChildren() {
1299
                Set ret = new TreeSet();
1300
                Iterator iter = this.layers.iterator();
1301
                while (iter.hasNext()) {
1302
                        ret.add(iter.next());
1303
                }
1304
                return ret;
1305
        }
1306

    
1307
        /*
1308
         * (non-Javadoc)
1309
         * 
1310
         * @see org.gvsig.metadata.Metadata#getMetadataName()
1311
         */
1312
        public String getMetadataName() {
1313
                StringBuilder strb = new StringBuilder();
1314
                strb.append("Layer Group '");
1315
                strb.append(this.getName());
1316
                strb.append("': {");
1317
                Iterator iter = this.layers.iterator();
1318
                while (iter.hasNext()) {
1319
                        strb.append(((FLayer) iter.next()).getMetadataName());
1320
                        strb.append(",");
1321
                }
1322
                strb.append("}");
1323
                return strb.toString();
1324
        }
1325

    
1326

    
1327
        public void beginDraw(Graphics2D g, ViewPort viewPort) {
1328
                LayerDrawEvent beforeEvent = new LayerDrawEvent(this, g, viewPort, LayerDrawEvent.LAYER_BEFORE_DRAW);
1329
                fmap.fireLayerDrawingEvent(beforeEvent);
1330
        }
1331

    
1332
        public void endDraw(Graphics2D g, ViewPort viewPort) {
1333
                LayerDrawEvent afterEvent = new LayerDrawEvent(this, g, viewPort, LayerDrawEvent.LAYER_AFTER_DRAW);
1334
                fmap.fireLayerDrawingEvent(afterEvent);
1335
        }
1336

    
1337
}