Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.mapcontext / org.gvsig.fmap.mapcontext.api / src / main / java / org / gvsig / fmap / mapcontext / layers / vectorial / FLyrVect.java @ 40559

History | View | Annotate | Download (37.6 KB)

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

    
26
import java.awt.Graphics2D;
27
import java.awt.Point;
28
import java.awt.geom.AffineTransform;
29
import java.awt.geom.Point2D;
30
import java.awt.image.BufferedImage;
31
import java.util.Set;
32
import java.util.TreeSet;
33

    
34
import org.cresques.cts.ICoordTrans;
35
import org.cresques.cts.IProjection;
36
import org.slf4j.LoggerFactory;
37

    
38
import org.gvsig.compat.print.PrintAttributes;
39
import org.gvsig.fmap.dal.DataStore;
40
import org.gvsig.fmap.dal.exception.DataException;
41
import org.gvsig.fmap.dal.exception.ReadException;
42
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
43
import org.gvsig.fmap.dal.feature.FeatureQuery;
44
import org.gvsig.fmap.dal.feature.FeatureSet;
45
import org.gvsig.fmap.dal.feature.FeatureStore;
46
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
47
import org.gvsig.fmap.dal.feature.FeatureType;
48
import org.gvsig.fmap.dal.feature.exception.CreateGeometryException;
49
import org.gvsig.fmap.geom.Geometry;
50
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
51
import org.gvsig.fmap.geom.Geometry.TYPES;
52
import org.gvsig.fmap.geom.GeometryLocator;
53
import org.gvsig.fmap.geom.GeometryManager;
54
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
55
import org.gvsig.fmap.geom.primitive.Circle;
56
import org.gvsig.fmap.geom.primitive.Envelope;
57
import org.gvsig.fmap.geom.type.GeometryType;
58
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
59
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
60
import org.gvsig.fmap.mapcontext.MapContextLocator;
61
import org.gvsig.fmap.mapcontext.MapContextManager;
62
import org.gvsig.fmap.mapcontext.ViewPort;
63
import org.gvsig.fmap.mapcontext.exceptions.LegendLayerException;
64
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
65
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
66
import org.gvsig.fmap.mapcontext.exceptions.StartEditionLayerException;
67
import org.gvsig.fmap.mapcontext.layers.FLayer;
68
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
69
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
70
import org.gvsig.fmap.mapcontext.layers.SpatialCache;
71
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
72
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
73
import org.gvsig.fmap.mapcontext.rendering.legend.LegendException;
74
import org.gvsig.fmap.mapcontext.rendering.legend.events.FeatureDrawnNotification;
75
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendChangedEvent;
76
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendClearEvent;
77
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendContentsChangedListener;
78
import org.gvsig.fmap.mapcontext.rendering.legend.events.SymbolLegendEvent;
79
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelingStrategy;
80
import org.gvsig.fmap.mapcontext.rendering.symbols.CartographicSupport;
81
import org.gvsig.metadata.exceptions.MetadataException;
82
import org.gvsig.tools.ToolsLocator;
83
import org.gvsig.tools.dynobject.DynObjectSet;
84
import org.gvsig.tools.dynobject.DynStruct;
85
import org.gvsig.tools.exception.BaseException;
86
import org.gvsig.tools.locator.LocatorException;
87
import org.gvsig.tools.observer.Observable;
88
import org.gvsig.tools.observer.Observer;
89
import org.gvsig.tools.persistence.PersistenceManager;
90
import org.gvsig.tools.persistence.PersistentState;
91
import org.gvsig.tools.persistence.exception.PersistenceException;
92
import org.gvsig.tools.persistence.exception.PersistenceRuntimeException;
93
import org.gvsig.tools.task.Cancellable;
94

    
95
/**
96
 * Capa b?sica Vectorial.
97
 * 
98
 */
99

    
100
public class FLyrVect extends FLyrDefault implements VectorLayer,
101
    LegendContentsChangedListener, Observer {
102

    
103
    final static private org.slf4j.Logger logger =
104
        LoggerFactory.getLogger(FLyrVect.class);
105
    private final GeometryManager geomManager =
106
        GeometryLocator.getGeometryManager();
107

    
108
    /** Leyenda de la capa vectorial */
109
    private IVectorLegend legend;
110
    private int typeShape = -1;
111
    private FeatureStore featureStore = null;
112
    private SpatialCache spatialCache = new SpatialCache();
113

    
114
    /**
115
     * An implementation of gvSIG spatial index
116
     */
117
    // protected ISpatialIndex spatialIndex = null;
118
    private IVectorLegend loadLegend = null;
119

    
120
    private boolean isLabeled;
121
    protected ILabelingStrategy strategy;
122
//        private ReprojectDefaultGeometry reprojectTransform;
123

    
124
    public FLyrVect() {
125
        super();
126
    }
127
    
128
        public String getTocImageIcon() {
129
            if (this.isAvailable()) {
130
            return MapContextLocator.getMapContextManager().getIconLayer(this.getDataStore());
131
            } else {
132
                /*
133
                 * data store can be be null,
134
                 * for example, a layer not loaded from persistence
135
                 */
136
            return "layer-icon-unavailable";
137
            }
138
                
139
        }
140

    
141
    /**
142
     * Devuelve el VectorialAdapater de la capa.
143
     * 
144
     * @return VectorialAdapter.
145
     */
146
    public DataStore getDataStore() {
147
        if (!this.isAvailable()) {
148
            return null;
149
        }
150
        return featureStore;
151
    }
152
    
153
    /**
154
     * Asigna el data-store a la capa.
155
     * Esta operacion no se deneria poder hacer desde fuera de la clase.
156
     * 
157
     * @param dataStore
158
     * @throws LoadLayerException
159
     * @deprecated use {@link #bindToDataStore(DataStore)}
160
     */
161
    public void setDataStore(DataStore dataStore) throws LoadLayerException {
162
            bindToDataStore(dataStore);
163
    }
164
    
165
    /**
166
     * Enlaza la capa con el DataStore indicado.
167
     *  
168
     * @param dataStore
169
     * @throws LoadLayerException
170
     */
171
    protected void bindToDataStore(DataStore dataStore) throws LoadLayerException {
172
        if (this.featureStore != null && this.featureStore != dataStore) {
173
            this.featureStore.deleteObserver(this);
174
        }
175

    
176
        featureStore = (FeatureStore) dataStore;
177

    
178
        MapContextManager mapContextManager =
179
            MapContextLocator.getMapContextManager();
180
        
181
        //Set the legend
182
        IVectorLegend legend =
183
            (IVectorLegend)mapContextManager.getLegend(dataStore);
184

    
185
        if (legend == null) {
186
            throw new LegendLayerException(this.getName());
187
        }
188

    
189
        this.setLegend(legend);
190

    
191
        //Set the labeling strategy
192
        ILabelingStrategy labeler = 
193
            (ILabelingStrategy) mapContextManager.getLabelingStrategy(dataStore);
194

    
195
        if (labeler != null) {
196
            labeler.setLayer(this);
197
            this.setLabelingStrategy(labeler);
198
            this.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t?
199
                                     // etiquetes?????
200
        }
201

    
202
        this.delegate(dataStore);
203

    
204
        dataStore.addObserver(this);
205

    
206
        ToolsLocator.getDisposableManager().bind(dataStore);
207
    }
208

    
209
    public Envelope getFullEnvelope() throws ReadException {
210
        Envelope rAux;
211
        try {
212
            rAux = getFeatureStore().getEnvelope();
213
        } catch (BaseException e) {
214
            throw new ReadException(getName(), e);
215
        }
216

    
217
        // Esto es para cuando se crea una capa nueva con el fullExtent de ancho
218
        // y alto 0.
219
        if (rAux == null || rAux.isEmpty() || rAux.getMaximum(0) - rAux.getMinimum(0) == 0
220
            && rAux.getMaximum(1) - rAux.getMinimum(1) == 0) {
221
            try {
222
                rAux =
223
                    geomManager.createEnvelope(0, 0, 90, 90, SUBTYPES.GEOM2D);
224
            } catch (CreateEnvelopeException e) {
225
                logger.error("Error creating the envelope", e);
226
                e.printStackTrace();
227
            }
228
        }
229
        // Si existe reproyecci?n, reproyectar el extent
230
        ICoordTrans ct = getCoordTrans();
231
        if (ct != null) {
232
                rAux = rAux.convert(ct);
233
        }
234
        return rAux;
235

    
236
    }
237

    
238
    /**
239
     * Draws using IFeatureIterator. This method will replace the old draw(...)
240
     * one.
241
     * 
242
     * @autor jaume dominguez faus - jaume.dominguez@iver.es
243
     * @param image
244
     * @param g
245
     * @param viewPort
246
     * @param cancel
247
     * @param scale
248
     * @throws ReadDriverException
249
     */
250
    public void draw(BufferedImage image,
251
        Graphics2D g,
252
        ViewPort viewPort,
253
        Cancellable cancel,
254
        double scale) throws ReadException {
255

    
256
        if (legend == null) {
257
            return;
258
        }
259

    
260
        if (!this.isWithinScale(scale)) {
261
            return;
262
        }
263
        if (cancel.isCanceled()) {
264
            return;
265
        }
266

    
267
        if (spatialCache.isEnabled()) {
268
            spatialCache.clearAll();
269
            legend.addDrawingObserver(this);
270
        }
271

    
272
        FeatureQuery featureQuery = null;
273
        try {
274
            FeatureAttributeDescriptor featureAttributeDescriptor =
275
                getFeatureStore().getDefaultFeatureType().getDefaultTimeAttribute();
276

    
277
            if ((viewPort.getTime() != null) && (featureAttributeDescriptor != null)){
278
                featureQuery = getFeatureStore().createFeatureQuery();
279
                IntersectsTimeEvaluator intersectsTimeEvaluator =
280
                    new IntersectsTimeEvaluator(viewPort.getTime(), featureAttributeDescriptor.getName());
281
                featureQuery.addFilter(intersectsTimeEvaluator);
282
            }
283
        } catch (DataException e1) {
284
            logger.error("Impossible to get the temporal filter", e1);
285
        }
286

    
287
        try {
288
            
289
            long tini = System.currentTimeMillis();
290
            
291
            legend.draw(image,
292
                g,
293
                viewPort,
294
                cancel,
295
                scale,
296
                null,
297
                getCoordTrans(),
298
                getFeatureStore(),
299
                featureQuery);
300
            
301
            logger.debug("Layer " + this.getName() + " drawn in " +
302
                (System.currentTimeMillis() - tini) + " milliseconds.");
303

    
304
        } catch (LegendException e) {
305
            this.setVisible(false);
306
            this.setActive(false);
307
            throw new ReadException(getName(), e);
308
        } finally {
309
            if (spatialCache.isEnabled()) {
310
                legend.deleteDrawingObserver(this);
311
            }
312
        }
313
    }
314

    
315
    public void print(Graphics2D g,
316
        ViewPort viewPort,
317
        Cancellable cancel,
318
        double scale,
319
        PrintAttributes properties) throws ReadException {
320
        if (!this.isWithinScale(scale)) {
321
            return;
322
        }
323
        if (cancel.isCanceled()) {
324
            return;
325
        }
326

    
327
        try {
328
            legend.print(g,
329
                viewPort,
330
                cancel,
331
                scale,
332
                null,
333
                getCoordTrans(),
334
                getFeatureStore(),
335
                null,
336
                properties);
337

    
338
        } catch (LegendException e) {
339
            this.setVisible(false);
340
            this.setActive(false);
341
            throw new ReadException(getName(), e);
342
        }
343
    }
344

    
345
    public void setLegend(IVectorLegend legend) throws LegendLayerException {
346
        if (this.legend == legend) {
347
            return;
348
        }
349
        if (this.legend != null && this.legend.equals(legend)) {
350
            return;
351
        }
352
        IVectorLegend oldLegend = this.legend;
353
        this.legend = legend;
354
        if (oldLegend != null) {
355
            oldLegend.removeLegendListener(this);
356
            oldLegend.deleteDrawingObserver(this);
357
        }
358
        if (legend != null) {
359
            this.legend.addDrawingObserver(this);
360
            this.legend.addLegendListener(this);
361
        }
362
        LegendChangedEvent e =
363
            LegendChangedEvent.createLegendChangedEvent(oldLegend, this.legend);
364
        e.setLayer(this);
365
        updateDrawVersion();
366
        callLegendChanged(e);
367
    }
368

    
369
    /**
370
     * Devuelve la Leyenda de la capa.
371
     * 
372
     * @return Leyenda.
373
     */
374
    public ILegend getLegend() {
375
        return legend;
376
    }
377

    
378
    public int getShapeType() throws ReadException {
379
            if (typeShape == -1) {
380
                    FeatureType featureType = null;
381
                    try {
382
                            if( getDataStore()!=null ){
383
                                    featureType =
384
                                            (((FeatureStore) getDataStore()).getDefaultFeatureType());
385
                            }
386
                    } catch (DataException e) {
387
                            throw new ReadException(getName(), e);
388
                    }
389
                    if( featureType!=null ){
390
                            int indexGeom = featureType.getDefaultGeometryAttributeIndex();
391
                            typeShape =
392
                                    featureType.getAttributeDescriptor(indexGeom).getGeometryType();
393
                    }
394
            }
395
            return typeShape;
396
    }
397

    
398
    /**
399
     * Returns the layer's geometry type
400
     * 
401
     * @return the geometry type
402
     * 
403
     * @throws ReadException
404
     *             if there is an error getting the geometry type
405
     */
406
    public GeometryType getGeometryType() throws ReadException {
407
        FeatureType featureType = null;
408
        try {
409
            if (getDataStore() != null) {
410
                featureType =
411
                    (((FeatureStore) getDataStore()).getDefaultFeatureType());
412
            }
413
        } catch (DataException e) {
414
            throw new ReadException(getName(), e);
415
        }
416
        return featureType == null ? null : featureType
417
            .getDefaultGeometryAttribute().getGeomType();
418
    }
419

    
420
    public void saveToState(PersistentState state) throws PersistenceException {
421

    
422
        if (!this.isAvailable()) {
423
            return;
424
        }
425

    
426
        super.saveToState(state);
427

    
428
        if (getLegend() != null) {
429
            state.set("legend", getLegend());
430
        }
431

    
432
        FeatureStore fst = null;
433
        fst = getFeatureStore();
434

    
435
        if (fst != null) {
436
            state.set("featureStore", fst);
437
        }
438

    
439
        state.set("isLabeled", isLabeled);
440

    
441
        if (strategy != null) {
442
            state.set("labelingStrategy", strategy);
443
        }
444

    
445
        if (getLinkProperties() != null) {
446
            state.set("linkProperties", getLinkProperties());
447
        }
448

    
449
        // state.set("bHasJoin", bHasJoin);
450
        state.set("typeShape", typeShape);
451
    }
452

    
453

    
454
    public void loadFromState(PersistentState state) throws PersistenceException {
455

    
456
        super.loadFromState(state);
457
        DataStore store = null;
458
        try {
459
                store = (DataStore) state.get("featureStore");
460
        } catch (PersistenceRuntimeException e) {
461
            logger.debug("Unable to load store from persistence in layer: " + this.getName(), e);
462
                        this.setAvailable(false);
463
                        return;
464
                }
465
        try {
466
            this.bindToDataStore(store);
467
        } catch (LoadLayerException e) {
468
            throw new PersistenceException("While loading FLyrVect from state.",
469
                e);
470
        }
471

    
472
        IVectorLegend lgnd = (IVectorLegend) state.get("legend");
473
        try {
474
            this.setLegend(lgnd);
475
        } catch (LegendLayerException e) {
476
            throw new PersistenceException("While loading FLyrVect from state.",
477
                e);
478
        }
479

    
480
        Boolean isLbl = new Boolean(false);
481
        ILabelingStrategy lblst = null;
482

    
483
        try {
484
            isLbl = (Boolean) state.get("isLabeled");
485
            if (isLbl.booleanValue()) {
486
                lblst = (ILabelingStrategy) state.get("labelingStrategy");
487
            }
488
        } catch (Exception ex) {
489
            throw new PersistenceException("While loading FLyrVect from state.",
490
                ex);
491
        }
492

    
493
        /*
494
         * String _labelFieldName = null;
495
         * String _labelfield = null;
496
         */
497

    
498
        if (isLbl.booleanValue()) {
499
            this.setIsLabeled(true);
500
            this.setLabelingStrategy(lblst);
501
        } else {
502
            this.setIsLabeled(false);
503
            this.setLabelingStrategy(null);
504
        }
505

    
506
        typeShape = state.getInt("typeShape");
507

    
508
    }
509

    
510
    /**
511
     * Sobreimplementaci?n del m?todo toString para que las bases de datos
512
     * identifiquen la capa.
513
     * 
514
     * @return DOCUMENT ME!
515
     */
516
    public String toString() {
517
        /*
518
         * Se usa internamente para que la parte de datos identifique de forma
519
         * un?voca las tablas
520
         */
521
        String ret = super.toString();
522

    
523
        return "layer" + ret.substring(ret.indexOf('@') + 1);
524
    }
525

    
526
    public boolean isEditing() {
527
        FeatureStore fs = getFeatureStore();
528
        if (fs == null) {
529
            /*
530
             * This happens when layer is not available, for example,
531
             * it was not possible to load from persistence
532
             */
533
            return false;
534
        } else {
535
            return fs.isEditing();
536
        }
537
    }
538
    
539
    
540
    public void setEditing(boolean b) throws StartEditionLayerException {
541
        
542
        try {
543
            throw new RuntimeException();
544
        } catch (Throwable th) {
545
            logger.info("This method is deprecated. ", th);
546
        }
547
        
548
        if (b == super.isEditing()) {
549
            return;
550
        }
551
        
552
        super.setEditing(b);
553
        FeatureStore fs = getFeatureStore();
554
        if (b) {
555
            try {
556
                fs.edit();
557
            } catch (DataException e) {
558
                throw new StartEditionLayerException(getName(), e);
559
            }
560
        }
561
        setSpatialCacheEnabled(b);
562
        callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
563
    }
564

    
565

    
566
    /**
567
     * @deprecated Use {@link #getSpatialCache()}
568
     */
569
    public void clearSpatialCache() {
570
        spatialCache.clearAll();
571
    }
572

    
573
    /**
574
     * @deprecated Use {@link #getSpatialCache()}
575
     */
576
    public boolean isSpatialCacheEnabled() {
577
        return spatialCache.isEnabled();
578
    }
579

    
580
    /**
581
     * @deprecated Use {@link #getSpatialCache()}
582
     */
583
    public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
584
        spatialCache.setEnabled(spatialCacheEnabled);
585
    }
586

    
587
    public SpatialCache getSpatialCache() {
588
        return spatialCache;
589
    }
590

    
591
    /**
592
     * Siempre es un numero mayor de 1000
593
     * 
594
     * @param maxFeatures
595
     */
596
    public void setMaxFeaturesInEditionCache(int maxFeatures) {
597
        if (maxFeatures > spatialCache.getMaxFeatures()) {
598
            spatialCache.setMaxFeatures(maxFeatures);
599
        }
600

    
601
    }
602

    
603
    /**
604
     * This method returns a boolean that is used by the FPopMenu
605
     * to make visible the properties menu or not. It is visible by
606
     * default, and if a later don't have to show this menu only
607
     * has to override this method.
608
     * 
609
     * @return
610
     *         If the properties menu is visible (or not)
611
     */
612
    public boolean isPropertiesMenuVisible() {
613
        return true;
614
    }
615

    
616
    public void reload() throws ReloadLayerException {
617
        super.reload();
618
        try {
619
            getFeatureStore().refresh();
620
        } catch (Exception e) {
621
            throw new ReloadLayerException(getName(), e);
622
        }
623
    }
624

    
625
    protected void setLoadSelection(Object xml) {
626
        // this.loadSelection = xml;
627
    }
628

    
629
    protected void setLoadLegend(IVectorLegend legend) {
630
        this.loadLegend = legend;
631
    }
632

    
633
    protected void putLoadSelection() {
634
        // if (this.loadSelection == null) return;
635
        // try {
636
        // this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
637
        // } catch (ReadDriverException e) {
638
        // throw new XMLException(e);
639
        // }
640
        // this.loadSelection = null;
641

    
642
    }
643

    
644
    protected void putLoadLegend() throws LegendLayerException {
645
        if (this.loadLegend == null) {
646
            return;
647
        }
648
        this.setLegend(this.loadLegend);
649
        this.loadLegend = null;
650
    }
651

    
652
    protected void cleanLoadOptions() {
653
        this.loadLegend = null;
654
    }
655

    
656
    public boolean isWritable() {
657
        return getFeatureStore().allowWrite();
658
    }
659

    
660
    public FLayer cloneLayer() throws Exception {
661
        FLyrVect clonedLayer = new FLyrVect();
662
        clonedLayer.bindToDataStore(getDataStore());
663
        // if (isJoined()) {
664
        // clonedLayer.setIsJoined(true);
665
        // }
666
        clonedLayer.setVisible(isVisible());
667
        // clonedLayer.setISpatialIndex(getISpatialIndex());
668
        clonedLayer.setName(getName());
669
        clonedLayer.setCoordTrans(getCoordTrans());
670

    
671
        clonedLayer.setLegend((IVectorLegend) getLegend().cloneLegend());
672

    
673
        clonedLayer.setIsLabeled(isLabeled());
674
        ILabelingStrategy labelingStrategy = getLabelingStrategy();
675
        if (labelingStrategy != null) {
676
            clonedLayer.setLabelingStrategy(labelingStrategy);
677
        }
678

    
679
        return clonedLayer;
680
    }
681

    
682
    protected boolean isOnePoint(AffineTransform graphicsTransform,
683
        ViewPort viewPort,
684
        double dpi,
685
        CartographicSupport csSym,
686
        Geometry geom,
687
        int[] xyCoords) {
688
        return isOnePoint(graphicsTransform, viewPort, geom, xyCoords)
689
            && csSym.getCartographicSize(viewPort, dpi, geom) <= 1;
690
    }
691

    
692
    private boolean isOnePoint(AffineTransform graphicsTransform,
693
        ViewPort viewPort,
694
        Geometry geom,
695
        int[] xyCoords) {
696
        boolean onePoint = false;
697
        int type = geom.getType();
698
        if (type == Geometry.TYPES.NULL) {
699
            return false;
700
        }
701
        if (type != Geometry.TYPES.POINT && type != Geometry.TYPES.MULTIPOINT) {
702

    
703
            Envelope geomBounds = geom.getEnvelope();
704

    
705
            // ICoordTrans ct = getCoordTrans();
706

    
707
            // Se supone que la geometria ya esta reproyectada
708
            // if (ct!=null) {
709
            // // geomBounds = ct.getInverted().convert(geomBounds);
710
            // geomBounds = geomBounds.convert(ct);
711
            // }
712

    
713
            double dist1Pixel = viewPort.getDist1pixel();
714

    
715
            onePoint =
716
                (geomBounds.getLength(0) <= dist1Pixel && geomBounds.getLength(1) <= dist1Pixel);
717

    
718
            if (onePoint) {
719
                // avoid out of range exceptions
720
                org.gvsig.fmap.geom.primitive.Point p;
721
                try {
722
                    p =
723
                        geomManager.createPoint(geomBounds.getMinimum(0),
724
                            geomBounds.getMinimum(1),
725
                            SUBTYPES.GEOM2D);
726
                    p.transform(viewPort.getAffineTransform());
727
                    p.transform(graphicsTransform);
728
                    xyCoords[0] = (int) p.getX();
729
                    xyCoords[1] = (int) p.getY();
730
                } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
731
                    logger.error("Error creating a point", e);
732
                }
733

    
734
            }
735

    
736
        }
737
        return onePoint;
738
    }
739

    
740
    public boolean isLabeled() {
741
        return isLabeled;
742
    }
743

    
744
    public void setIsLabeled(boolean isLabeled) {
745
        this.isLabeled = isLabeled;
746
    }
747

    
748
    public ILabelingStrategy getLabelingStrategy() {
749
        return strategy;
750
    }
751

    
752
    public void setLabelingStrategy(ILabelingStrategy strategy) {
753
        this.strategy = strategy;
754
        if (strategy == null) {
755
            return;
756
        }
757
        strategy.setLayer(this);
758
        updateDrawVersion();
759
    }
760

    
761
    public void drawLabels(BufferedImage image,
762
        Graphics2D g,
763
        ViewPort viewPort,
764
        Cancellable cancel,
765
        double scale,
766
        double dpi) throws ReadException {
767
        if (strategy != null && isWithinScale(scale)) {
768
            strategy.draw(image, g, viewPort, cancel, dpi);
769
        }
770
    }
771

    
772
    public void printLabels(Graphics2D g,
773
        ViewPort viewPort,
774
        Cancellable cancel,
775
        double scale,
776
        PrintAttributes properties) throws ReadException {
777
        if (strategy != null) {
778
            strategy.print(g, viewPort, cancel, properties);
779
        }
780
    }
781

    
782
    /**
783
     * Return true, because a Vectorial Layer supports HyperLink
784
     * 
785
     * @deprecated the hiperlink functionaliti is out the layer now
786
     */
787
    public boolean allowLinks() {
788
        return false;
789
    }
790

    
791
    public void load() throws LoadLayerException {
792
        super.load();
793
    }
794

    
795
    public FeatureStore getFeatureStore() {
796
        return (FeatureStore) getDataStore();
797
    }
798

    
799
    /**
800
     * @deprecated use instead {@link #queryByPoint(org.gvsig.fmap.geom.primitive.Point, double, FeatureType)}
801
     */
802
    public FeatureSet queryByPoint(Point2D mapPoint,
803
        double tol,
804
        FeatureType featureType) throws DataException {
805
        logger.warn("Deprecated use of queryByPoint.");
806
        GeometryManager manager = GeometryLocator.getGeometryManager();
807
        org.gvsig.fmap.geom.primitive.Point center;
808
        try {
809
            center =
810
                (org.gvsig.fmap.geom.primitive.Point) manager.create(TYPES.POINT,
811
                    SUBTYPES.GEOM2D);
812
            center.setX(mapPoint.getX());
813
            center.setY(mapPoint.getY());
814
            Circle circle =
815
                (Circle) manager.create(TYPES.CIRCLE, SUBTYPES.GEOM2D);
816
            circle.setPoints(center, tol);
817
            return queryByGeometry(circle, featureType);
818
        } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
819
            throw new CreateGeometryException(TYPES.CIRCLE, SUBTYPES.GEOM2D, e);
820
        }
821
    }
822

    
823
    public FeatureSet queryByPoint(org.gvsig.fmap.geom.primitive.Point point,
824
        double tol,
825
        FeatureType featureType) throws DataException {
826
        GeometryManager manager = GeometryLocator.getGeometryManager();
827
        try {
828
            Circle circle =
829
                (Circle) manager.create(TYPES.CIRCLE, SUBTYPES.GEOM2D);
830
            circle.setPoints(point, tol);
831
            return queryByGeometry(circle, featureType);
832
        } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
833
            throw new CreateGeometryException(TYPES.CIRCLE, SUBTYPES.GEOM2D, e);
834
        }
835
    }
836

    
837
    public FeatureSet queryByGeometry(Geometry geom, FeatureType featureType) throws DataException {
838
        FeatureQuery featureQuery = featureStore.createFeatureQuery();
839
        String geomName =
840
            featureStore.getDefaultFeatureType()
841
                .getDefaultGeometryAttributeName();
842
        featureQuery.setFeatureType(featureType);
843
        
844
        Geometry query_geo = fromViewPortCRSToSourceCRS(this, geom, true);
845
        IProjection query_proj = getMapContext().getProjection();
846
        if (this.getCoordTrans() != null) {
847
            query_proj = this.getCoordTrans().getPOrig(); 
848
        }
849

    
850
        IntersectsGeometryEvaluator iee =
851
            new IntersectsGeometryEvaluator(
852
                query_geo,
853
                query_proj,
854
                featureStore.getDefaultFeatureType(),
855
                geomName);
856
        featureQuery.setFilter(iee);
857
        featureQuery.setAttributeNames(null);
858
        return getFeatureStore().getFeatureSet(featureQuery);
859

    
860
    }
861

    
862
    /**
863
     * It return the {@link FeatureSet} that intersects with the envelope.
864
     * @param envelope
865
     *          envelope that defines the area for the query.
866
     * @param featureType
867
     *          only the features with this feature type are used in
868
     *          the query.    
869
     * @return
870
     *          the set of features that intersect with the envelope.
871
     * @throws DataException
872
     */
873
    public FeatureSet queryByEnvelope(Envelope envelope, FeatureType featureType) throws DataException {
874
        return queryByEnvelope(envelope, featureType, null);
875
    }
876

    
877
    /**
878
     * It return the {@link FeatureSet} that intersects with the envelope.
879
     * @param envelope
880
     *          envelope that defines the area for the query in viewport CRS
881
     * @param featureType
882
     *          only the features with this feature type are used in
883
     *          the query.
884
     * @param names
885
     *          the feature attributes that have to be checked.
886
     * @return
887
     *          the set of features that intersect with the envelope.
888
     * @throws DataException
889
     */
890
    public FeatureSet queryByEnvelope(Envelope envelope,
891
        FeatureType featureType,
892
        String[] names) throws DataException {
893
        FeatureQuery featureQuery = featureStore.createFeatureQuery();
894
        if (names == null) {
895
            featureQuery.setFeatureType(featureType);
896
        } else {
897
            featureQuery.setAttributeNames(names);
898
            featureQuery.setFeatureTypeId(featureType.getId());
899
        }
900
        String geomName = featureStore.getDefaultFeatureType()
901
                .getDefaultGeometryAttributeName();
902
        
903
        Envelope query_env = fromViewPortCRSToSourceCRS(this, envelope);
904
        IProjection query_proj = getMapContext().getProjection();
905
        if (this.getCoordTrans() != null) {
906
            query_proj = this.getCoordTrans().getPOrig(); 
907
        }
908
        
909
        IntersectsGeometryEvaluator iee =
910
            new IntersectsGeometryEvaluator(
911
                query_env.getGeometry(), query_proj, 
912
                featureStore.getDefaultFeatureType(),
913
                geomName);
914
        featureQuery.setFilter(iee);
915
        return getFeatureStore().getFeatureSet(featureQuery);
916

    
917
    }
918

    
919
    public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel) throws LoadLayerException,
920
        DataException {
921

    
922
        return getInfo(p, tolerance, cancel, true);
923
    }
924

    
925
    public DynObjectSet getInfo(Point p,
926
        double tolerance,
927
        Cancellable cancel,
928
        boolean fast) throws LoadLayerException, DataException {
929
        Point2D infop = new Point2D.Double(p.x, p.y);
930
        Point2D pReal = this.getMapContext().getViewPort().toMapPoint(infop);
931
        return queryByPoint(pReal,
932
            tolerance,
933
            getFeatureStore().getDefaultFeatureType()).getDynObjectSet(fast);
934
    }
935

    
936
    public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p,
937
        double tolerance) throws LoadLayerException, DataException {
938
        return queryByPoint(p,tolerance, getFeatureStore().getDefaultFeatureType()).getDynObjectSet(false);
939
    }
940
    
941
    public void legendCleared(LegendClearEvent event) {
942
        this.updateDrawVersion();
943
        LegendChangedEvent e =
944
            LegendChangedEvent.createLegendChangedEvent(legend, legend);
945
        this.callLegendChanged(e);
946
    }
947

    
948
    public boolean symbolChanged(SymbolLegendEvent e) {
949
        this.updateDrawVersion();
950
        LegendChangedEvent ev =
951
            LegendChangedEvent.createLegendChangedEvent(legend, legend);
952
        this.callLegendChanged(ev);
953
        return true;
954
    }
955

    
956
    public void update(Observable observable, Object notification) {
957
        if (observable.equals(this.featureStore)) {
958
            if (notification instanceof FeatureStoreNotification) {
959
                FeatureStoreNotification event =
960
                    (FeatureStoreNotification) notification;
961
                if (event.getType() == FeatureStoreNotification.AFTER_DELETE
962
                    || event.getType() == FeatureStoreNotification.AFTER_UNDO
963
                    || event.getType() == FeatureStoreNotification.AFTER_REDO
964
                    || event.getType() == FeatureStoreNotification.AFTER_REFRESH
965
                    || event.getType() == FeatureStoreNotification.AFTER_UPDATE
966
                    || event.getType() == FeatureStoreNotification.AFTER_UPDATE_TYPE
967
                    || event.getType() == FeatureStoreNotification.SELECTION_CHANGE
968
                    || event.getType() == FeatureStoreNotification.AFTER_INSERT) {
969
                    this.updateDrawVersion();
970
                    
971
                } else if (event.getType() == FeatureStoreNotification.AFTER_CANCELEDITING) {
972
                    
973
                    setSpatialCacheEnabled(false);
974
                    callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
975
                    this.updateDrawVersion();
976
                    
977
                } else if (event.getType() == FeatureStoreNotification.AFTER_STARTEDITING) {
978
                    
979
                    setSpatialCacheEnabled(true);
980
                    callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
981

    
982
                } else if (event.getType() == FeatureStoreNotification.TRANSFORM_CHANGE){
983
                    //If a transform has to be applied, try to reload the layer.
984
                    try {
985
                        reload();
986
                    } catch (ReloadLayerException e) {
987
                        this.setAvailable(false);
988
                    }
989
                } else if (event.getType() == FeatureStoreNotification.RESOURCE_CHANGED) {
990
                    this.setAvailable(false);
991
                } else         if (event.getType() == FeatureStoreNotification.AFTER_FINISHEDITING) {
992
                    this.setAvailable(true);
993
                    setSpatialCacheEnabled(false);
994
                    callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
995
                    this.updateDrawVersion();
996
                }
997
            }
998
        }
999
        else if (notification instanceof FeatureDrawnNotification
1000
            && isEditing()) {
1001
            // This code is needed only on edition.
1002
            Geometry geometry =
1003
                ((FeatureDrawnNotification) notification).getDrawnGeometry();
1004
            spatialCache.insert(geometry.getEnvelope(), geometry);
1005
        }
1006
    }
1007

    
1008
    /*
1009
     * (non-Javadoc)
1010
     * 
1011
     * @see org.gvsig.metadata.Metadata#getMetadataChildren()
1012
     */
1013
    public Set getMetadataChildren() {
1014
        Set ret = new TreeSet();
1015
        ret.add(this.featureStore);
1016
        return ret;
1017
    }
1018

    
1019
    /*
1020
     * (non-Javadoc)
1021
     * 
1022
     * @see org.gvsig.metadata.Metadata#getMetadataID()
1023
     */
1024
    public Object getMetadataID() throws MetadataException {
1025
        return "Layer(" + this.getName() + "):"
1026
            + this.featureStore.getMetadataID();
1027
    }
1028

    
1029
    
1030

    
1031
    public GeometryType getTypeVectorLayer() throws DataException,
1032
        LocatorException,
1033
        GeometryTypeNotSupportedException,
1034
        GeometryTypeNotValidException {
1035
        // FIXME Esto deberia de pedirse a FType!!!!
1036
        FeatureStore fs = this.getFeatureStore();
1037
        FeatureType fType = fs.getDefaultFeatureType();
1038
        FeatureAttributeDescriptor attr =
1039
            fType.getAttributeDescriptor(fType.getDefaultGeometryAttributeIndex());
1040
        GeometryType geomType =
1041
            GeometryLocator.getGeometryManager()
1042
                .getGeometryType(attr.getGeometryType(),
1043
                    attr.getGeometrySubType());
1044
        return geomType;
1045
    }
1046

    
1047
    public static void registerPersistent() {
1048
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
1049
        if (manager.getDefinition(FLyrDefault.class) == null) {
1050
            FLyrDefault.registerPersistent();
1051
        }
1052
        DynStruct definition =
1053
            manager.addDefinition(FLyrVect.class,
1054
                "FLyrVect",
1055
                "FLyrVect Persistence definition",
1056
                null,
1057
                null);
1058
        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE,
1059
            "FLyrDefault");
1060

    
1061
        definition.addDynFieldObject("legend")
1062
            .setClassOfValue(IVectorLegend.class)
1063
            .setMandatory(true);
1064
        definition.addDynFieldObject("featureStore")
1065
            .setClassOfValue(FeatureStore.class)
1066
            .setMandatory(true);
1067
        definition.addDynFieldBoolean("isLabeled").setMandatory(true);
1068
        definition.addDynFieldInt("typeShape").setMandatory(true);
1069
        definition.addDynFieldObject("labelingStrategy")
1070
            .setClassOfValue(ILabelingStrategy.class)
1071
            .setMandatory(false);
1072

    
1073
    }
1074

    
1075
    protected void doDispose() throws BaseException {
1076
        dispose(featureStore);
1077
        spatialCache.clearAll();
1078
    }
1079
    
1080
    /**
1081
     * Returns envelope in layer's data source CRS
1082
     * from envelope provided in viewport CRS
1083
     * 
1084
     * @param lyr
1085
     * @param env
1086
     * @return
1087
     */
1088
    public static Envelope fromViewPortCRSToSourceCRS(FLayer lyr, Envelope env) {
1089

    
1090
        if (lyr == null || env == null) {
1091
            return null;
1092
        }
1093

    
1094
        ICoordTrans ct = lyr.getCoordTrans();
1095
        if (ct == null) {
1096
            return env;
1097
        } else {
1098
            return env.convert(ct.getInverted());
1099
        }
1100
    }
1101

    
1102
    /**
1103
     * Returns geometry in layer's data source CRS
1104
     * from geometry provided in viewport CRS
1105
     * 
1106
     * @param lyr
1107
     * @param geo
1108
     * @param clone
1109
     * @return
1110
     */
1111
    public static Geometry fromViewPortCRSToSourceCRS(
1112
        FLayer lyr,
1113
        Geometry geo,
1114
        boolean clone) {
1115
        
1116
        if (lyr == null || geo == null) {
1117
            return null;
1118
        }
1119
        ICoordTrans ct = lyr.getCoordTrans();
1120
        Geometry resp = geo;
1121
        if (clone) {
1122
            resp = resp.cloneGeometry();
1123
        }
1124
        if (ct != null) {
1125
            resp.reProject(ct.getInverted());
1126
        }
1127
        return resp;
1128
    }
1129

    
1130
    
1131
}