Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libFMap_mapcontext / src / org / gvsig / fmap / mapcontext / layers / vectorial / FLyrVect.java @ 38581

History | View | Annotate | Download (34.4 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.vectorial;
42

    
43
import java.awt.Graphics2D;
44
import java.awt.Point;
45
import java.awt.geom.AffineTransform;
46
import java.awt.geom.Point2D;
47
import java.awt.image.BufferedImage;
48
import java.util.Set;
49
import java.util.TreeSet;
50

    
51
import org.cresques.cts.ICoordTrans;
52
import org.slf4j.LoggerFactory;
53

    
54
import org.gvsig.compat.print.PrintAttributes;
55
import org.gvsig.fmap.dal.DataStore;
56
import org.gvsig.fmap.dal.exception.DataException;
57
import org.gvsig.fmap.dal.exception.ReadException;
58
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
59
import org.gvsig.fmap.dal.feature.FeatureQuery;
60
import org.gvsig.fmap.dal.feature.FeatureSet;
61
import org.gvsig.fmap.dal.feature.FeatureStore;
62
import org.gvsig.fmap.dal.feature.FeatureStoreNotification;
63
import org.gvsig.fmap.dal.feature.FeatureType;
64
import org.gvsig.fmap.dal.feature.exception.CreateGeometryException;
65
import org.gvsig.fmap.geom.Geometry;
66
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
67
import org.gvsig.fmap.geom.Geometry.TYPES;
68
import org.gvsig.fmap.geom.GeometryLocator;
69
import org.gvsig.fmap.geom.GeometryManager;
70
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
71
import org.gvsig.fmap.geom.primitive.Circle;
72
import org.gvsig.fmap.geom.primitive.Envelope;
73
import org.gvsig.fmap.geom.type.GeometryType;
74
import org.gvsig.fmap.geom.type.GeometryTypeNotSupportedException;
75
import org.gvsig.fmap.geom.type.GeometryTypeNotValidException;
76
import org.gvsig.fmap.mapcontext.MapContextLocator;
77
import org.gvsig.fmap.mapcontext.MapContextManager;
78
import org.gvsig.fmap.mapcontext.ViewPort;
79
import org.gvsig.fmap.mapcontext.exceptions.LegendLayerException;
80
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
81
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
82
import org.gvsig.fmap.mapcontext.exceptions.ReprojectLayerException;
83
import org.gvsig.fmap.mapcontext.exceptions.StartEditionLayerException;
84
import org.gvsig.fmap.mapcontext.exceptions.StopEditionLayerException;
85
import org.gvsig.fmap.mapcontext.layers.FLayer;
86
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
87
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
88
import org.gvsig.fmap.mapcontext.layers.SpatialCache;
89
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
90
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
91
import org.gvsig.fmap.mapcontext.rendering.legend.LegendException;
92
import org.gvsig.fmap.mapcontext.rendering.legend.events.FeatureDrawnNotification;
93
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendChangedEvent;
94
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendClearEvent;
95
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendContentsChangedListener;
96
import org.gvsig.fmap.mapcontext.rendering.legend.events.SymbolLegendEvent;
97
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelingStrategy;
98
import org.gvsig.fmap.mapcontext.rendering.symbols.CartographicSupport;
99
import org.gvsig.metadata.exceptions.MetadataException;
100
import org.gvsig.tools.ToolsLocator;
101
import org.gvsig.tools.dynobject.DynObjectSet;
102
import org.gvsig.tools.dynobject.DynStruct;
103
import org.gvsig.tools.exception.BaseException;
104
import org.gvsig.tools.locator.LocatorException;
105
import org.gvsig.tools.observer.Observable;
106
import org.gvsig.tools.observer.Observer;
107
import org.gvsig.tools.persistence.PersistenceManager;
108
import org.gvsig.tools.persistence.PersistentState;
109
import org.gvsig.tools.persistence.exception.PersistenceException;
110
import org.gvsig.tools.persistence.exception.PersistenceRuntimeException;
111
import org.gvsig.tools.task.Cancellable;
112

    
113
/**
114
 * Capa b?sica Vectorial.
115
 * 
116
 * @author Fernando Gonz?lez Cort?s
117
 */
118

    
119
public class FLyrVect extends FLyrDefault implements VectorLayer,
120
    LegendContentsChangedListener, Observer {
121

    
122
    final static private org.slf4j.Logger logger =
123
        LoggerFactory.getLogger(FLyrVect.class);
124
    private final GeometryManager geomManager =
125
        GeometryLocator.getGeometryManager();
126

    
127
    /** Leyenda de la capa vectorial */
128
    private IVectorLegend legend;
129
    private int typeShape = -1;
130
    private FeatureStore featureStore = null;
131
    private SpatialCache spatialCache = new SpatialCache();
132

    
133
    /**
134
     * An implementation of gvSIG spatial index
135
     */
136
    // protected ISpatialIndex spatialIndex = null;
137
    private IVectorLegend loadLegend = null;
138

    
139
    private boolean isLabeled;
140
    protected ILabelingStrategy strategy;
141
//        private ReprojectDefaultGeometry reprojectTransform;
142

    
143
    public FLyrVect() {
144
        super();
145
    }
146
    
147
        public String getTocImageIcon() {
148
                return MapContextLocator.getMapContextManager().getIconLayer(this.getDataStore());
149
        }
150

    
151
    /**
152
     * Devuelve el VectorialAdapater de la capa.
153
     * 
154
     * @return VectorialAdapter.
155
     */
156
    public DataStore getDataStore() {
157
        if (!this.isAvailable()) {
158
            return null;
159
        }
160
        return featureStore;
161
    }
162
    
163
    /**
164
     * Inserta el DataStore a la capa.
165
     * 
166
     * @param va
167
     *            VectorialAdapter.
168
     * 
169
     * @deprecated esto deber?a se ser protected
170
     */
171
    public void setDataStore(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
            legend.draw(image,
289
                g,
290
                viewPort,
291
                cancel,
292
                scale,
293
                null,
294
                getCoordTrans(),
295
                getFeatureStore(),
296
                featureQuery);
297

    
298
        } catch (LegendException e) {
299
            this.setVisible(false);
300
            this.setActive(false);
301
            throw new ReadException(getName(), e);
302
        } finally {
303
            if (spatialCache.isEnabled()) {
304
                legend.deleteDrawingObserver(this);
305
            }
306
        }
307
    }
308

    
309
    public void print(Graphics2D g,
310
        ViewPort viewPort,
311
        Cancellable cancel,
312
        double scale,
313
        PrintAttributes properties) throws ReadException {
314
        if (!this.isWithinScale(scale)) {
315
            return;
316
        }
317
        if (cancel.isCanceled()) {
318
            return;
319
        }
320

    
321
        try {
322
            legend.print(g,
323
                viewPort,
324
                cancel,
325
                scale,
326
                null,
327
                getCoordTrans(),
328
                getFeatureStore(),
329
                null,
330
                properties);
331

    
332
        } catch (LegendException e) {
333
            this.setVisible(false);
334
            this.setActive(false);
335
            throw new ReadException(getName(), e);
336
        }
337
    }
338

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

    
363
    /**
364
     * Devuelve la Leyenda de la capa.
365
     * 
366
     * @return Leyenda.
367
     */
368
    public ILegend getLegend() {
369
        return legend;
370
    }
371

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

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

    
414
    public void saveToState(PersistentState state) throws PersistenceException {
415

    
416
        if (!this.isAvailable()) {
417
            return;
418
        }
419

    
420
        super.saveToState(state);
421

    
422
        if (getLegend() != null) {
423
            state.set("legend", getLegend());
424
        }
425

    
426
        FeatureStore fst = null;
427
        fst = getFeatureStore();
428

    
429
        if (fst != null) {
430
            state.set("featureStore", fst);
431
        }
432

    
433
        state.set("isLabeled", isLabeled);
434

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

    
439
        if (getLinkProperties() != null) {
440
            state.set("linkProperties", getLinkProperties());
441
        }
442

    
443
        // state.set("bHasJoin", bHasJoin);
444
        state.set("typeShape", typeShape);
445
    }
446

    
447

    
448
    public void loadFromState(PersistentState state) throws PersistenceException {
449

    
450
        super.loadFromState(state);
451
        DataStore store = null;
452
        try {
453
                store = (DataStore) state.get("featureStore");
454
        } catch (PersistenceRuntimeException e) {
455
                        this.setAvailable(false);
456
                        return;
457
                }
458
        try {
459
            this.setDataStore(store);
460
        } catch (LoadLayerException e) {
461
            throw new PersistenceException("While loading FLyrVect from state.",
462
                e);
463
        }
464

    
465
        IVectorLegend lgnd = (IVectorLegend) state.get("legend");
466
        try {
467
            this.setLegend(lgnd);
468
        } catch (LegendLayerException e) {
469
            throw new PersistenceException("While loading FLyrVect from state.",
470
                e);
471
        }
472

    
473
        Boolean isLbl = new Boolean(false);
474
        ILabelingStrategy lblst = null;
475

    
476
        try {
477
            isLbl = (Boolean) state.get("isLabeled");
478
            if (isLbl.booleanValue()) {
479
                lblst = (ILabelingStrategy) state.get("labelingStrategy");
480
            }
481
        } catch (Exception ex) {
482
            throw new PersistenceException("While loading FLyrVect from state.",
483
                ex);
484
        }
485

    
486
        /*
487
         * String _labelFieldName = null;
488
         * String _labelfield = null;
489
         */
490

    
491
        if (isLbl.booleanValue()) {
492
            this.setIsLabeled(true);
493
            this.setLabelingStrategy(lblst);
494
        } else {
495
            this.setIsLabeled(false);
496
            this.setLabelingStrategy(null);
497
        }
498

    
499
        typeShape = state.getInt("typeShape");
500

    
501
    }
502

    
503
    /**
504
     * Sobreimplementaci?n del m?todo toString para que las bases de datos
505
     * identifiquen la capa.
506
     * 
507
     * @return DOCUMENT ME!
508
     */
509
    public String toString() {
510
        /*
511
         * Se usa internamente para que la parte de datos identifique de forma
512
         * un?voca las tablas
513
         */
514
        String ret = super.toString();
515

    
516
        return "layer" + ret.substring(ret.indexOf('@') + 1);
517
    }
518

    
519
    public void setEditing(boolean b) throws StartEditionLayerException {
520
        super.setEditing(b);
521
        FeatureStore fs = getFeatureStore();
522
        if (b) {
523
            try {
524
                fs.edit();
525
            } catch (ReadException e) {
526
                throw new StartEditionLayerException(getName(), e);
527
            } catch (DataException e) {
528
                throw new StartEditionLayerException(getName(), e);
529
            }
530
        }
531
        setSpatialCacheEnabled(b);
532
        callEditionChanged(LayerEvent.createEditionChangedEvent(this, "edition"));
533
    }
534

    
535
    /**
536
     * @deprecated Use {@link #getSpatialCache()}
537
     */
538
    public void clearSpatialCache() {
539
        spatialCache.clearAll();
540
    }
541

    
542
    /**
543
     * @deprecated Use {@link #getSpatialCache()}
544
     */
545
    public boolean isSpatialCacheEnabled() {
546
        return spatialCache.isEnabled();
547
    }
548

    
549
    /**
550
     * @deprecated Use {@link #getSpatialCache()}
551
     */
552
    public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
553
        spatialCache.setEnabled(spatialCacheEnabled);
554
    }
555

    
556
    public SpatialCache getSpatialCache() {
557
        return spatialCache;
558
    }
559

    
560
    /**
561
     * Siempre es un numero mayor de 1000
562
     * 
563
     * @param maxFeatures
564
     */
565
    public void setMaxFeaturesInEditionCache(int maxFeatures) {
566
        if (maxFeatures > spatialCache.getMaxFeatures()) {
567
            spatialCache.setMaxFeatures(maxFeatures);
568
        }
569

    
570
    }
571

    
572
    /**
573
     * This method returns a boolean that is used by the FPopMenu
574
     * to make visible the properties menu or not. It is visible by
575
     * default, and if a later don't have to show this menu only
576
     * has to override this method.
577
     * 
578
     * @return
579
     *         If the properties menu is visible (or not)
580
     */
581
    public boolean isPropertiesMenuVisible() {
582
        return true;
583
    }
584

    
585
    public void reload() throws ReloadLayerException {
586
        super.reload();
587
        try {
588
            getFeatureStore().refresh();
589
        } catch (Exception e) {
590
            throw new ReloadLayerException(getName(), e);
591
        }
592
    }
593

    
594
    protected void setLoadSelection(Object xml) {
595
        // this.loadSelection = xml;
596
    }
597

    
598
    protected void setLoadLegend(IVectorLegend legend) {
599
        this.loadLegend = legend;
600
    }
601

    
602
    protected void putLoadSelection() {
603
        // if (this.loadSelection == null) return;
604
        // try {
605
        // this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
606
        // } catch (ReadDriverException e) {
607
        // throw new XMLException(e);
608
        // }
609
        // this.loadSelection = null;
610

    
611
    }
612

    
613
    protected void putLoadLegend() throws LegendLayerException {
614
        if (this.loadLegend == null) {
615
            return;
616
        }
617
        this.setLegend(this.loadLegend);
618
        this.loadLegend = null;
619
    }
620

    
621
    protected void cleanLoadOptions() {
622
        this.loadLegend = null;
623
    }
624

    
625
    public boolean isWritable() {
626
        return getFeatureStore().allowWrite();
627
    }
628

    
629
    public FLayer cloneLayer() throws Exception {
630
        FLyrVect clonedLayer = new FLyrVect();
631
        clonedLayer.setDataStore(getDataStore());
632
        // if (isJoined()) {
633
        // clonedLayer.setIsJoined(true);
634
        // }
635
        clonedLayer.setVisible(isVisible());
636
        // clonedLayer.setISpatialIndex(getISpatialIndex());
637
        clonedLayer.setName(getName());
638
        clonedLayer.setCoordTrans(getCoordTrans());
639

    
640
        clonedLayer.setLegend((IVectorLegend) getLegend().cloneLegend());
641

    
642
        clonedLayer.setIsLabeled(isLabeled());
643
        ILabelingStrategy labelingStrategy = getLabelingStrategy();
644
        if (labelingStrategy != null) {
645
            clonedLayer.setLabelingStrategy(labelingStrategy);
646
        }
647

    
648
        return clonedLayer;
649
    }
650

    
651
    protected boolean isOnePoint(AffineTransform graphicsTransform,
652
        ViewPort viewPort,
653
        double dpi,
654
        CartographicSupport csSym,
655
        Geometry geom,
656
        int[] xyCoords) {
657
        return isOnePoint(graphicsTransform, viewPort, geom, xyCoords)
658
            && csSym.getCartographicSize(viewPort, dpi, geom) <= 1;
659
    }
660

    
661
    private boolean isOnePoint(AffineTransform graphicsTransform,
662
        ViewPort viewPort,
663
        Geometry geom,
664
        int[] xyCoords) {
665
        boolean onePoint = false;
666
        int type = geom.getType();
667
        if (type == Geometry.TYPES.NULL) {
668
            return false;
669
        }
670
        if (type != Geometry.TYPES.POINT && type != Geometry.TYPES.MULTIPOINT) {
671

    
672
            Envelope geomBounds = geom.getEnvelope();
673

    
674
            // ICoordTrans ct = getCoordTrans();
675

    
676
            // Se supone que la geometria ya esta reproyectada
677
            // if (ct!=null) {
678
            // // geomBounds = ct.getInverted().convert(geomBounds);
679
            // geomBounds = geomBounds.convert(ct);
680
            // }
681

    
682
            double dist1Pixel = viewPort.getDist1pixel();
683

    
684
            onePoint =
685
                (geomBounds.getLength(0) <= dist1Pixel && geomBounds.getLength(1) <= dist1Pixel);
686

    
687
            if (onePoint) {
688
                // avoid out of range exceptions
689
                org.gvsig.fmap.geom.primitive.Point p;
690
                try {
691
                    p =
692
                        geomManager.createPoint(geomBounds.getMinimum(0),
693
                            geomBounds.getMinimum(1),
694
                            SUBTYPES.GEOM2D);
695
                    p.transform(viewPort.getAffineTransform());
696
                    p.transform(graphicsTransform);
697
                    xyCoords[0] = (int) p.getX();
698
                    xyCoords[1] = (int) p.getY();
699
                } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
700
                    logger.error("Error creating a point", e);
701
                }
702

    
703
            }
704

    
705
        }
706
        return onePoint;
707
    }
708

    
709
    public boolean isLabeled() {
710
        return isLabeled;
711
    }
712

    
713
    public void setIsLabeled(boolean isLabeled) {
714
        this.isLabeled = isLabeled;
715
    }
716

    
717
    public ILabelingStrategy getLabelingStrategy() {
718
        return strategy;
719
    }
720

    
721
    public void setLabelingStrategy(ILabelingStrategy strategy) {
722
        this.strategy = strategy;
723
        if (strategy == null) {
724
            return;
725
        }
726
        strategy.setLayer(this);
727
        updateDrawVersion();
728
    }
729

    
730
    public void drawLabels(BufferedImage image,
731
        Graphics2D g,
732
        ViewPort viewPort,
733
        Cancellable cancel,
734
        double scale,
735
        double dpi) throws ReadException {
736
        if (strategy != null && isWithinScale(scale)) {
737
            strategy.draw(image, g, viewPort, cancel, dpi);
738
        }
739
    }
740

    
741
    public void printLabels(Graphics2D g,
742
        ViewPort viewPort,
743
        Cancellable cancel,
744
        double scale,
745
        PrintAttributes properties) throws ReadException {
746
        if (strategy != null) {
747
            strategy.print(g, viewPort, cancel, properties);
748
        }
749
    }
750

    
751
    /**
752
     * Return true, because a Vectorial Layer supports HyperLink
753
     * 
754
     * @deprecated the hiperlink functionaliti is out the layer now
755
     */
756
    public boolean allowLinks() {
757
        return false;
758
    }
759

    
760
    public void load() throws LoadLayerException {
761
        super.load();
762
    }
763

    
764
    public FeatureStore getFeatureStore() {
765
        return (FeatureStore) getDataStore();
766
    }
767

    
768
    /**
769
     * @deprecated use instead {@link #queryByPoint(org.gvsig.fmap.geom.primitive.Point, double, FeatureType)}
770
     */
771
    public FeatureSet queryByPoint(Point2D mapPoint,
772
        double tol,
773
        FeatureType featureType) throws DataException {
774
        logger.warn("Deprecated use of queryByPoint.");
775
        GeometryManager manager = GeometryLocator.getGeometryManager();
776
        org.gvsig.fmap.geom.primitive.Point center;
777
        try {
778
            center =
779
                (org.gvsig.fmap.geom.primitive.Point) manager.create(TYPES.POINT,
780
                    SUBTYPES.GEOM2D);
781
            center.setX(mapPoint.getX());
782
            center.setY(mapPoint.getY());
783
            Circle circle =
784
                (Circle) manager.create(TYPES.CIRCLE, SUBTYPES.GEOM2D);
785
            circle.setPoints(center, tol);
786
            return queryByGeometry(circle, featureType);
787
        } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
788
            throw new CreateGeometryException(TYPES.CIRCLE, SUBTYPES.GEOM2D, e);
789
        }
790
    }
791

    
792
    public FeatureSet queryByPoint(org.gvsig.fmap.geom.primitive.Point point,
793
        double tol,
794
        FeatureType featureType) throws DataException {
795
        GeometryManager manager = GeometryLocator.getGeometryManager();
796
        try {
797
            Circle circle =
798
                (Circle) manager.create(TYPES.CIRCLE, SUBTYPES.GEOM2D);
799
            circle.setPoints(point, tol);
800
            return queryByGeometry(circle, featureType);
801
        } catch (org.gvsig.fmap.geom.exception.CreateGeometryException e) {
802
            throw new CreateGeometryException(TYPES.CIRCLE, SUBTYPES.GEOM2D, e);
803
        }
804
    }
805

    
806
    public FeatureSet queryByGeometry(Geometry geom, FeatureType featureType) throws DataException {
807
        FeatureQuery featureQuery = featureStore.createFeatureQuery();
808
        String geomName =
809
            featureStore.getDefaultFeatureType()
810
                .getDefaultGeometryAttributeName();
811
        featureQuery.setFeatureType(featureType);
812
        IntersectsGeometryEvaluator iee =
813
            new IntersectsGeometryEvaluator(geom,
814
                getMapContext().getViewPort().getProjection(),
815
                featureStore.getDefaultFeatureType(),
816
                geomName);
817
        featureQuery.setFilter(iee);
818
        return getFeatureStore().getFeatureSet(featureQuery);
819

    
820
    }
821

    
822
    /**
823
     * It return the {@link FeatureSet} that intersects with the envelope.
824
     * @param envelope
825
     *          envelope that defines the area for the query.
826
     * @param featureType
827
     *          only the features with this feature type are used in
828
     *          the query.    
829
     * @return
830
     *          the set of features that intersect with the envelope.
831
     * @throws DataException
832
     */
833
    public FeatureSet queryByEnvelope(Envelope envelope, FeatureType featureType) throws DataException {
834
        return queryByEnvelope(envelope, featureType, null);
835
    }
836

    
837
    /**
838
     * It return the {@link FeatureSet} that intersects with the envelope.
839
     * @param envelope
840
     *          envelope that defines the area for the query.
841
     * @param featureType
842
     *          only the features with this feature type are used in
843
     *          the query.
844
     * @param names
845
     *          the feature attributes that have to be checked.
846
     * @return
847
     *          the set of features that intersect with the envelope.
848
     * @throws DataException
849
     */
850
    public FeatureSet queryByEnvelope(Envelope envelope,
851
        FeatureType featureType,
852
        String[] names) throws DataException {
853
        FeatureQuery featureQuery = featureStore.createFeatureQuery();
854
        if (names == null) {
855
            featureQuery.setFeatureType(featureType);
856
        } else {
857
            featureQuery.setAttributeNames(names);
858
            featureQuery.setFeatureTypeId(featureType.getId());
859
        }
860
        String geomName =
861
            featureStore.getDefaultFeatureType()
862
                .getDefaultGeometryAttributeName();
863
        IntersectsGeometryEvaluator iee =
864
            new IntersectsGeometryEvaluator(envelope.getGeometry(),
865
                getMapContext().getViewPort().getProjection(),
866
                featureStore.getDefaultFeatureType(),
867
                geomName);
868
        featureQuery.setFilter(iee);
869
        return getFeatureStore().getFeatureSet(featureQuery);
870

    
871
    }
872

    
873
    public DynObjectSet getInfo(Point p, double tolerance, Cancellable cancel) throws LoadLayerException,
874
        DataException {
875

    
876
        return getInfo(p, tolerance, cancel, true);
877
    }
878

    
879
    public DynObjectSet getInfo(Point p,
880
        double tolerance,
881
        Cancellable cancel,
882
        boolean fast) throws LoadLayerException, DataException {
883
        Point2D infop = new Point2D.Double(p.x, p.y);
884
        Point2D pReal = this.getMapContext().getViewPort().toMapPoint(infop);
885
        return queryByPoint(pReal,
886
            tolerance,
887
            getFeatureStore().getDefaultFeatureType()).getDynObjectSet(fast);
888
    }
889

    
890
    public DynObjectSet getInfo(org.gvsig.fmap.geom.primitive.Point p,
891
        double tolerance) throws LoadLayerException, DataException {
892
        return queryByPoint(p,tolerance, getFeatureStore().getDefaultFeatureType()).getDynObjectSet(false);
893
    }
894
    
895
    public void legendCleared(LegendClearEvent event) {
896
        this.updateDrawVersion();
897
        LegendChangedEvent e =
898
            LegendChangedEvent.createLegendChangedEvent(legend, legend);
899
        this.callLegendChanged(e);
900
    }
901

    
902
    public boolean symbolChanged(SymbolLegendEvent e) {
903
        this.updateDrawVersion();
904
        LegendChangedEvent ev =
905
            LegendChangedEvent.createLegendChangedEvent(legend, legend);
906
        this.callLegendChanged(ev);
907
        return true;
908
    }
909

    
910
    public void update(Observable observable, Object notification) {
911
        if (observable.equals(this.featureStore)) {
912
            if (notification instanceof FeatureStoreNotification) {
913
                FeatureStoreNotification event =
914
                    (FeatureStoreNotification) notification;
915
                if (event.getType() == FeatureStoreNotification.AFTER_CANCELEDITING
916
                    || event.getType() == FeatureStoreNotification.AFTER_DELETE
917
                    || event.getType() == FeatureStoreNotification.AFTER_UNDO
918
                    || event.getType() == FeatureStoreNotification.AFTER_REDO
919
                    || event.getType() == FeatureStoreNotification.AFTER_REFRESH
920
                    || event.getType() == FeatureStoreNotification.AFTER_UPDATE
921
                    || event.getType() == FeatureStoreNotification.AFTER_UPDATE_TYPE
922
                    || event.getType() == FeatureStoreNotification.SELECTION_CHANGE
923
                    || event.getType() == FeatureStoreNotification.AFTER_INSERT) {
924
                    this.updateDrawVersion();
925

    
926
                } else if (event.getType() == FeatureStoreNotification.TRANSFORM_CHANGE){
927
                    //If a transform has to be applied, try to reload the layer.
928
                    try {
929
                        reload();
930
                    } catch (ReloadLayerException e) {
931
                        this.setAvailable(false);
932
                    }
933
                } else if (event.getType() == FeatureStoreNotification.RESOURCE_CHANGED) {
934
                    this.setAvailable(false);
935
                } else         if (event.getType() == FeatureStoreNotification.AFTER_FINISHEDITING) {
936
                    this.setAvailable(true);
937
                }
938
            }
939
        }
940
        // Only if its an event from our own legend
941
        else
942
            // I comment this line because a legend doesn't implements the
943
            // Observable interface.
944
            // This code is necessary on edition.
945
            // if (observable == getLegend()) {
946
            if (notification instanceof FeatureDrawnNotification) {
947
                Geometry geometry =
948
                    ((FeatureDrawnNotification) notification).getDrawnGeometry();
949
                spatialCache.insert(geometry.getEnvelope(), geometry);
950
                // }
951
            }
952

    
953
    }
954

    
955
    /*
956
     * (non-Javadoc)
957
     * 
958
     * @see org.gvsig.metadata.Metadata#getMetadataChildren()
959
     */
960
    public Set getMetadataChildren() {
961
        Set ret = new TreeSet();
962
        ret.add(this.featureStore);
963
        return ret;
964
    }
965

    
966
    /*
967
     * (non-Javadoc)
968
     * 
969
     * @see org.gvsig.metadata.Metadata#getMetadataID()
970
     */
971
    public Object getMetadataID() throws MetadataException {
972
        return "Layer(" + this.getName() + "):"
973
            + this.featureStore.getMetadataID();
974
    }
975

    
976
    
977

    
978
    public GeometryType getTypeVectorLayer() throws DataException,
979
        LocatorException,
980
        GeometryTypeNotSupportedException,
981
        GeometryTypeNotValidException {
982
        // FIXME Esto deberia de pedirse a FType!!!!
983
        FeatureStore fs = this.getFeatureStore();
984
        FeatureType fType = fs.getDefaultFeatureType();
985
        FeatureAttributeDescriptor attr =
986
            fType.getAttributeDescriptor(fType.getDefaultGeometryAttributeIndex());
987
        GeometryType geomType =
988
            GeometryLocator.getGeometryManager()
989
                .getGeometryType(attr.getGeometryType(),
990
                    attr.getGeometrySubType());
991
        return geomType;
992
    }
993

    
994
    public static void registerPersistent() {
995
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
996
        if (manager.getDefinition(FLyrDefault.class) == null) {
997
            FLyrDefault.registerPersistent();
998
        }
999
        DynStruct definition =
1000
            manager.addDefinition(FLyrVect.class,
1001
                "FLyrVect",
1002
                "FLyrVect Persistence definition",
1003
                null,
1004
                null);
1005
        definition.extend(PersistenceManager.PERSISTENCE_NAMESPACE,
1006
            "FLyrDefault");
1007

    
1008
        definition.addDynFieldObject("legend")
1009
            .setClassOfValue(IVectorLegend.class)
1010
            .setMandatory(true);
1011
        definition.addDynFieldObject("featureStore")
1012
            .setClassOfValue(FeatureStore.class)
1013
            .setMandatory(true);
1014
        definition.addDynFieldBoolean("isLabeled").setMandatory(true);
1015
        definition.addDynFieldInt("typeShape").setMandatory(true);
1016
        definition.addDynFieldObject("labelingStrategy")
1017
            .setClassOfValue(ILabelingStrategy.class)
1018
            .setMandatory(false);
1019

    
1020
    }
1021

    
1022
    protected void doDispose() throws BaseException {
1023
        dispose(featureStore);
1024
        spatialCache.clearAll();
1025
    }
1026
}