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

History | View | Annotate | Download (38.9 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
        DataStore store = null;
457
        try {
458
            super.loadFromState(state);
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

    
466
        try {
467
            this.bindToDataStore(store);
468
        } catch (LoadLayerException e) {
469
            throw new PersistenceException("While loading FLyrVect from state.",
470
                e);
471
        }
472
        
473
        IVectorLegend lgnd = null;
474
        
475
        try {
476
            lgnd = (IVectorLegend) state.get("legend");
477
        } catch (PersistenceRuntimeException pre) {
478
            /*
479
             * For example, symbol image file not found
480
             */
481
            logger.debug("Unable to instantiate persisted lagend.", pre);
482
            this.setAvailable(false);
483
            return;
484
        }
485
        
486
        try {
487
            this.setLegend(lgnd);
488
        } catch (LegendLayerException e) {
489
            throw new PersistenceException("While loading FLyrVect from state.", e);
490
        }
491

    
492
        Boolean isLbl = new Boolean(false);
493
        ILabelingStrategy lblst = null;
494

    
495
        try {
496
            isLbl = (Boolean) state.get("isLabeled");
497
            if (isLbl.booleanValue()) {
498
                lblst = (ILabelingStrategy) state.get("labelingStrategy");
499
            }
500
        } catch (Exception ex) {
501
            throw new PersistenceException("While loading FLyrVect from state.",
502
                ex);
503
        }
504

    
505
        /*
506
         * String _labelFieldName = null;
507
         * String _labelfield = null;
508
         */
509

    
510
        if (isLbl.booleanValue()) {
511
            this.setIsLabeled(true);
512
            this.setLabelingStrategy(lblst);
513
        } else {
514
            this.setIsLabeled(false);
515
            this.setLabelingStrategy(null);
516
        }
517

    
518
        typeShape = state.getInt("typeShape");
519

    
520
    }
521

    
522
    /**
523
     * Sobreimplementaci?n del m?todo toString para que las bases de datos
524
     * identifiquen la capa.
525
     * 
526
     * @return DOCUMENT ME!
527
     */
528
    public String toString() {
529
        /*
530
         * Se usa internamente para que la parte de datos identifique de forma
531
         * un?voca las tablas
532
         */
533
        String ret = super.toString();
534

    
535
        return "layer" + ret.substring(ret.indexOf('@') + 1);
536
    }
537

    
538
    public boolean isEditing() {
539
        FeatureStore fs = getFeatureStore();
540
        if (fs == null) {
541
            /*
542
             * This happens when layer is not available, for example,
543
             * it was not possible to load from persistence
544
             */
545
            return false;
546
        } else {
547
            return fs.isEditing();
548
        }
549
    }
550
    
551
    
552
    public void setEditing(boolean b) throws StartEditionLayerException {
553
        
554
        try {
555
            throw new RuntimeException();
556
        } catch (Throwable th) {
557
            logger.info("This method is deprecated. ", th);
558
        }
559
        
560
        if (b == super.isEditing()) {
561
            return;
562
        }
563
        
564
        super.setEditing(b);
565
        FeatureStore fs = getFeatureStore();
566
        if (b) {
567
            try {
568
                fs.edit();
569
            } catch (DataException e) {
570
                throw new StartEditionLayerException(getName(), e);
571
            }
572
        }
573
        setSpatialCacheEnabled(b);
574
        callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
575
    }
576

    
577

    
578
    /**
579
     * @deprecated Use {@link #getSpatialCache()}
580
     */
581
    public void clearSpatialCache() {
582
        spatialCache.clearAll();
583
    }
584

    
585
    /**
586
     * @deprecated Use {@link #getSpatialCache()}
587
     */
588
    public boolean isSpatialCacheEnabled() {
589
        return spatialCache.isEnabled();
590
    }
591

    
592
    /**
593
     * @deprecated Use {@link #getSpatialCache()}
594
     */
595
    public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
596
        spatialCache.setEnabled(spatialCacheEnabled);
597
    }
598

    
599
    public SpatialCache getSpatialCache() {
600
        return spatialCache;
601
    }
602

    
603
    /**
604
     * Siempre es un numero mayor de 1000
605
     * 
606
     * @param maxFeatures
607
     */
608
    public void setMaxFeaturesInEditionCache(int maxFeatures) {
609
        if (maxFeatures > spatialCache.getMaxFeatures()) {
610
            spatialCache.setMaxFeatures(maxFeatures);
611
        }
612

    
613
    }
614

    
615
    /**
616
     * This method returns a boolean that is used by the FPopMenu
617
     * to make visible the properties menu or not. It is visible by
618
     * default, and if a later don't have to show this menu only
619
     * has to override this method.
620
     * 
621
     * @return
622
     *         If the properties menu is visible (or not)
623
     */
624
    public boolean isPropertiesMenuVisible() {
625
        return true;
626
    }
627

    
628
    public void reload() throws ReloadLayerException {
629
        super.reload();
630
        try {
631
            getFeatureStore().refresh();
632
        } catch (Exception e) {
633
            throw new ReloadLayerException(getName(), e);
634
        }
635
    }
636

    
637
    protected void setLoadSelection(Object xml) {
638
        // this.loadSelection = xml;
639
    }
640

    
641
    protected void setLoadLegend(IVectorLegend legend) {
642
        this.loadLegend = legend;
643
    }
644

    
645
    protected void putLoadSelection() {
646
        // if (this.loadSelection == null) return;
647
        // try {
648
        // this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
649
        // } catch (ReadDriverException e) {
650
        // throw new XMLException(e);
651
        // }
652
        // this.loadSelection = null;
653

    
654
    }
655

    
656
    protected void putLoadLegend() throws LegendLayerException {
657
        if (this.loadLegend == null) {
658
            return;
659
        }
660
        this.setLegend(this.loadLegend);
661
        this.loadLegend = null;
662
    }
663

    
664
    protected void cleanLoadOptions() {
665
        this.loadLegend = null;
666
    }
667

    
668
    public boolean isWritable() {
669
        return getFeatureStore().allowWrite();
670
    }
671

    
672
    public FLayer cloneLayer() throws Exception {
673
        FLyrVect clonedLayer = new FLyrVect();
674
        clonedLayer.bindToDataStore(getDataStore());
675
        // if (isJoined()) {
676
        // clonedLayer.setIsJoined(true);
677
        // }
678
        clonedLayer.setVisible(isVisible());
679
        // clonedLayer.setISpatialIndex(getISpatialIndex());
680
        clonedLayer.setName(getName());
681
        clonedLayer.setCoordTrans(getCoordTrans());
682

    
683
        clonedLayer.setLegend((IVectorLegend) getLegend().cloneLegend());
684

    
685
        clonedLayer.setIsLabeled(isLabeled());
686
        ILabelingStrategy labelingStrategy = getLabelingStrategy();
687
        if (labelingStrategy != null) {
688
            clonedLayer.setLabelingStrategy(labelingStrategy);
689
        }
690

    
691
        return clonedLayer;
692
    }
693

    
694
    protected boolean isOnePoint(AffineTransform graphicsTransform,
695
        ViewPort viewPort,
696
        double dpi,
697
        CartographicSupport csSym,
698
        Geometry geom,
699
        int[] xyCoords) {
700
        return isOnePoint(graphicsTransform, viewPort, geom, xyCoords)
701
            && csSym.getCartographicSize(viewPort, dpi, geom) <= 1;
702
    }
703

    
704
    private boolean isOnePoint(AffineTransform graphicsTransform,
705
        ViewPort viewPort,
706
        Geometry geom,
707
        int[] xyCoords) {
708
        boolean onePoint = false;
709
        int type = geom.getType();
710
        if (type == Geometry.TYPES.NULL) {
711
            return false;
712
        }
713
        if (type != Geometry.TYPES.POINT && type != Geometry.TYPES.MULTIPOINT) {
714

    
715
            Envelope geomBounds = geom.getEnvelope();
716

    
717
            // ICoordTrans ct = getCoordTrans();
718

    
719
            // Se supone que la geometria ya esta reproyectada
720
            // if (ct!=null) {
721
            // // geomBounds = ct.getInverted().convert(geomBounds);
722
            // geomBounds = geomBounds.convert(ct);
723
            // }
724

    
725
            double dist1Pixel = viewPort.getDist1pixel();
726

    
727
            onePoint =
728
                (geomBounds.getLength(0) <= dist1Pixel && geomBounds.getLength(1) <= dist1Pixel);
729

    
730
            if (onePoint) {
731
                // avoid out of range exceptions
732
                org.gvsig.fmap.geom.primitive.Point p;
733
                try {
734
                    p =
735
                        geomManager.createPoint(geomBounds.getMinimum(0),
736
                            geomBounds.getMinimum(1),
737
                            SUBTYPES.GEOM2D);
738
                    p.transform(viewPort.getAffineTransform());
739
                    p.transform(graphicsTransform);
740
                    xyCoords[0] = (int) p.getX();
741
                    xyCoords[1] = (int) p.getY();
742
                } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
743
                    logger.error("Error creating a point", e);
744
                }
745

    
746
            }
747

    
748
        }
749
        return onePoint;
750
    }
751

    
752
    public boolean isLabeled() {
753
        return isLabeled;
754
    }
755

    
756
    public void setIsLabeled(boolean isLabeled) {
757
        this.isLabeled = isLabeled;
758
    }
759

    
760
    public ILabelingStrategy getLabelingStrategy() {
761
        return strategy;
762
    }
763

    
764
    public void setLabelingStrategy(ILabelingStrategy strategy) {
765
        this.strategy = strategy;
766
        if (strategy == null) {
767
            return;
768
        }
769
        strategy.setLayer(this);
770
        updateDrawVersion();
771
    }
772

    
773
    public void drawLabels(BufferedImage image,
774
        Graphics2D g,
775
        ViewPort viewPort,
776
        Cancellable cancel,
777
        double scale,
778
        double dpi) throws ReadException {
779
        if (strategy != null && isWithinScale(scale)) {
780
            strategy.draw(image, g, viewPort, cancel, dpi);
781
        }
782
    }
783

    
784
    public void printLabels(Graphics2D g,
785
        ViewPort viewPort,
786
        Cancellable cancel,
787
        double scale,
788
        PrintAttributes properties) throws ReadException {
789
        if (strategy != null) {
790
            strategy.print(g, viewPort, cancel, properties);
791
        }
792
    }
793

    
794
    /**
795
     * Return true, because a Vectorial Layer supports HyperLink
796
     * 
797
     * @deprecated the hiperlink functionaliti is out the layer now
798
     */
799
    public boolean allowLinks() {
800
        return false;
801
    }
802

    
803
    public void load() throws LoadLayerException {
804
        super.load();
805
    }
806

    
807
    public FeatureStore getFeatureStore() {
808
        return (FeatureStore) getDataStore();
809
    }
810

    
811
    /**
812
     * @deprecated use instead {@link #queryByPoint(org.gvsig.fmap.geom.primitive.Point, double, FeatureType)}
813
     */
814
    public FeatureSet queryByPoint(Point2D mapPoint,
815
        double tol,
816
        FeatureType featureType) throws DataException {
817
        logger.warn("Deprecated use of queryByPoint.");
818
        GeometryManager manager = GeometryLocator.getGeometryManager();
819
        org.gvsig.fmap.geom.primitive.Point center;
820
        try {
821
            center =
822
                (org.gvsig.fmap.geom.primitive.Point) manager.create(TYPES.POINT,
823
                    SUBTYPES.GEOM2D);
824
            center.setX(mapPoint.getX());
825
            center.setY(mapPoint.getY());
826
            Circle circle =
827
                (Circle) manager.create(TYPES.CIRCLE, SUBTYPES.GEOM2D);
828
            circle.setPoints(center, tol);
829
            return queryByGeometry(circle, featureType);
830
        } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
831
            throw new CreateGeometryException(TYPES.CIRCLE, SUBTYPES.GEOM2D, e);
832
        }
833
    }
834

    
835
    public FeatureSet queryByPoint(org.gvsig.fmap.geom.primitive.Point point,
836
        double tol,
837
        FeatureType featureType) throws DataException {
838
        GeometryManager manager = GeometryLocator.getGeometryManager();
839
        try {
840
            Circle circle =
841
                (Circle) manager.create(TYPES.CIRCLE, SUBTYPES.GEOM2D);
842
            circle.setPoints(point, tol);
843
            return queryByGeometry(circle, featureType);
844
        } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
845
            throw new CreateGeometryException(TYPES.CIRCLE, SUBTYPES.GEOM2D, e);
846
        }
847
    }
848

    
849
    /**
850
     * Input geom must be in the CRS of the view.
851
     * 
852
     * @param geom
853
     * @param featureType
854
     * @return
855
     * @throws DataException
856
     */
857
    public FeatureSet queryByGeometry(Geometry geom, FeatureType featureType) throws DataException {
858
        FeatureQuery featureQuery = featureStore.createFeatureQuery();
859
        String geomName =
860
            featureStore.getDefaultFeatureType()
861
                .getDefaultGeometryAttributeName();
862
        featureQuery.setFeatureType(featureType);
863
        
864
        Geometry query_geo = fromViewPortCRSToSourceCRS(this, geom, true);
865
        IProjection query_proj = getMapContext().getProjection();
866
        if (this.getCoordTrans() != null) {
867
            query_proj = this.getCoordTrans().getPOrig(); 
868
        }
869

    
870
        IntersectsGeometryEvaluator iee =
871
            new IntersectsGeometryEvaluator(
872
                query_geo,
873
                query_proj,
874
                featureStore.getDefaultFeatureType(),
875
                geomName);
876
        featureQuery.setFilter(iee);
877
        featureQuery.setAttributeNames(null);
878
        return getFeatureStore().getFeatureSet(featureQuery);
879

    
880
    }
881

    
882
    /**
883
     * It return the {@link FeatureSet} that intersects with the envelope.
884
     * @param envelope
885
     *          envelope that defines the area for the query.
886
     * @param featureType
887
     *          only the features with this feature type are used in
888
     *          the query.    
889
     * @return
890
     *          the set of features that intersect with the envelope.
891
     * @throws DataException
892
     */
893
    public FeatureSet queryByEnvelope(Envelope envelope, FeatureType featureType) throws DataException {
894
        return queryByEnvelope(envelope, featureType, null);
895
    }
896

    
897
    /**
898
     * It return the {@link FeatureSet} that intersects with the envelope.
899
     * @param envelope
900
     *          envelope that defines the area for the query in viewport CRS
901
     * @param featureType
902
     *          only the features with this feature type are used in
903
     *          the query.
904
     * @param names
905
     *          the feature attributes that have to be checked.
906
     * @return
907
     *          the set of features that intersect with the envelope.
908
     * @throws DataException
909
     */
910
    public FeatureSet queryByEnvelope(Envelope envelope,
911
        FeatureType featureType,
912
        String[] names) throws DataException {
913
        FeatureQuery featureQuery = featureStore.createFeatureQuery();
914
        if (names == null) {
915
            featureQuery.setFeatureType(featureType);
916
        } else {
917
            featureQuery.setAttributeNames(names);
918
            featureQuery.setFeatureTypeId(featureType.getId());
919
        }
920
        String geomName = featureStore.getDefaultFeatureType()
921
                .getDefaultGeometryAttributeName();
922
        
923
        Envelope query_env = fromViewPortCRSToSourceCRS(this, envelope);
924
        IProjection query_proj = getMapContext().getProjection();
925
        if (this.getCoordTrans() != null) {
926
            query_proj = this.getCoordTrans().getPOrig(); 
927
        }
928
        
929
        IntersectsGeometryEvaluator iee =
930
            new IntersectsGeometryEvaluator(
931
                query_env.getGeometry(), query_proj, 
932
                featureStore.getDefaultFeatureType(),
933
                geomName);
934
        featureQuery.setFilter(iee);
935
        return getFeatureStore().getFeatureSet(featureQuery);
936

    
937
    }
938

    
939
    public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel) throws LoadLayerException,
940
        DataException {
941

    
942
        return getInfo(p, tolerance, cancel, true);
943
    }
944

    
945
    public DynObjectSet getInfo(Point p,
946
        double tolerance,
947
        Cancellable cancel,
948
        boolean fast) throws LoadLayerException, DataException {
949
        Point2D infop = new Point2D.Double(p.x, p.y);
950
        Point2D pReal = this.getMapContext().getViewPort().toMapPoint(infop);
951
        return queryByPoint(pReal,
952
            tolerance,
953
            getFeatureStore().getDefaultFeatureType()).getDynObjectSet(fast);
954
    }
955

    
956
    public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p,
957
        double tolerance) throws LoadLayerException, DataException {
958
        return queryByPoint(p,tolerance, getFeatureStore().getDefaultFeatureType()).getDynObjectSet(false);
959
    }
960
    
961
    public void legendCleared(LegendClearEvent event) {
962
        this.updateDrawVersion();
963
        LegendChangedEvent e =
964
            LegendChangedEvent.createLegendChangedEvent(legend, legend);
965
        this.callLegendChanged(e);
966
    }
967

    
968
    public boolean symbolChanged(SymbolLegendEvent e) {
969
        this.updateDrawVersion();
970
        LegendChangedEvent ev =
971
            LegendChangedEvent.createLegendChangedEvent(legend, legend);
972
        this.callLegendChanged(ev);
973
        return true;
974
    }
975

    
976
    public void update(Observable observable, Object notification) {
977
        if (observable.equals(this.featureStore)) {
978
            if (notification instanceof FeatureStoreNotification) {
979
                FeatureStoreNotification event =
980
                    (FeatureStoreNotification) notification;
981
                if (event.getType() == FeatureStoreNotification.AFTER_DELETE
982
                    || event.getType() == FeatureStoreNotification.AFTER_UNDO
983
                    || event.getType() == FeatureStoreNotification.AFTER_REDO
984
                    || event.getType() == FeatureStoreNotification.AFTER_REFRESH
985
                    || event.getType() == FeatureStoreNotification.AFTER_UPDATE
986
                    || event.getType() == FeatureStoreNotification.AFTER_UPDATE_TYPE
987
                    || event.getType() == FeatureStoreNotification.SELECTION_CHANGE
988
                    || event.getType() == FeatureStoreNotification.AFTER_INSERT) {
989
                    this.updateDrawVersion();
990
                    
991
                } else if (event.getType() == FeatureStoreNotification.AFTER_CANCELEDITING) {
992
                    
993
                    setSpatialCacheEnabled(false);
994
                    callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
995
                    this.updateDrawVersion();
996
                    
997
                } else if (event.getType() == FeatureStoreNotification.AFTER_STARTEDITING) {
998
                    
999
                    setSpatialCacheEnabled(true);
1000
                    callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
1001

    
1002
                } else if (event.getType() == FeatureStoreNotification.TRANSFORM_CHANGE){
1003
                    //If a transform has to be applied, try to reload the layer.
1004
                    try {
1005
                        reload();
1006
                    } catch (ReloadLayerException e) {
1007
                        logger.info("While reloading layer.", e);
1008
                        this.setAvailable(false);
1009
                    }
1010
                } else if (event.getType() == FeatureStoreNotification.RESOURCE_CHANGED) {
1011
                    this.setAvailable(false);
1012
                } else         if (event.getType() == FeatureStoreNotification.AFTER_FINISHEDITING) {
1013
                    this.setAvailable(true);
1014
                    setSpatialCacheEnabled(false);
1015
                    callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
1016
                    this.updateDrawVersion();
1017
                }
1018
            }
1019
        }
1020
        else if (notification instanceof FeatureDrawnNotification
1021
            && (isEditing() || isLayerToSnap())) {
1022
            // This code is needed in editing mode
1023
                // for all layers involved in snapping
1024
                // (including the layer being edited)
1025
            Geometry geometry =
1026
                ((FeatureDrawnNotification) notification).getDrawnGeometry();
1027
            spatialCache.insert(geometry.getEnvelope(), geometry);
1028
        }
1029
    }
1030

    
1031
    private boolean isLayerToSnap() {
1032

    
1033
        if (this.getMapContext() == null) {
1034
            /*
1035
             * This happens with the graphics layer because it has no parent
1036
             */
1037
            return false;
1038
        } else {
1039
            return this.getMapContext().getLayersToSnap().contains(this);
1040
        }
1041
            
1042
            /*
1043
            Iterator itersnap = this.getMapContext().getLayersToSnap().iterator();
1044
            Object item = null;
1045
            while (itersnap.hasNext()) {
1046
                    item = itersnap.next();
1047
                    if (item == this) {
1048
                            return true;
1049
                    }
1050
            }
1051
                return false;
1052
                */
1053
        }
1054

    
1055
        /*
1056
     * (non-Javadoc)
1057
     * 
1058
     * @see org.gvsig.metadata.Metadata#getMetadataChildren()
1059
     */
1060
    public Set getMetadataChildren() {
1061
        Set ret = new TreeSet();
1062
        ret.add(this.featureStore);
1063
        return ret;
1064
    }
1065

    
1066
    /*
1067
     * (non-Javadoc)
1068
     * 
1069
     * @see org.gvsig.metadata.Metadata#getMetadataID()
1070
     */
1071
    public Object getMetadataID() throws MetadataException {
1072
        return "Layer(" + this.getName() + "):"
1073
            + this.featureStore.getMetadataID();
1074
    }
1075

    
1076
    
1077

    
1078
    public GeometryType getTypeVectorLayer() throws DataException,
1079
        LocatorException,
1080
        GeometryTypeNotSupportedException,
1081
        GeometryTypeNotValidException {
1082
        // FIXME Esto deberia de pedirse a FType!!!!
1083
        FeatureStore fs = this.getFeatureStore();
1084
        FeatureType fType = fs.getDefaultFeatureType();
1085
        FeatureAttributeDescriptor attr =
1086
            fType.getAttributeDescriptor(fType.getDefaultGeometryAttributeIndex());
1087
        GeometryType geomType =
1088
            GeometryLocator.getGeometryManager()
1089
                .getGeometryType(attr.getGeometryType(),
1090
                    attr.getGeometrySubType());
1091
        return geomType;
1092
    }
1093

    
1094
    public static void registerPersistent() {
1095
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
1096
        if (manager.getDefinition(FLyrDefault.class) == null) {
1097
            FLyrDefault.registerPersistent();
1098
        }
1099
        DynStruct definition =
1100
            manager.addDefinition(FLyrVect.class,
1101
                "FLyrVect",
1102
                "FLyrVect Persistence definition",
1103
                null,
1104
                null);
1105
        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE,
1106
            "FLyrDefault");
1107

    
1108
        definition.addDynFieldObject("legend")
1109
            .setClassOfValue(IVectorLegend.class)
1110
            .setMandatory(true);
1111
        definition.addDynFieldObject("featureStore")
1112
            .setClassOfValue(FeatureStore.class)
1113
            .setMandatory(true);
1114
        definition.addDynFieldBoolean("isLabeled").setMandatory(true);
1115
        definition.addDynFieldInt("typeShape").setMandatory(true);
1116
        definition.addDynFieldObject("labelingStrategy")
1117
            .setClassOfValue(ILabelingStrategy.class)
1118
            .setMandatory(false);
1119

    
1120
    }
1121

    
1122
    protected void doDispose() throws BaseException {
1123
        dispose(featureStore);
1124
        spatialCache.clearAll();
1125
    }
1126
    
1127
    /**
1128
     * Returns envelope in layer's data source CRS
1129
     * from envelope provided in viewport CRS
1130
     * 
1131
     * @param lyr
1132
     * @param env
1133
     * @return
1134
     */
1135
    public static Envelope fromViewPortCRSToSourceCRS(FLayer lyr, Envelope env) {
1136

    
1137
        if (lyr == null || env == null) {
1138
            return null;
1139
        }
1140

    
1141
        ICoordTrans ct = lyr.getCoordTrans();
1142
        if (ct == null) {
1143
            return env;
1144
        } else {
1145
            return env.convert(ct.getInverted());
1146
        }
1147
    }
1148

    
1149
    /**
1150
     * Returns geometry in layer's data source CRS
1151
     * from geometry provided in viewport CRS
1152
     * 
1153
     * @param lyr
1154
     * @param geo
1155
     * @param clone
1156
     * @return
1157
     */
1158
    public static Geometry fromViewPortCRSToSourceCRS(
1159
        FLayer lyr,
1160
        Geometry geo,
1161
        boolean clone) {
1162
        
1163
        if (lyr == null || geo == null) {
1164
            return null;
1165
        }
1166
        ICoordTrans ct = lyr.getCoordTrans();
1167
        Geometry resp = geo;
1168
        if (clone) {
1169
            resp = resp.cloneGeometry();
1170
        }
1171
        if (ct != null) {
1172
            resp.reProject(ct.getInverted());
1173
        }
1174
        return resp;
1175
    }
1176

    
1177
    
1178
}