Statistics
| Revision:

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

History | View | Annotate | Download (44.2 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.swing.ImageIcon;
55

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

    
81
import com.iver.utiles.XMLEntity;
82
import com.iver.utiles.XMLException;
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 = new ArrayList();
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 = Collections.synchronizedList(new ArrayList());
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
        final static private Logger logger = LoggerFactory.getLogger(FLayers.class);
139

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

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

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

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

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

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

    
199
        /*
200
         * (non-Javadoc)
201
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#addLayer(com.iver.cit.gvsig.fmap.layers.FLayer)
202
         */
203
        public void addLayer(FLayer layer) {
204
                addLayer(layers.size(),layer);
205
        }
206

    
207
        /**
208
         * Adds a layer in an specified position in this node.
209
         *
210
         * @param layer a layer
211
         */
212
        public void addLayer(int pos,FLayer layer) {
213
                try {
214
                        //Notificamos a la capa que va a ser a?adida
215
                        if (layer instanceof FLyrDefault) {
216
                                ((FLyrDefault)layer).wakeUp();
217
                        }
218

    
219
                        if (layer instanceof FLayers){
220
                                FLayers layers=(FLayers)layer;
221
                                fmap.addAsCollectionListener(layers);
222
                        }
223
                        callLayerAdding(LayerCollectionEvent.createLayerAddingEvent(layer));
224

    
225
                        doAddLayer(pos,layer);
226

    
227
                        callLayerAdded(LayerCollectionEvent.createLayerAddedEvent(layer));
228
                } catch (CancelationException e) {
229
                        logger.warn(e.getMessage());
230
                } catch (LoadLayerException e) {
231
                        layer.setAvailable(false);
232
                        layer.addError(e);
233
                }
234
        }
235

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

    
254
        /**
255
         * Removes an inner layer.
256
         *
257
         * @param lyr a layer
258
         */
259
        private void doRemoveLayer(FLayer lyr) {
260
                layers.remove(lyr);
261
                this.updateDrawVersion();
262
        }
263

    
264
        /*
265
         * (non-Javadoc)
266
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(com.iver.cit.gvsig.fmap.layers.FLayer)
267
         */
268
        public void removeLayer(FLayer lyr) throws CancelationException {
269
                callLayerRemoving(LayerCollectionEvent.createLayerRemovingEvent(lyr));
270
                doRemoveLayer(lyr);
271
                callLayerRemoved(LayerCollectionEvent.createLayerRemovedEvent(lyr));
272
        }
273

    
274
        /*
275
         * (non-Javadoc)
276
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(int)
277
         */
278
        public void removeLayer(int idLayer) {
279
                FLayer lyr = (FLayer) layers.get(idLayer);
280
                callLayerRemoving(LayerCollectionEvent.createLayerRemovingEvent(lyr));
281
                layers.remove(idLayer);
282
                this.updateDrawVersion();
283
                callLayerRemoved(LayerCollectionEvent.createLayerRemovedEvent(lyr));
284
        }
285

    
286
        /*
287
         * (non-Javadoc)
288
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#removeLayer(java.lang.String)
289
         */
290
        public void removeLayer(String layerName) {
291
                FLayer lyr;
292

    
293
                for (int i = 0; i < layers.size(); i++) {
294
                        lyr = ((FLayer) layers.get(i));
295

    
296
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
297
                                removeLayer(i);
298

    
299
                                break;
300
                        }
301
                }
302
        }
303

    
304
        /**
305
         * Replace a layer identified by its name, by another.
306
         *
307
         * @param layerName the name of the layer to be replaced
308
         * @param layer the new layer
309
         */
310
        public void replaceLayer(String layerName, FLayer layer) throws LoadLayerException
311
        {
312
                FLayer lyr;
313
                FLayer parent;
314
                for (int i = 0; i < layers.size(); i++) {
315
                        lyr = ((FLayer) layers.get(i));
316

    
317
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
318
                                parent = lyr.getParentLayer();
319
                                removeLayer(i);
320
                                if (parent != null) {
321
                                        //Notificamos a la capa que va a ser a?adida
322
                                        if (layer instanceof FLyrDefault) {
323
                                                ((FLyrDefault)layer).wakeUp();
324
                                        }
325
                                }
326

    
327
                                if (layer instanceof FLayers){
328
                                        FLayers layers=(FLayers)layer;
329
                                        fmap.addAsCollectionListener(layers);
330
                                }
331
                                callLayerAdding(LayerCollectionEvent.createLayerAddingEvent(layer));
332

    
333
                                layers.add(i,layer);
334
                                layer.setParentLayer(this);
335

    
336
                                callLayerAdded(LayerCollectionEvent.createLayerAddedEvent(layer));
337
                                break;
338
                        }
339
                }
340
        }
341

    
342
        /*
343
         * (non-Javadoc)
344
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getVisibles()
345
         */
346
        public FLayer[] getVisibles() {
347
                ArrayList array = new ArrayList();
348
                LayersIterator iter = new LayersIterator(this) {
349
                        public boolean evaluate(FLayer layer) {
350
                                return layer.isVisible();
351
                        }
352

    
353
                };
354

    
355
                while (iter.hasNext()) {
356
                        array.add(iter.nextLayer());
357
                }
358

    
359
                return (FLayer[]) array.toArray(new FLayer[0]);
360
        }
361

    
362
        /*
363
         * (non-Javadoc)
364
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayer(int)
365
         */
366
        public FLayer getLayer(int index) {
367
                return (FLayer) layers.get(index);
368
        }
369

    
370
        /*
371
         * (non-Javadoc)
372
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayer(java.lang.String)
373
         */
374
        public FLayer getLayer(String layerName) {
375
                FLayer lyr;
376
                FLayer lyr2;
377
                ArrayList layerList;
378

    
379
                for (int i = 0; i < layers.size(); i++) {
380
                        lyr = ((FLayer) layers.get(i));
381

    
382
                        if (lyr.getName().compareToIgnoreCase(layerName) == 0) {
383
                                return lyr;
384
                        }
385

    
386
                        layerList = new ArrayList();
387
                        splitLayerGroup(lyr,layerList);
388
                        for(int j = 0; j<layerList.size(); j++ )
389
                        {
390
                                lyr2 = ((FLayer)layerList.get(j));
391
                                if (lyr2.getName().compareToIgnoreCase(layerName) == 0) {
392
                                        return lyr2;
393
                                }
394
                        }
395
                }
396

    
397
                return null;
398
        }
399

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

    
426
        /*
427
         * (non-Javadoc)
428
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getLayersCount()
429
         */
430
        public int getLayersCount() {
431
                return layers.size();
432
        }
433

    
434
        /*
435
         * (non-Javadoc)
436
         * @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)
437
         */
438
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
439
                        Cancellable cancel, double scale) throws ReadException {
440
                // FIXME Arreglar este error
441
                throw new RuntimeException("Esto no deberia de llamarse");
442
        }
443

    
444
        /*
445
         * (non-Javadoc)
446
         *
447
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
448
         * com.iver.cit.gvsig.fmap.ViewPort,
449
         * com.iver.utiles.swing.threads.Cancellable, double,
450
         * javax.print.attribute.PrintAttributes)
451
         */
452
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
453
                        double scale, PrintAttributes properties)
454
        throws ReadException {
455
                throw new RuntimeException("No deberia pasar por aqui");
456
        }
457

    
458
        public void print_old(Graphics2D g, ViewPort viewPort, Cancellable cancel,
459
                        double scale, PrintAttributes properties)
460
        throws ReadException {
461
                this.print_old(g, viewPort, cancel, scale, properties, null);
462
        }
463

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

    
499
                int resolution = properties.getPrintQuality();
500
                if (resolution == PrintAttributes.PRINT_QUALITY_NORMAL) {
501
                        dpi = 300;
502
                } else if (resolution == PrintAttributes.PRINT_QUALITY_HIGH){
503
                        dpi = 600;
504
                } else if (resolution == PrintAttributes.PRINT_QUALITY_DRAFT){
505
                        dpi = 72;
506
                }
507

    
508
                // TODO: A la hora de imprimir, isWithinScale falla, porque est?
509
                // calculando la escala en pantalla, no para el layout.
510
                // Revisar esto.
511

    
512
                // TODO: We have to check when we have to call the drawLabels method when exists a ComposedLayer group.
513
                for (int i=0; i < layers.size(); i++) {
514
                        FLayer lyr = (FLayer) layers.get(i);
515
                        if (!lyr.isVisible() || !lyr.isWithinScale(scale)) {
516
                                continue;
517
                        }
518

    
519
                        try{
520

    
521
                                ///// CHEMA ComposedLayer
522
                                // Checks for draw group (ComposedLayer)
523
                                if (group != null) {
524
                                        if (lyr instanceof FLayers){
525
                                                group = ((FLayers)lyr).print_old(g, viewPort, cancel,scale,properties,group);
526
                                        } else {
527
                                                // If layer can be added to the group, does it
528
                                                if (lyr instanceof ILabelable
529
                                                                && ((ILabelable) lyr).isLabeled()
530
                                                                && ((ILabelable) lyr).getLabelingStrategy() != null
531
                                                                && ((ILabelable) lyr).getLabelingStrategy().shouldDrawLabels(scale)) {
532
                                                        group.add(lyr);
533
                                                } else {
534
                                                        // draw the 'pending to draw' layer group
535
                                                        group.print(g,viewPort,cancel,scale,properties);
536

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

    
565
                                                        }
566

    
567
                                                }
568
                                        }
569
                                } else {
570
                                        // gets a new group instance
571
                                        group = lyr.newComposedLayer();
572
                                        // if layer hasn't group, draws it inmediately
573
                                        if (group == null) {
574
                                                if (lyr instanceof FLayers){
575
                                                        group = ((FLayers)lyr).print_old(g, viewPort, cancel,scale,properties,group);
576
                                                } else {
577
                                                        lyr.print(g, viewPort, cancel,scale,properties);
578
                                                        if (lyr instanceof ILabelable && ((ILabelable) lyr).isLabeled()) {
579
                                                                ILabelable lLayer = (ILabelable) lyr;
580

    
581
                                                                lLayer.drawLabels(null, g, viewPort, cancel, scale, dpi);
582
                                                        }
583
                                                }
584
                                        } else {
585
                                                // add the layer to the group
586
                                                group.setMapContext(fmap);
587
                                                group.add(lyr);
588

    
589
                                        }
590
                                }
591
                                ///// CHEMA ComposedLayer
592

    
593
                        } catch (Exception e){
594
                                String mesg = Messages.getString("error_printing_layer")+" "+ lyr.getName() + ": " + e.getMessage();
595
                                fmap.addLayerError(mesg);
596
                                logger.error(mesg, e);
597
                        }
598

    
599
                }
600

    
601
                ///// CHEMA ComposedLayer
602
                if (group != null && this.getParentLayer() == null) {
603
                        //si tenemos un grupo pendiente de pintar, pintamos
604
                        group.print(g, viewPort, cancel,scale,properties);
605
                        group = null;
606

    
607
                }
608
                ///// CHEMA ComposedLayer
609

    
610
                //                if (getVirtualLayers() != null) {
611
                //                        getVirtualLayers().print( g, viewPort, cancel, scale, properties);
612
                //                }
613

    
614
                ///// CHEMA ComposedLayer
615
                return group;
616
                ///// CHEMA ComposedLayer
617
        }
618

    
619
        /*
620
         * (non-Javadoc)
621
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getFullExtent()
622
         */
623
        public Envelope getFullEnvelope() {
624
                Envelope rAux = null;
625
                boolean first = true;
626

    
627

    
628
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
629
                        FLayer capa = (FLayer) iter.next();
630
                        try{
631
                                if (first) {
632
                                        rAux = capa.getFullEnvelope();
633
                                        first=false;
634
                                } else {
635
                                        rAux.add(capa.getFullEnvelope());
636
                                }
637
                        }catch (Exception e) {
638
                                e.printStackTrace();//TODO hay que revisar para determinar el comportamiento que espera el usuario.
639
                        }
640
                }
641

    
642
                return rAux;
643
        }
644

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

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

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

    
692
        /**
693
         * Notifies all listeners associated to this collection of layers,
694
         *  that another layer has been added or replaced in the internal
695
         *  list of layers.
696
         *
697
         * @param e a layer collection event with the new layer
698
         */
699
        protected void callLayerAdded(LayerCollectionEvent event) {
700
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
701
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
702
                        ((LayerCollectionListener) iter.next()).layerAdded(event);
703
                }
704
        }
705

    
706
        /**
707
         * Notifies all listeners associated to this collection of layers,
708
         *  that another layer has been removed from the internal list of layers.
709
         *
710
         * @param e a layer collection event with the layer removed
711
         */
712
        protected void callLayerRemoved(LayerCollectionEvent event) {
713
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
714
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
715
                        ((LayerCollectionListener) iter.next()).layerRemoved(event);
716
                }
717
        }
718

    
719
        /**
720
         * Notifies all listeners associated to this collection of layers,
721
         *  that another layer has been moved in the internal list of layers.
722
         *
723
         * @param e a layer collection event with the layer moved, and the initial and final positions
724
         */
725
        protected void callLayerMoved(LayerPositionEvent event) {
726
                ArrayList aux = (ArrayList) layerCollectionListeners.clone();
727
                for (Iterator iter = aux.iterator(); iter.hasNext();) {
728
                        ((LayerCollectionListener) iter.next()).layerMoved(event);
729
                }
730
        }
731

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

    
752
                String[] s = new String[layers.size()];
753

    
754
                for (int i = 0; i < layers.size(); i++) {
755
                        s[i] = ((FLayer) layers.get(i)).getName();
756
                }
757

    
758
                xml.putProperty("LayerNames", s);
759

    
760
                for (int i = 0; i < layers.size(); i++) {
761
                        try {
762
                                XMLEntity xmlLayer=((FLayer) layers.get(i)).getXMLEntity();
763
                                xmlLayer.putProperty("tagName", "layer");
764
                                xml.addChild(xmlLayer);
765
                        }catch (XMLException e) {
766
                                e.printStackTrace();
767
                        }
768
                }
769

    
770
                return xml;
771
        }
772

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

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

    
828
                for (Iterator iter = layers.iterator(); iter.hasNext();) {
829
                        FLayer layer = (FLayer) iter.next();
830
                        layer.setCoordTrans(ct);
831
                }
832
        }
833
        /*
834
         * (non-Javadoc)
835
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#setAllActives(boolean)
836
         */
837
        public void setAllActives(boolean active) {
838
                FLayer lyr;
839

    
840
                for (int i = 0; i < layers.size(); i++) {
841
                        lyr = ((FLayer) layers.get(i));
842
                        lyr.setActive(active);
843

    
844
                        if (lyr instanceof LayerCollection) {
845
                                ((LayerCollection) lyr).setAllActives(active);
846
                        }
847
                }
848
        }
849

    
850
        /*
851
         * (non-Javadoc)
852
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.LayerCollection#getActives()
853
         */
854
        public FLayer[] getActives() {
855
                ArrayList ret = new ArrayList();
856
                LayersIterator it = new LayersIterator(this) {
857

    
858
                        public boolean evaluate(FLayer layer) {
859
                                return layer.isActive();
860
                        }
861

    
862
                };
863

    
864
                while (it.hasNext())
865
                {
866
                        ret.add(it.next());
867
                }
868
                return (FLayer[]) ret.toArray(new FLayer[0]);
869
        }
870

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

    
950
        }
951

    
952
        /*
953
         * (non-Javadoc)
954
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#getTocImageIcon()
955
         */
956
        public ImageIcon getTocImageIcon() {
957
                return new ImageIcon(MapContext.class.getResource("images/layerGroup.png"));
958
        }
959

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

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

    
995
                try {
996
                        if (name == null) {
997
                                name = xml.getName();
998
                        }
999

    
1000

    
1001
                        String className = xml.getStringProperty("className");
1002
                        Class clase = Class.forName(className);
1003
                        layer = (FLayer) clase.newInstance();
1004
                        if (FLayers.class.isAssignableFrom(clase)) {
1005
                                ((FLayers)layer).setMapContext(getMapContext());
1006
                                ((FLayers)layer).setParentLayer(this);
1007
                                //                        layer = new FLayers(getMapContext(),this);
1008
                                layer.setXMLEntity(xml);
1009
                        } else {
1010
                                // Capas Nuevas (externas)
1011
                                layer.setName(name);
1012
                                layer.setXMLEntity(xml);
1013
                                layer.load();
1014
                        }
1015

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

    
1157
                                        layer.setCoordTrans(ct);
1158
                                }
1159
                        }
1160
                } catch (XMLException e) {
1161
                        fmap.addLayerError(xml.getStringProperty("name"));
1162
                        throw new LoadLayerException(name,e);
1163
                } catch (ClassNotFoundException e) {
1164
                        fmap.addLayerError(xml.getStringProperty("name"));
1165
                        throw new LoadLayerException(name,e);
1166
                } catch (InstantiationException e) {
1167
                        fmap.addLayerError(xml.getStringProperty("name"));
1168
                        throw new LoadLayerException(name,e);
1169
                } catch (IllegalAccessException e) {
1170
                        fmap.addLayerError(xml.getStringProperty("name"));
1171
                        throw new LoadLayerException(name,e);
1172
                } catch (LoadLayerException e){
1173
                        fmap.addLayerError(xml.getStringProperty("name"));
1174
                        throw e;
1175
                }
1176
        }
1177

    
1178
        /**
1179
         * <p>Sets the <code>MapContext</code> that contains this layer node.</p>
1180
         *
1181
         * @param mapContext the <code>MapContext</code> that contains this layer node
1182
         */
1183
        public void setMapContext(MapContext mapContext) {
1184
                this.fmap = mapContext;
1185
        }
1186

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

    
1266
        public void accept(Visitor visitor) throws BaseException {
1267
                throw new NotSupportedOperationException(visitor, this);
1268
        }
1269

    
1270
        public void accept(LayersVisitor visitor) throws BaseException {
1271
                for (int i = 0; i < this.getLayersCount(); i++) {
1272
                        FLayer layer = this.getLayer(i);
1273
                        if (layer instanceof LayersVisitable) {
1274
                                ((LayersVisitable) layer).accept(visitor);
1275
                        } else {
1276
                                visitor.visit(layer);
1277
                        }
1278
                }
1279
        }
1280

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

    
1299
        }
1300

    
1301
        /*
1302
         * (non-Javadoc)
1303
         *
1304
         * @see org.gvsig.metadata.Metadata#getMetadataChildren()
1305
         */
1306
        public Set getMetadataChildren() {
1307
                Set ret = new TreeSet();
1308
                Iterator iter = this.layers.iterator();
1309
                while (iter.hasNext()) {
1310
                        ret.add(iter.next());
1311
                }
1312
                return ret;
1313
        }
1314

    
1315
        /*
1316
         * (non-Javadoc)
1317
         *
1318
         * @see org.gvsig.metadata.Metadata#getMetadataName()
1319
         */
1320
        public String getMetadataName() {
1321
                StringBuilder strb = new StringBuilder();
1322
                strb.append("Layer Group '");
1323
                strb.append(this.getName());
1324
                strb.append("': {");
1325
                Iterator iter = this.layers.iterator();
1326
                while (iter.hasNext()) {
1327
                        strb.append(((FLayer) iter.next()).getMetadataName());
1328
                        strb.append(",");
1329
                }
1330
                strb.append("}");
1331
                return strb.toString();
1332
        }
1333

    
1334

    
1335
        public void beginDraw(Graphics2D g, ViewPort viewPort) {
1336
                LayerDrawEvent beforeEvent = new LayerDrawEvent(this, g, viewPort, LayerDrawEvent.LAYER_BEFORE_DRAW);
1337
                fmap.fireLayerDrawingEvent(beforeEvent);
1338
        }
1339

    
1340
        public void endDraw(Graphics2D g, ViewPort viewPort) {
1341
                LayerDrawEvent afterEvent = new LayerDrawEvent(this, g, viewPort, LayerDrawEvent.LAYER_AFTER_DRAW);
1342
                fmap.fireLayerDrawingEvent(afterEvent);
1343
        }
1344

    
1345
}