Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / libraries / libFMap_mapcontext / src / org / gvsig / fmap / mapcontext / layers / vectorial / FLyrVect.java @ 22358

History | View | Annotate | Download (68.1 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.geom.Rectangle2D;
48
import java.awt.image.BufferedImage;
49
import java.net.URI;
50
import java.util.ArrayList;
51
import java.util.Iterator;
52

    
53
import javax.print.attribute.PrintRequestAttributeSet;
54
import javax.print.attribute.standard.PrintQuality;
55

    
56
import org.apache.log4j.Logger;
57
import org.cresques.cts.ICoordTrans;
58
import org.gvsig.exceptions.BaseException;
59
import org.gvsig.fmap.data.DataStore;
60
import org.gvsig.fmap.data.ReadException;
61
import org.gvsig.fmap.data.operation.DataStoreOperationException;
62
import org.gvsig.fmap.data.operation.DataStoreOperationNotSupportedException;
63
import org.gvsig.fmap.data.vectorial.Feature;
64
import org.gvsig.fmap.data.vectorial.FeatureCollection;
65
import org.gvsig.fmap.data.vectorial.FeatureStore;
66
import org.gvsig.fmap.data.vectorial.FeatureType;
67
import org.gvsig.fmap.geom.Geometry;
68
import org.gvsig.fmap.geom.GeometryManager;
69
import org.gvsig.fmap.geom.operation.DrawInts;
70
import org.gvsig.fmap.geom.operation.DrawOperationContext;
71
import org.gvsig.fmap.geom.operation.GeometryOperationException;
72
import org.gvsig.fmap.geom.operation.GeometryOperationNotSupportedException;
73
import org.gvsig.fmap.geom.operation.towkt.ToWKT;
74
import org.gvsig.fmap.geom.primitive.DefaultEnvelope;
75
import org.gvsig.fmap.geom.primitive.Envelope;
76
import org.gvsig.fmap.mapcontext.MapContext;
77
import org.gvsig.fmap.mapcontext.ViewPort;
78
import org.gvsig.fmap.mapcontext.exceptions.LegendLayerException;
79
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
80
import org.gvsig.fmap.mapcontext.exceptions.ReloadLayerException;
81
import org.gvsig.fmap.mapcontext.exceptions.StartEditionLayerException;
82
import org.gvsig.fmap.mapcontext.layers.AbstractLinkProperties;
83
import org.gvsig.fmap.mapcontext.layers.FLayer;
84
import org.gvsig.fmap.mapcontext.layers.FLyrDefault;
85
import org.gvsig.fmap.mapcontext.layers.FLyrVectLinkProperties;
86
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
87
import org.gvsig.fmap.mapcontext.layers.SpatialCache;
88
import org.gvsig.fmap.mapcontext.layers.XMLException;
89
import org.gvsig.fmap.mapcontext.layers.operations.ClassifiableVectorial;
90
import org.gvsig.fmap.mapcontext.layers.operations.ILabelable;
91
import org.gvsig.fmap.mapcontext.layers.operations.InfoByPoint;
92
import org.gvsig.fmap.mapcontext.layers.operations.SingleLayer;
93
import org.gvsig.fmap.mapcontext.layers.operations.VectorialXMLItem;
94
import org.gvsig.fmap.mapcontext.layers.operations.XMLItem;
95
import org.gvsig.fmap.mapcontext.rendering.legend.IClassifiedVectorLegend;
96
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
97
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
98
import org.gvsig.fmap.mapcontext.rendering.legend.LegendFactory;
99
import org.gvsig.fmap.mapcontext.rendering.legend.SingleSymbolLegend;
100
import org.gvsig.fmap.mapcontext.rendering.legend.ZSort;
101
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendChangedEvent;
102
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelingStrategy;
103
import org.gvsig.fmap.mapcontext.rendering.symbols.CartographicSupport;
104
import org.gvsig.fmap.mapcontext.rendering.symbols.FSymbol;
105
import org.gvsig.fmap.mapcontext.rendering.symbols.IMultiLayerSymbol;
106
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
107

    
108
import com.iver.utiles.XMLEntity;
109
import com.iver.utiles.swing.threads.Cancellable;
110

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

    
117
// TODO Cuando no sea para pruebas debe no ser public
118
public class FLyrVect extends FLyrDefault implements ILabelable, InfoByPoint,
119
                ClassifiableVectorial, SingleLayer {
120
    private static Logger logger = Logger.getLogger(FLyrVect.class.getName());
121

    
122
    /** Leyenda de la capa vectorial */
123
    private IVectorLegend legend;
124
    private int typeShape = -1;
125
//    private ReadableVectorial source;
126
//    private SelectableDataSource sds;
127
    private FeatureStore featureStore=null;
128
//    private SelectionSupport selectionSupport = new SelectionSupport();
129
    private SpatialCache spatialCache = new SpatialCache();
130
    private boolean spatialCacheEnabled = false;
131

    
132
    /**
133
     * An implementation of gvSIG spatial index
134
     */
135
//    protected ISpatialIndex spatialIndex = null;
136
    private boolean bHasJoin = false;
137
    private XMLEntity orgXMLEntity = null;
138
    private XMLEntity loadSelection = null;
139
    private IVectorLegend loadLegend = null;
140

    
141
    //Lo a?ado. Caracter?sticas de HyperEnlace (LINK)
142
    private FLyrVectLinkProperties linkProperties=new FLyrVectLinkProperties();
143

    
144
    /**
145
     * Devuelve el VectorialAdapater de la capa.
146
     *
147
     * @return VectorialAdapter.
148
     */
149
    public DataStore getDataStore() {
150
        if (!this.isAvailable()) {
151
                        return null;
152
                }
153
        return featureStore;
154
    }
155

    
156
    /**
157
     * If we use a persistent spatial index associated with this layer, and the
158
     * index is not intrisic to the layer (for example spatial databases) this
159
     * method looks for existent spatial index, and loads it.
160
     *
161
     */
162
//    private void loadSpatialIndex() {
163
//        //FIXME: Al abrir el indice en fichero...
164
//        //?C?mo lo liberamos? un metodo Layer.shutdown()
165
//
166
//
167
//        ReadableVectorial source = getSource();
168
//        //REVISAR QUE PASA CON LOS DRIVERS DXF, DGN, etc.
169
//        //PUES SON VECTORIALFILEADAPTER
170
//        if (!(source instanceof VectorialFileAdapter)) {
171
//            // we are not interested in db adapters
172
//            return;
173
//        }
174
//        VectorialDriver driver = source.getDriver();
175
//        if (!(driver instanceof BoundedShapes)) {
176
//            // we dont spatially index layers that are not bounded
177
//            return;
178
//        }
179
//        File file = ((VectorialFileAdapter) source).getFile();
180
//        String fileName = file.getAbsolutePath();
181
//        File sptFile = new File(fileName + ".qix");
182
//        if (!sptFile.exists() || (!(sptFile.length() > 0))) {
183
//            // before to exit, look for it in temp path
184
//            String tempPath = System.getProperty("java.io.tmpdir");
185
//            fileName = tempPath + File.separator + sptFile.getName();
186
//            sptFile = new File(fileName);
187
//            // it doesnt exists, must to create
188
//            if (!sptFile.exists() || (!(sptFile.length() > 0))) {
189
//                return;
190
//            }// if
191
//        }// if
192
//
193
//        try {
194
//            source.start();
195
//            spatialIndex = new QuadtreeGt2(FileUtils.getFileWithoutExtension(sptFile),
196
//                    "NM", source.getFullExtent(), source.getShapeCount(), false);
197
//            source.setSpatialIndex(spatialIndex);
198
//        } catch (SpatialIndexException e) {
199
//            spatialIndex = null;
200
//            e.printStackTrace();
201
//            return;
202
//        } catch (ReadDriverException e) {
203
//            spatialIndex = null;
204
//            e.printStackTrace();
205
//            return;
206
//        }
207
//
208
//    }
209

    
210
    /**
211
     * Checks if it has associated an external spatial index
212
     * (an spatial index file).
213
     *
214
     * It looks for it in main file path, or in temp system path.
215
     * If main file is rivers.shp, it looks for a file called
216
     * rivers.shp.qix.
217

218
     * @return
219
     */
220
//    public boolean isExternallySpatiallyIndexed() {
221
//        /*
222
//         * FIXME (AZABALA): Independizar del tipo de fichero de ?ndice
223
//          * con el que se trabaje (ahora mismo considera la extension .qix,
224
//         * pero esto depender? del tipo de ?ndice)
225
//         * */
226
//        ReadableVectorial source = getSource();
227
//        if (!(source instanceof VectorialFileAdapter)) {
228
//            // we are not interested in db adapters.
229
//            // think in non spatial dbs, like HSQLDB
230
//            return false;
231
//        }
232
//        File file = ((VectorialFileAdapter) source).getFile();
233
//        String fileName = file.getAbsolutePath();
234
//        File sptFile = new File(fileName + ".qix");
235
//        if (!sptFile.exists() || (!(sptFile.length() > 0))) {
236
//            // before to exit, look for it in temp path
237
//            // it doesnt exists, must to create
238
//            String tempPath = System.getProperty("java.io.tmpdir");
239
//            fileName = tempPath + File.separator + sptFile.getName();
240
//            sptFile = new File(fileName);
241
//            if (!sptFile.exists() || (!(sptFile.length() > 0))) {
242
//                return false;
243
//            }// if
244
//        }// if
245
//        return true;
246
//    }
247

    
248
    /**
249
     * Inserta el VectorialAdapter a la capa.
250
     *
251
     * @param va
252
     *            VectorialAdapter.
253
     */
254
    public void setDataStore(DataStore dataStore) throws LoadLayerException {
255
        featureStore = (FeatureStore)dataStore;
256

    
257
        if (dataStore.implementsOperation("defaultLegend")) {
258
                        ILegend legend = null;
259
                        try {
260
                                legend = (ILegend) dataStore.invokeOperation("defaultLegend",
261
                                                null);
262
                        } catch (DataStoreOperationNotSupportedException e) {
263
                                throw new LoadLayerException(this.getName(), e);
264
                        } catch (DataStoreOperationException e) {
265
                                throw new LoadLayerException(this.getName(), e);
266
                        }
267

    
268
                this.setLegend((IVectorLegend) legend);
269
                } else {
270
                        try {
271
                                this.setLegend(LegendFactory.createSingleSymbolLegend(this
272
                                                .getShapeType()));
273
                        } catch (ReadException e) {
274
                                throw new LoadLayerException(this.getName(), e);
275
                        }
276
                }
277

    
278
        if (dataStore.implementsOperation("defaultLabelingStrategy")) {
279

    
280
                ILabelingStrategy labeler = null;
281
                        try {
282
                                labeler = (ILabelingStrategy) dataStore.invokeOperation(
283
                                                "defaultLabelingStrategy", null);
284
                        } catch (DataStoreOperationNotSupportedException e) {
285
                                throw new LoadLayerException(this.getName(), e);
286
                        } catch (DataStoreOperationException e) {
287
                                throw new LoadLayerException(this.getName(), e);
288
                        }
289

    
290
                if (labeler != null) {
291
                                try {
292
                                        labeler.setLayer(this);
293
                                } catch (ReadException e) {
294
                                        throw new LoadLayerException(this.getName(), e);
295
                                }
296
                                this.setLabelingStrategy(labeler);
297
                                this.setIsLabeled(true); // TODO: ac? no s'hauria de detectar si t? etiquetes?????
298
                        }
299
        }
300

    
301

    
302
        // azabala: we check if this layer could have a file spatial index
303
        // and load it if it exists
304
//        loadSpatialIndex();
305
    }
306

    
307
    public Envelope getFullEnvelope() throws ReadException {
308
//            Rectangle2D rAux=null;
309
////            source.start();
310
////            rAux = (Rectangle2D)source.getFullExtent().clone();
311
////            source.stop();
312
////
313
////
314
////            // Si existe reproyecci?n, reproyectar el extent
315
////            ICoordTrans ct = getCoordTrans();
316
////
317
////            if (ct != null) {
318
////                Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
319
////                Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
320
////                pt1 = ct.convert(pt1, null);
321
////                pt2 = ct.convert(pt2, null);
322
////                rAux = new Rectangle2D.Double();
323
////                rAux.setFrameFromDiagonal(pt1, pt2);
324
////            }
325
////
326
////            //Esto es para cuando se crea una capa nueva con el fullExtent de ancho y alto 0.
327
////            if (rAux.getWidth()==0 && rAux.getHeight()==0) {
328
////                rAux=new Rectangle2D.Double(0,0,100,100);
329
////            }
330
//
331
//            return rAux;
332

    
333
           Envelope rAux;
334
                try {
335
                        rAux = (Envelope)getFeatureStore().getMetadata().get("extent");
336
                } catch (BaseException e) {
337
                        throw new ReadException(getName(),e);
338
                }
339
                        // logger.debug("source.stop()");
340
//                getSource().stop();
341
                        // Si existe reproyecci?n, reproyectar el extent
342
                ICoordTrans ct = getCoordTrans();
343
                if (ct != null) {
344
                        Point2D pt1 = new Point2D.Double(rAux.getMinimum(0), rAux.getMinimum(1));
345
                        Point2D pt2 = new Point2D.Double(rAux.getMaximum(0), rAux.getMaximum(1));
346
                        pt1 = ct.convert(pt1, null);
347
                        pt2 = ct.convert(pt2, null);
348
                        rAux = new DefaultEnvelope(2,new double[]{pt1.getX(),pt1.getY()},new double[]{pt2.getX(),pt2.getY()});//new Rectangle2D.Double();
349
                }
350
                //Esto es para cuando se crea una capa nueva con el fullExtent de ancho y alto 0.
351
                if (rAux.getMaximum(0)-rAux.getMinimum(0)==0 && rAux.getMaximum(1)-rAux.getMinimum(1)==0) {
352
                        rAux=new DefaultEnvelope(2,new double[]{0,0},new double[]{100,100});
353
                }
354
                return rAux;
355

    
356
    }
357

    
358
    /**
359
     * Draws using IFeatureIterator. This method will replace the old draw(...) one.
360
     * @autor jaume dominguez faus - jaume.dominguez@iver.es
361
     * @param image
362
     * @param g
363
     * @param viewPort
364
     * @param cancel
365
     * @param scale
366
     * @throws ReadDriverException
367
     */
368
    public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
369
                    Cancellable cancel, double scale) throws ReadException {
370
            DrawOperationContext doc=new DrawOperationContext();
371
            doc.setViewPort(viewPort);
372
            boolean bDrawShapes = true;
373
            if (legend instanceof SingleSymbolLegend) {
374
                    bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
375
            }
376
            Point2D offset = viewPort.getOffset();
377
            double dpi = MapContext.getScreenDPI();
378

    
379

    
380

    
381
            if (bDrawShapes) {
382
                    boolean cacheFeatures = isSpatialCacheEnabled();
383
                    SpatialCache cache = null;
384
                if (cacheFeatures) {
385
                        getSpatialCache().clearAll();
386
                        cache = getSpatialCache();
387
                }
388

    
389
                    try {
390
                            ArrayList<String> fieldList = new ArrayList<String>();
391

    
392
                            // fields from legend
393
                            String[] aux = null;
394

    
395
                            if (legend instanceof IClassifiedVectorLegend) {
396
                                    aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames();
397
                                    for (int i = 0; i < aux.length; i++) {
398
                                            fieldList.add(aux[i]);
399
                                    }
400
                            }
401
                            FeatureStore featureStore=getFeatureStore();
402
                            // Get the iterator over the visible features
403
                            String featureFilter = null;
404

    
405
                            if (!viewPort.getAdjustedExtent().contains((Envelope)featureStore.getMetadata().get("extent"))) {
406
                                        featureFilter=this.getDataStoreFilterForGeomerty(
407
                                                viewPort.getAdjustedExtent().getGeometry(),
408
                                                featureStore.getDefaultFeatureType().getDefaultGeometry(),
409
                                                null);
410
                                }
411

    
412

    
413
                            FeatureCollection featureCollection=null;
414
                            featureCollection = (FeatureCollection)featureStore.getDataCollection(
415
                                            new String[]{featureStore.getDefaultFeatureType().getDefaultGeometry()},
416
                                            featureFilter,//filter
417
                                            null);//order
418
                            Iterator it = featureCollection.iterator();
419

    
420

    
421
//                                            viewPort.getAdjustedExtent(),
422
//                                            fieldList.toArray(new String[fieldList.size()]),
423
//                                            viewPort.getProjection(),
424
//                                            true);
425

    
426
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
427

    
428
                            boolean bSymbolLevelError = false;
429

    
430
                            // if layer has map levels it will use a ZSort
431
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
432

    
433
                            // -- visual FX stuff
434
                            long time = System.currentTimeMillis();
435
                            BufferedImage virtualBim;
436
                            Graphics2D virtualGraphics;
437

    
438
                            // render temporary map each screenRefreshRate milliseconds;
439
                            int screenRefreshDelay = (int) ((1D/MapContext.getDrawFrameRate())*3*1000);
440
                            BufferedImage[] imageLevels = null;
441
                            Graphics2D[] graphics = null;
442
                            if (useZSort) {
443
                                    imageLevels = new BufferedImage[zSort.getLevelCount()];
444
                                    graphics = new Graphics2D[imageLevels.length];
445
                                    for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
446
                                            imageLevels[i] = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
447
                                            graphics[i] = imageLevels[i].createGraphics();
448
                                            graphics[i].setTransform(g.getTransform());
449
                                            graphics[i].setRenderingHints(g.getRenderingHints());
450
                                    }
451
                            }
452
                            // -- end visual FX stuff
453

    
454

    
455
                            // Iteration over each feature
456
                            while ( !cancel.isCanceled() && it.hasNext()) {
457
                                    Feature feat = (Feature)it.next();
458

    
459
                                    Geometry geom = (Geometry)feat.getDefaultGeometry();
460

    
461
                                    if (cacheFeatures) {
462
                                            if (cache.getMaxFeatures() >= cache.size()) {
463
                                                        // already reprojected
464
                                                        cache.insert(geom.getEnvelope(), geom);
465
                                                }
466
                                    }
467

    
468
                                    // retrieve the symbol associated to such feature
469
                                    ISymbol sym = legend.getSymbolByFeature(feat);
470
                                    if (featureStore.getSelection().contains(feat)){
471
                                            sym=sym.getSymbolForSelection();
472
                                    }
473
                                    if (sym == null) {
474
                                                continue;
475
                                        }
476

    
477
                                    //C?digo para poder acceder a los ?ndices para ver si est? seleccionado un Feature
478
//                                    ReadableVectorial rv=getSource();
479
//                                    int selectionIndex=-1;
480
//                                    if (rv instanceof ISpatialDB){
481
//                                            selectionIndex=((ISpatialDB)rv).getRowIndexByFID(feat);
482
//                                    }else{
483
//                                            selectionIndex=Integer.parseInt(feat.getID());
484
//                                    }
485
//                                    if (selectionIndex!=-1) {
486
//                                            if (selectionSupport.isSelected(selectionIndex)) {
487
//                                                sym = sym.getSymbolForSelection();
488
//                                        }
489
//                                }
490

    
491
                                    // Check if this symbol is sized with CartographicSupport
492
                                    CartographicSupport csSym = null;
493
                                    int symbolType = sym.getSymbolType();
494
                                    boolean bDrawCartographicSupport = false;
495

    
496
                                    if (   symbolType == Geometry.TYPES.POINT
497
                                                    || symbolType == Geometry.TYPES.CURVE
498
                                                    || sym instanceof CartographicSupport) {
499

    
500
                                            // patch
501
                                        if (!sym.getClass().equals(FSymbol.class)) {
502
                                                csSym = (CartographicSupport) sym;
503
                                                bDrawCartographicSupport = (csSym.getUnit() != -1);
504
                                        }
505
                                    }
506

    
507
                                    int x = -1;
508
                                    int y = -1;
509
                                    int[] xyCoords = new int[2];
510

    
511
                                    // Check if size is a pixel
512
                                    boolean onePoint = bDrawCartographicSupport ?
513
                                                    isOnePoint(g.getTransform(), viewPort, MapContext.getScreenDPI(), csSym, geom, xyCoords) :
514
                                                    isOnePoint(g.getTransform(), viewPort, geom, xyCoords);
515

    
516
                                        // Avoid out of bounds exceptions
517
                                        if (onePoint) {
518
                                                x = xyCoords[0];
519
                                                y = xyCoords[1];
520
                                                if (x<0 || y<0 || x>= viewPort.getImageWidth() || y>=viewPort.getImageHeight()) {
521
                                                        continue;
522
                                                }
523
                                        }
524

    
525
                                        if (useZSort) {
526
                                                // Check if this symbol is a multilayer
527
                                                if (sym instanceof IMultiLayerSymbol) {
528
                                                        // if so, treat each of its layers as a single symbol
529
                                                        // in its corresponding map level
530
                                                        IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
531
                                                        for (int i = 0; !cancel.isCanceled() && i < mlSym.getLayerCount(); i++) {
532
                                                                ISymbol mySym = mlSym.getLayer(i);
533
                                                                int symbolLevel = zSort.getSymbolLevel(mySym);
534

    
535
                                                                if (symbolLevel == -1) {
536
                                                                        /* an error occured when managing symbol levels
537
                                                                         * some of the legend changed events regarding the
538
                                                                         * symbols did not finish satisfactory and the legend
539
                                                                         * is now inconsistent. For this drawing, it will finish
540
                                                                         * as it was at the bottom (level 0) but, when done, the
541
                                                                         * ZSort will be reset to avoid app crashes. This is
542
                                                                         * a bug that has to be fixed.
543
                                                                         */
544
                                                                        bSymbolLevelError = true;
545
                                                                        symbolLevel=0;
546
                                                                }
547

    
548
                                                                if (onePoint) {
549
                                                                        if (x<0 || y<0 || x>= imageLevels[symbolLevel].getWidth() || y>=imageLevels[symbolLevel].getHeight()) {
550
                                                                                continue;
551
                                                                        }
552
                                                                        imageLevels[symbolLevel].setRGB(x, y, mySym.getOnePointRgb());
553
                                                                } else {
554
                                                                        if (!bDrawCartographicSupport) {
555
                                                                                doc.setGraphics(graphics[symbolLevel]);
556
                                                                                doc.setSymbol(mySym);
557
                                                                                doc.setCancellable(cancel);
558
                                                                                geom.invokeOperation(DrawInts.CODE,doc);
559
                                                                        } else {
560
                                                                                doc.setGraphics(graphics[symbolLevel]);
561
                                                                                doc.setSymbol(mySym);
562
                                                                                doc.setCancellable(cancel);
563
                                                                                doc.setDPI(dpi);
564
                                                                                geom.invokeOperation(DrawInts.CODE,doc);
565
                                                                        }
566
                                                                }
567
                                                        }
568
                                                } else {
569
                                                        // else, just draw the symbol in its level
570
                                                        if (!bDrawCartographicSupport) {
571
                                                                doc.setGraphics(graphics[zSort.getSymbolLevel(sym)]);
572
                                                                doc.setSymbol(sym);
573
                                                                doc.setCancellable(cancel);
574
                                                                geom.invokeOperation(DrawInts.CODE,doc);
575
                                                        } else {
576
                                                                doc.setGraphics(graphics[zSort.getSymbolLevel(sym)]);
577
                                                                doc.setSymbol((ISymbol)csSym);
578
                                                                doc.setCancellable(cancel);
579
                                                                doc.setDPI(dpi);
580
                                                                geom.invokeOperation(DrawInts.CODE,doc);
581
                                                        }
582
                                                }
583

    
584
                                                // -- visual FX stuff
585
                                                // Cuando el offset!=0 se est? dibujando sobre el Layout y por tanto no tiene que ejecutar el siguiente c?digo.
586
                                                if (offset.getX()==0 && offset.getY()==0) {
587
                                                        if ((System.currentTimeMillis() - time) > screenRefreshDelay) {
588
                                                                virtualBim = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB);
589
                                                                virtualGraphics = virtualBim.createGraphics();
590
                                                                virtualGraphics.drawImage(image,0,0, null);
591
                                                                for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
592
                                                                        virtualGraphics.drawImage(imageLevels[i],0,0, null);
593
                                                                }
594
                                                                g.clearRect(0, 0, image.getWidth(), image.getHeight());
595
                                                                g.drawImage(virtualBim, 0, 0, null);
596
                                                                time = System.currentTimeMillis();
597
                                                        }
598
                                                // -- end visual FX stuff
599
                                                }
600

    
601
                                        } else {
602
                                                // no ZSort, so there is only a map level, symbols are
603
                                                // just drawn.
604
                                                if (onePoint) {
605
                                                        if (x<0 || y<0 || x>= image.getWidth() || y>=image.getHeight()) {
606
                                                                continue;
607
                                                        }
608
                                                        image.setRGB(x, y, sym.getOnePointRgb());
609
                                                } else {
610

    
611
                                                        if (!bDrawCartographicSupport) {
612
                                                                doc.setGraphics(g);
613
                                                                doc.setSymbol(sym);
614
                                                                doc.setCancellable(cancel);
615
                                                                geom.invokeOperation(DrawInts.CODE,doc);
616
                                                        } else {
617
                                                                doc.setGraphics(g);
618
                                                                doc.setSymbol((ISymbol)csSym);
619
                                                                doc.setCancellable(cancel);
620
                                                                doc.setDPI(dpi);
621
                                                                geom.invokeOperation(DrawInts.CODE,doc);
622
                                                        }
623
                                                }
624
                                        }
625
                            }
626

    
627
                            if (useZSort) {
628
                                    g.drawImage(image, 0, 0, null);
629
                                        g.translate(offset.getX(), offset.getY());
630
                                    for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
631
                                            g.drawImage(imageLevels[i],0,0, null);
632
                                            imageLevels[i] = null;
633
                                            graphics[i] = null;
634
                                    }
635
                                        g.translate(-offset.getX(), -offset.getY());
636
                                    imageLevels = null;
637
                                    graphics = null;
638
                            }
639
//                            it.closeIterator();
640
                            it=null;
641
                            featureCollection.dispose();
642

    
643
                            if (bSymbolLevelError) {
644
                                    ((IVectorLegend) getLegend()).setZSort(null);
645
                            }
646

    
647
                    } catch (ReadException e) {
648
                            this.setVisible(false);
649
                            this.setActive(false);
650
                            throw e;
651
                    } catch (GeometryOperationNotSupportedException e) {
652
                            this.setVisible(false);
653
                            this.setActive(false);
654
                            throw new ReadException(getName(),e);
655
                        } catch (GeometryOperationException e) {
656
                                this.setVisible(false);
657
                            this.setActive(false);
658
                            throw new ReadException(getName(),e);
659
                        } catch (BaseException e) {
660
                                this.setVisible(false);
661
                            this.setActive(false);
662
                            throw new ReadException(getName(),e);
663
                        }
664

    
665

    
666
            }
667
    }
668

    
669
//           public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
670
//            Cancellable cancel, double scale) throws ReadException {
671
////            forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD = true;
672
//            if (!isUseStrategy()) {
673
//                    _draw(image, g, viewPort, cancel, scale);
674
//            } else {
675
////                    moved up to FLayers
676
////                    if (isWithinScale(scale)) {
677
//
678
//
679
//                            // Las que solo tienen etiquetado sin pintar el shape,
680
//                            // no pasamos por ellas
681
//                            boolean bDrawShapes = true;
682
//                            if (legend instanceof SingleSymbolLegend) {
683
//                                    if (legend.getDefaultSymbol().isShapeVisible() == false)
684
//                                            bDrawShapes = false;
685
//                            }
686
//                            if (bDrawShapes) {
687
//                                    Strategy strategy = StrategyManager.getStrategy(this);
688
//                                    try {
689
//                                            prepareDrawing(image, g, viewPort);
690
//                                            strategy.draw(image, g, viewPort, cancel);
691
//                                    } catch (ReadDriverException e) {
692
//                                            this.setVisible(false);
693
//                                            this.setActive(false);
694
//                                            throw e;
695
//                                    }
696
//                            }
697
//                            if (getVirtualLayers() != null) {
698
//                                    getVirtualLayers().draw(image, g, viewPort, cancel, scale);
699
//                            }
700
////                    }
701
//            }
702
//    }
703

    
704
    /**
705
     * Se llama antes de empezar a pintar.
706
     * Es ?til para preparar la cache a emplear, las leyendas, etc.
707
     * @param image
708
     * @param g
709
     * @param viewPort
710
     */
711
    private void prepareDrawing(BufferedImage image, Graphics2D g, ViewPort viewPort) {
712

    
713
    }
714

    
715
    public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
716
                    double scale, PrintRequestAttributeSet properties) throws ReadException {
717
            // TEST METHOD
718

    
719

    
720
                    /* SVN */
721

    
722
    /*        boolean bDrawShapes = true;
723
            if (legend instanceof SingleSymbolLegend) {
724
                    bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
725
            }
726

727

728
            if (bDrawShapes) {
729
                    double dpi = 72;
730

731
                    PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
732
                    if (resolution.equals(PrintQuality.NORMAL)){
733
                            dpi = 300;
734
                    } else if (resolution.equals(PrintQuality.HIGH)){
735
                            dpi = 600;
736
                    } else if (resolution.equals(PrintQuality.DRAFT)){
737
                            dpi = 72;
738
                    }
739

740

741
                    try {
742
                            prepareDrawing(null, g, viewPort);
743
                            ArrayList<String> fieldList = new ArrayList<String>();
744
                            String[] aux;
745

746
                            // fields from legend
747
                            if (legend instanceof IClassifiedVectorLegend) {
748
                                    aux = ((IClassifiedVectorLegend) legend).
749
                                                                            getClassifyingFieldNames();
750
                                    for (int i = 0; i < aux.length; i++) {
751
                                            fieldList.add(aux[i]);
752
                                    }
753
                            }
754

755
                            // fields from labeling
756
                            if (isLabeled()) {
757
                                    aux = getLabelingStrategy().getUsedFields();
758
                                    for (int i = 0; i < aux.length; i++) {
759
                                            fieldList.add(aux[i]);
760
                                    }
761
                            }
762

763
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
764

765
                            // if layer has map levels it will use a ZSort
766
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
767

768

769
                            int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
770
                            for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
771
                                    // Get the iterator over the visible features
772
                                    IFeatureIterator it = getSource().getFeatureIterator(
773
                                                    viewPort.getAdjustedExtent(),
774
                                                    fieldList.toArray(new String[fieldList.size()]),
775
                                                    viewPort.getProjection(),
776
                                                    true);
777

778
                                    // Iteration over each feature
779
                                    while ( !cancel.isCanceled() && it.hasNext()) {
780
                                            IFeature feat = it.next();
781
                                            IGeometry geom = feat.getGeometry();
782

783
                                            // retreive the symbol associated to such feature
784
                                            ISymbol sym = legend.getSymbolByFeature(feat);
785

786
                                            if (useZSort) {
787
                                                    // Check if this symbol is a multilayer
788
                                                        if (sym instanceof IMultiLayerSymbol) {
789
                                                                // if so, get the layer corresponding to the current
790
                                                                // level. If none, continue to next iteration
791
                                                                IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
792
                                                                for (int i = 0; i < mlSym.getLayerCount(); i++) {
793
                                                                        ISymbol mySym = mlSym.getLayer(i);
794
                                                                        if (zSort.getSymbolLevel(mySym) == mapPass) {
795
                                                                                sym = mySym;
796
                                                                                break;
797
                                                                        }
798
                                                                        System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")");
799
                                                                }
800

801
                                                                if (sym == null) {
802
                                                                        continue;
803
                                                                }
804
                                                        } else {
805
                                                                // else, just draw the symbol in its level
806
                                                                if (zSort.getSymbolLevel(sym) != mapPass) {
807
                                                                        System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")");
808
                                                                        continue;
809
                                                                }
810
                                                        }
811
                                            }
812

813
                                            // Check if this symbol is sized with CartographicSupport
814
                                            CartographicSupport csSym = null;
815
                                            int symbolType = sym.getSymbolType();
816
                                            boolean bDrawCartographicSupport = false;
817

818
                                            if (   symbolType == FShape.POINT
819
                                                            || symbolType == FShape.LINE
820
                                                            || sym instanceof CartographicSupport) {
821

822
                                                    csSym = (CartographicSupport) sym;
823
                                                    bDrawCartographicSupport = (csSym.getUnit() != -1);
824
                                            }
825

826
                                            System.err.println("passada "+mapPass+" pinte s?mboll "+sym.getDescription());
827

828
                                            if (!bDrawCartographicSupport) {
829
                                                    geom.drawInts(g, viewPort, sym, null);
830
                                            } else {
831
                                                    geom.drawInts(g, viewPort, dpi, (CartographicSupport) csSym);
832
                                            }
833

834
                                    }
835
                                    it.closeIterator();
836
                            }
837
                    } catch (ReadDriverException e) {
838
                            this.setVisible(false);
839
                            this.setActive(false);
840
                            throw e;
841
                    }
842
        */
843

    
844

    
845
            // TEST METHOD
846
            boolean bDrawShapes = true;
847
            if (legend instanceof SingleSymbolLegend) {
848
                    bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
849
            }
850

    
851

    
852
            if (bDrawShapes) {
853

    
854
                    try {
855
                            double dpi = 72;
856

    
857
                            PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
858
                            if (resolution.equals(PrintQuality.NORMAL)){
859
                                    dpi = 300;
860
                            } else if (resolution.equals(PrintQuality.HIGH)){
861
                                    dpi = 600;
862
                            } else if (resolution.equals(PrintQuality.DRAFT)){
863
                                    dpi = 72;
864
                            }
865
                            ArrayList<String> fieldList = new ArrayList<String>();
866
                            String[] aux;
867

    
868
                            // fields from legend
869
                            if (legend instanceof IClassifiedVectorLegend) {
870
                                    aux = ((IClassifiedVectorLegend) legend).
871
                                    getClassifyingFieldNames();
872
                                    for (int i = 0; i < aux.length; i++) {
873
                                            fieldList.add(aux[i]);
874
                                    }
875
                            }
876
//
877
//                            // fields from labeling
878
//                            if (isLabeled()) {
879
//                                    aux = getLabelingStrategy().getUsedFields();
880
//                                    for (int i = 0; i < aux.length; i++) {
881
//                                            fieldList.add(aux[i]);
882
//                                    }
883
//                            }
884

    
885
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
886

    
887
                            // if layer has map levels it will use a ZSort
888
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
889

    
890

    
891
                            int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
892
                            for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
893
                                    // Get the iterator over the visible features
894
                                    FeatureStore featureStore=(FeatureStore)getDataStore();
895
                                // Get the iterator over the visible features
896
                                    FeatureCollection featureCollection=null;
897
                                featureCollection= (FeatureCollection) featureStore.getDataCollection(
898
                                                fieldList.toArray(new String[fieldList.size()]),
899
                                                null,//filter
900
                                                null);//order
901
                                Iterator it = featureCollection.iterator();
902
//                                                    viewPort.getAdjustedExtent(),
903
//                                                    fieldList.toArray(new String[fieldList.size()]),
904
//                                                    viewPort.getProjection(),
905
//                                                    true);
906

    
907
                                    // Iteration over each feature
908
                                    while ( !cancel.isCanceled() && it.hasNext()) {
909
                                            Feature feat = (Feature)it.next();
910
                                            Geometry geom = (Geometry)feat.getDefaultGeometry();
911

    
912
                                            // retreive the symbol associated to such feature
913
                                            ISymbol sym = legend.getSymbolByFeature(feat);
914

    
915
                                            if (useZSort) {
916
                                                    // Check if this symbol is a multilayer
917
                                                    if (sym instanceof IMultiLayerSymbol) {
918
                                                            // if so, get the layer corresponding to the current
919
                                                            // level. If none, continue to next iteration
920
                                                            IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
921
                                                            for (int i = 0; i < mlSym.getLayerCount(); i++) {
922
                                                                    ISymbol mySym = mlSym.getLayer(i);
923
                                                                    if (zSort.getSymbolLevel(mySym) == mapPass) {
924
                                                                            sym = mySym;
925
                                                                            break;
926
                                                                    }
927
                                                                    System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")");
928
                                                            }
929

    
930
                                                            if (sym == null) {
931
                                                                    continue;
932
                                                            }
933
                                                    } else {
934
                                                            // else, just draw the symbol in its level
935
                                                            if (zSort.getSymbolLevel(sym) != mapPass) {
936
                                                                    System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")");
937
                                                                    continue;
938
                                                            }
939
                                                    }
940
                                            }
941

    
942
                                            // Check if this symbol is sized with CartographicSupport
943
                                            CartographicSupport csSym = null;
944
                                            int symbolType = sym.getSymbolType();
945
                                            boolean bDrawCartographicSupport = false;
946

    
947
                                            if (   symbolType == Geometry.TYPES.POINT
948
                                                            || symbolType == Geometry.TYPES.CURVE
949
                                                            || sym instanceof CartographicSupport) {
950

    
951
                                                    csSym = (CartographicSupport) sym;
952
                                                    bDrawCartographicSupport = (csSym.getUnit() != -1);
953
                                            }
954

    
955
                                            System.err.println("passada "+mapPass+" pinte s?mboll "+sym.getDescription());
956

    
957
                                            if (!bDrawCartographicSupport) {
958
                                                        DrawOperationContext doc=new DrawOperationContext();
959
                                                        doc.setGraphics(g);
960
                                                        doc.setViewPort(viewPort);
961
                                                        doc.setSymbol(sym);
962
                                                        doc.setCancellable(cancel);
963
                                                        geom.invokeOperation(DrawInts.CODE,doc);
964
                                                } else {
965
                                                        DrawOperationContext doc=new DrawOperationContext();
966
                                                        doc.setGraphics(g);
967
                                                        doc.setViewPort(viewPort);
968
                                                        doc.setSymbol((ISymbol)csSym);
969
                                                        doc.setCancellable(cancel);
970
                                                        doc.setDPI(dpi);
971
                                                        geom.invokeOperation(DrawInts.CODE,doc);
972
                                                }
973
                                    }
974
//                                    it.closeIterator();
975
                                    it=null;
976
                                    featureCollection.dispose();
977
                            }
978
                    } catch (ReadException e) {
979
                            this.setVisible(false);
980
                            this.setActive(false);
981
                            throw e;
982
                    } catch (GeometryOperationNotSupportedException e) {
983
                            this.setVisible(false);
984
                            this.setActive(false);
985
                            throw new ReadException(getName(),e);
986
                        } catch (GeometryOperationException e) {
987
                                this.setVisible(false);
988
                            this.setActive(false);
989
                            throw new ReadException(getName(),e);
990
                        }
991
            }
992
    }
993

    
994

    
995
//    public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
996
//            double scale, PrintRequestAttributeSet properties) throws ReadException {
997
//            if (forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD) {
998
//                    _print(g, viewPort, cancel, scale, properties);
999
//            } else {
1000
////                    moved up to Flayers
1001
////                    if (isVisible() && isWithinScale(scale)) {
1002
//                            Strategy strategy = StrategyManager.getStrategy(this);
1003
//
1004
//                            strategy.print(g, viewPort, cancel, properties);
1005
//                            ILabelingStrategy labeling;
1006
//                            if ( (labeling = getLabelingStrategy() ) != null) {
1007
//                                    // contains labels
1008
//                                    labeling.print(g, viewPort, cancel, properties);
1009
//                            }
1010
////                    }
1011
//            }
1012
//    }
1013

    
1014
//    public void deleteSpatialIndex() {
1015
//        //must we delete possible spatial indexes files?
1016
//        spatialIndex = null;
1017
//    }
1018

    
1019
   /**
1020
    * <p>
1021
    * Creates an spatial index associated to this layer.
1022
    * The spatial index will used
1023
    * the native projection of the layer, so if the layer is reprojected, it will
1024
    * be ignored.
1025
    * </p>
1026
    * @param cancelMonitor instance of CancellableMonitorable that allows
1027
    * to monitor progress of spatial index creation, and cancel the process
1028
    */
1029
//    public void createSpatialIndex(CancellableMonitorable cancelMonitor){
1030
//         // FJP: ESTO HABR? QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
1031
//        // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
1032
//        // para que acepten recorrer sin geometria, solo con rectangulos.
1033
//
1034
//        //If this vectorial layer is based in a spatial database, the spatial
1035
//        //index is already implicit. We only will index file drivers
1036
//        ReadableVectorial va = getSource();
1037
//        //We must think in non spatial databases, like HSQLDB
1038
//        if(!(va instanceof VectorialFileAdapter)){
1039
//            return;
1040
//        }
1041
//        if (!(va.getDriver() instanceof BoundedShapes)) {
1042
//            return;
1043
//        }
1044
//        File file = ((VectorialFileAdapter) va).getFile();
1045
//        String fileName = file.getAbsolutePath();
1046
//        ISpatialIndex localCopy = null;
1047
//        try {
1048
//            va.start();
1049
//            localCopy = new QuadtreeGt2(fileName, "NM", va.getFullExtent(),
1050
//                    va.getShapeCount(), true);
1051
//
1052
//        } catch (SpatialIndexException e1) {
1053
//            // Probably we dont have writing permissions
1054
//            String directoryName = System.getProperty("java.io.tmpdir");
1055
//            File newFile = new File(directoryName +
1056
//                    File.separator +
1057
//                    file.getName());
1058
//            String newFileName = newFile.getName();
1059
//            try {
1060
//                localCopy = new QuadtreeGt2(newFileName, "NM", va.getFullExtent(),
1061
//                        va.getShapeCount(), true);
1062
//            } catch (SpatialIndexException e) {
1063
//                // if we cant build a file based spatial index, we'll build
1064
//                // a pure memory spatial index
1065
//                localCopy = new QuadtreeJts();
1066
//            } catch (ReadException e) {
1067
//                localCopy = new QuadtreeJts();
1068
//            }
1069
//
1070
//        } catch(Exception e){
1071
//            e.printStackTrace();
1072
//        }//try
1073
//        BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
1074
//        try {
1075
//            for (int i=0; i < va.getShapeCount(); i++)
1076
//            {
1077
//                if(cancelMonitor != null){
1078
//                    if(cancelMonitor.isCanceled())
1079
//                        return;
1080
//                    cancelMonitor.reportStep();
1081
//                }
1082
//                Rectangle2D r = shapeBounds.getShapeBounds(i);
1083
//                if(r != null)
1084
//                    localCopy.insert(r, i);
1085
//            } // for
1086
//            va.stop();
1087
//            if(localCopy instanceof IPersistentSpatialIndex)
1088
//                ((IPersistentSpatialIndex) localCopy).flush();
1089
//            spatialIndex = localCopy;
1090
//            //vectorial adapter needs a reference to the spatial index, to solve
1091
//            //request for feature iteration based in spatial queries
1092
//            source.setSpatialIndex(spatialIndex);
1093
//        } catch (ReadException e) {
1094
//            // TODO Auto-generated catch block
1095
//            e.printStackTrace();
1096
//        }
1097
//    }
1098

    
1099
//    public void createSpatialIndex() {
1100
//        createSpatialIndex(null);
1101
//    }
1102

    
1103
//    public void process(FeaturesVisitor visitor, Rectangle2D rect)
1104
//            throws ReadException {
1105
//        Strategy s = StrategyManager.getStrategy(this);
1106
//        s.process(visitor, rect);
1107
//    }
1108

    
1109
//    public FBitSet queryByRect(Rectangle2D rect) throws ReadException {
1110
//        Strategy s = StrategyManager.getStrategy(this);
1111
//
1112
//        return s.queryByRect(rect);
1113
//    }
1114

    
1115
//    public FBitSet queryByPoint(Point2D p, double tolerance)
1116
//            throws ReadException {
1117
//        Strategy s = StrategyManager.getStrategy(this);
1118
//        return s.queryByPoint(p, tolerance);
1119
//    }
1120

    
1121
//    public FBitSet queryByShape(Geometry g, int relationship)
1122
//            throws ReadException {
1123
//        Strategy s = StrategyManager.getStrategy(this);
1124
//        return s.queryByShape(g, relationship);
1125
//    }
1126

    
1127
//    public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException, VisitorException {
1128
//        Point2D pReal = this.getMapContext().getViewPort().toMapPoint(p);
1129
//        FBitSet bs = queryByPoint(pReal, tolerance);
1130
//        VectorialXMLItem[] item = new VectorialXMLItem[1];
1131
//        item[0] = new VectorialXMLItem(bs, this);
1132
//
1133
//        return item;
1134
//    }
1135

    
1136
    public void setLegend(IVectorLegend r) throws LegendLayerException {
1137
        IVectorLegend oldLegend = legend;
1138
        legend = r;
1139
        try {
1140
            legend.setFeatureStore(getFeatureStore());
1141
        } catch (ReadException e1) {
1142
            throw new LegendLayerException(getName(),e1);
1143
        }
1144
        LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
1145
                oldLegend, legend);
1146
        callLegendChanged(e);
1147
    }
1148

    
1149
    /**
1150
     * Devuelve la Leyenda de la capa.
1151
     *
1152
     * @return Leyenda.
1153
     */
1154
    public ILegend getLegend() {
1155
        return legend;
1156
    }
1157

    
1158
    /**
1159
     * Devuelve el tipo de shape que contiene la capa.
1160
     *
1161
     * @return tipo de shape.
1162
     *
1163
     * @throws DriverException
1164
     */
1165
    public int getShapeType() throws ReadException {
1166
        if (typeShape == -1) {
1167
//            getSource().start();
1168
            typeShape = ((FeatureType)((FeatureStore)getDataStore()).getFeatureTypes().get(0)).getGeometryTypes()[0];
1169
//            getSource().stop();
1170
        }
1171

    
1172
        return typeShape;
1173
    }
1174

    
1175
    public XMLEntity getXMLEntity() throws XMLException {
1176
//        if (!this.isAvailable() && this.orgXMLEntity != null) {
1177
//            return this.orgXMLEntity;
1178
//        }
1179
//        XMLEntity xml = super.getXMLEntity();
1180
//        if (getLegend()!=null)
1181
//            xml.addChild(getLegend().getXMLEntity());
1182
//        try {
1183
//            if (getRecordset()!=null)
1184
//                xml.addChild(getRecordset().getSelectionSupport().getXMLEntity());
1185
//        } catch (ReadException e1) {
1186
//            e1.printStackTrace();
1187
//            throw new XMLException(e1);
1188
//        }
1189
//        // Repongo el mismo ReadableVectorial m?s abajo para cuando se guarda el proyecto.
1190
//        ReadableVectorial rv=getSource();
1191
//        xml.putProperty("type", "vectorial");
1192
//        if (source instanceof VectorialEditableAdapter) {
1193
//            setSource(((VectorialEditableAdapter) source).getOriginalAdapter());
1194
//        }
1195
//        if (source instanceof VectorialFileAdapter) {
1196
//            xml.putProperty("type", "vectorial");
1197
//            xml.putProperty("file", ((VectorialFileAdapter) source)
1198
//                    .getFile());
1199
//            try {
1200
//                xml.putProperty("recordset-name", source.getRecordset()
1201
//                        .getName());
1202
//            } catch (ReadException e) {
1203
//                throw new XMLException(e);
1204
//            } catch (RuntimeException e) {
1205
//                e.printStackTrace();
1206
//            }
1207
//        } else if (source instanceof VectorialDBAdapter) {
1208
//            xml.putProperty("type", "vectorial");
1209
//
1210
//            IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) source
1211
//                    .getDriver();
1212
//
1213
//            // Guardamos el nombre del driver para poder recuperarlo
1214
//            // con el DriverManager de Fernando.
1215
//            xml.putProperty("db", dbDriver.getName());
1216
//            try {
1217
//                xml.putProperty("recordset-name", source.getRecordset()
1218
//                        .getName());
1219
//            } catch (ReadException e) {
1220
//                throw new XMLException(e);
1221
//            } catch (RuntimeException e) {
1222
//                e.printStackTrace();
1223
//            }
1224
//            xml.addChild(dbDriver.getXMLEntity()); // Tercer child. Antes hemos
1225
//                                                    // metido la leyenda y el
1226
//                                                    // selection support
1227
//        } else if (source instanceof VectorialAdapter) {
1228
//            // Se supone que hemos hecho algo gen?rico.
1229
//            xml.putProperty("type", "vectorial");
1230
//
1231
//            VectorialDriver driver = source.getDriver();
1232
//
1233
//            // Guardamos el nombre del driver para poder recuperarlo
1234
//            // con el DriverManager de Fernando.
1235
//            xml.putProperty("other", driver.getName());
1236
//            // try {
1237
//            try {
1238
//                xml.putProperty("recordset-name", source.getRecordset()
1239
//                        .getName());
1240
//            } catch (ReadException e) {
1241
//                throw new XMLException(e);
1242
//            } catch (RuntimeException e) {
1243
//                e.printStackTrace();
1244
//            }
1245
//            if (driver instanceof IPersistence) {
1246
//                // xml.putProperty("className", driver.getClass().getName());
1247
//                    IPersistence persist = (IPersistence) driver;
1248
//                xml.addChild(persist.getXMLEntity()); // Tercer child. Antes
1249
//                                                        // hemos metido la
1250
//                                                        // leyenda y el
1251
//                                                        // selection support
1252
//            }
1253
//        }
1254
//        if (rv!=null)
1255
//            setSource(rv);
1256
//        xml.putProperty("driverName", source.getDriver().getName());
1257
//        if (bHasJoin)
1258
//            xml.putProperty("hasJoin", "true");
1259
//
1260
//        // properties from ILabelable
1261
//        xml.putProperty("isLabeled", isLabeled);
1262
//        if (strategy != null) {
1263
//            XMLEntity strategyXML = strategy.getXMLEntity();
1264
//            strategyXML.putProperty("Strategy", strategy.getClassName());
1265
//            xml.addChild(strategy.getXMLEntity());
1266
//        }
1267
//        xml.addChild(getLinkProperties().getXMLEntity());
1268
//        return xml;
1269
            return null;
1270
    }
1271
    /*
1272
     * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
1273
     */
1274
    public void setXMLEntity(XMLEntity xml) throws XMLException {
1275
//        try {
1276
//                    super.setXMLEntity(xml);
1277
//                    XMLEntity legendXML = xml.getChild(0);
1278
//                    IVectorLegend leg = LegendFactory.createFromXML(legendXML);
1279
//                    /* (jaume) begin patch;
1280
//                     * for backward compatibility purposes. Since gvSIG v1.1 labeling is
1281
//                     * no longer managed by the Legend but by the ILabelingStrategy. The
1282
//                     * following allows restoring older projects' labelings.
1283
//                     */
1284
//                    if (legendXML.contains("labelFieldName")) {
1285
//                            String labelTextField = legendXML.getStringProperty("labelFieldName");
1286
//                            if (labelTextField != null) {
1287
//                                    AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1288
//                                    labeling.setLayer(this);
1289
//                                    labeling.setTextField(legendXML.getStringProperty("labelFieldName"));
1290
//                                    labeling.setHeightField(legendXML.getStringProperty("labelHeightFieldName"));
1291
//                                    labeling.setRotationField(legendXML.getStringProperty("labelRotationFieldName"));
1292
//                                    this.setLabelingStrategy(labeling);
1293
//                                    this.setIsLabeled(true);
1294
//                            }
1295
//                    }
1296
//                    /* end patch */
1297
//                    try {
1298
//                            getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
1299
//                            // JMVIVO: Esto sirve para algo????
1300
//                            String recordsetName = xml.getStringProperty("recordset-name");
1301
//
1302
//                            LayerFactory.getDataSourceFactory().changeDataSourceName(
1303
//                                            getSource().getRecordset().getName(), recordsetName);
1304
//                    } catch (NoSuchTableException e1) {
1305
//                            this.setAvailable(false);
1306
//                            throw new XMLException(e1);
1307
//                    } catch (ReadException e1) {
1308
//                            this.setAvailable(false);
1309
//                            throw new XMLException(e1);
1310
//                    }
1311
//                    // Si tiene una uni?n, lo marcamos para que no se cree la leyenda hasta
1312
//                    // el final
1313
//                    // de la lectura del proyecto
1314
//                    if (xml.contains("hasJoin")) {
1315
//                            setIsJoined(true);
1316
//                            PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
1317
//                    } else {
1318
//                            try {
1319
//                                    setLegend(leg);
1320
//                            } catch (LegendLayerException e) {
1321
//                                    throw new XMLException(e);
1322
//                            }
1323
//                    }
1324
//
1325
//                    // set properties for ILabelable
1326
//                    XMLEntity labelingXML = xml.firstChild("id", "LabelingStrategy");
1327
//                    if (labelingXML!= null) {
1328
//                            isLabeled = true;
1329
//                            try {
1330
//                                    this.strategy = LabelingFactory.createStrategyFromXML(labelingXML, this);
1331
//                            } catch (NotExistInXMLEntity neXMLEX) {
1332
//                                    // no strategy was set, just continue;
1333
//                                    logger.warn("Reached what should be unreachable code");
1334
//                            }
1335
//                    } else {
1336
//                            isLabeled = false;
1337
//                    }
1338
//
1339
//                    XMLEntity xmlLinkProperties=xml.firstChild("typeChild","linkProperties");
1340
//                    if (xmlLinkProperties != null){
1341
//                            getLinkProperties().setXMLEntity(xmlLinkProperties);
1342
//                    }
1343
//
1344
//            } catch (XMLException e) {
1345
//                    this.setAvailable(false);
1346
//                    this.orgXMLEntity = xml;
1347
//            } catch (Exception e) {
1348
//                    e.printStackTrace();
1349
//                    this.setAvailable(false);
1350
//                    this.orgXMLEntity = xml;
1351
//
1352
//            }
1353
//
1354

    
1355
    }
1356

    
1357
    public void setXMLEntityNew(XMLEntity xml) throws XMLException {
1358
//        try {
1359
//            super.setXMLEntity(xml);
1360
//
1361
//            XMLEntity legendXML = xml.getChild(0);
1362
//            IVectorLegend leg = LegendFactory.createFromXML(legendXML);
1363
//            /* (jaume) begin patch;
1364
//             * for backward compatibility purposes. Since gvSIG v1.1 labeling is
1365
//             * no longer managed by the Legend but by the ILabelingStrategy. The
1366
//             * following allows restoring older projects' labelings.
1367
//             */
1368
//            if (legendXML.contains("labelFieldHeight")) {
1369
//                AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1370
//                labeling.setLayer(this);
1371
//                labeling.setTextField(legendXML.getStringProperty("labelFieldHeight"));
1372
//                labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
1373
//                this.setLabelingStrategy(labeling);
1374
//                this.setIsLabeled(true);
1375
//              }
1376
//            /* end patch */
1377
//            try {
1378
//                getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
1379
//
1380
//                this.setLoadSelection(xml.getChild(1));
1381
//            } catch (ReadException e1) {
1382
//                this.setAvailable(false);
1383
//                throw new XMLException(e1);
1384
//            }
1385
//            // Si tiene una uni?n, lo marcamos para que no se cree la leyenda hasta
1386
//            // el final
1387
//            // de la lectura del proyecto
1388
//            if (xml.contains("hasJoin")) {
1389
//                setIsJoined(true);
1390
//                PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
1391
//            } else {
1392
//                this.setLoadLegend(leg);
1393
//            }
1394
//
1395
//        } catch (XMLException e) {
1396
//            this.setAvailable(false);
1397
//            this.orgXMLEntity = xml;
1398
//        } catch (Exception e) {
1399
//            this.setAvailable(false);
1400
//            this.orgXMLEntity = xml;
1401
//        }
1402

    
1403

    
1404
    }
1405

    
1406

    
1407
    /**
1408
     * Sobreimplementaci?n del m?todo toString para que las bases de datos
1409
     * identifiquen la capa.
1410
     *
1411
     * @return DOCUMENT ME!
1412
     */
1413
    public String toString() {
1414
        /*
1415
         * Se usa internamente para que la parte de datos identifique de forma
1416
         * un?voca las tablas
1417
         */
1418
        String ret = super.toString();
1419

    
1420
        return "layer" + ret.substring(ret.indexOf('@') + 1);
1421
    }
1422

    
1423
    public boolean isJoined() {
1424
        return bHasJoin;
1425
    }
1426

    
1427
    /**
1428
     * Returns if a layer is spatially indexed
1429
     *
1430
     * @return if this layer has the ability to proces spatial queries without
1431
     *         secuential scans.
1432
     */
1433
//    public boolean isSpatiallyIndexed() {
1434
//        ReadableVectorial source = getSource();
1435
//        if (source instanceof ISpatialDB)
1436
//            return true;
1437
//
1438
////FIXME azabala
1439
///*
1440
// * Esto es muy dudoso, y puede cambiar.
1441
// * Estoy diciendo que las que no son fichero o no son
1442
// * BoundedShapes estan indexadas. Esto es mentira, pero
1443
// * as? quien pregunte no querr? generar el indice.
1444
// * Esta por ver si interesa generar el indice para capas
1445
// * HSQLDB, WFS, etc.
1446
// */
1447
//        if(!(source instanceof VectorialFileAdapter)){
1448
//            return true;
1449
//        }
1450
//        if (!(source.getDriver() instanceof BoundedShapes)) {
1451
//            return true;
1452
//        }
1453
//
1454
//        if (getISpatialIndex() != null)
1455
//            return true;
1456
//        return false;
1457
//    }
1458

    
1459
    public void setIsJoined(boolean hasJoin) {
1460
        bHasJoin = hasJoin;
1461
    }
1462

    
1463
//    /**
1464
//     * @return Returns the spatialIndex.
1465
//     */
1466
//    public ISpatialIndex getISpatialIndex() {
1467
//        return spatialIndex;
1468
//    }
1469
//    /**
1470
//     * Sets the spatial index. This could be useful if, for some
1471
//     * reasons, you want to work with a distinct spatial index
1472
//     * (for example, a spatial index which could makes nearest
1473
//     * neighbour querys)
1474
//     * @param spatialIndex
1475
//     */
1476
//    public void setISpatialIndex(ISpatialIndex spatialIndex){
1477
//        this.spatialIndex = spatialIndex;
1478
//    }
1479

    
1480
//    public SelectableDataSource getRecordset() throws ReadException {
1481
//        if (!this.isAvailable()) return null;
1482
//        if (sds == null) {
1483
//
1484
//                SelectableDataSource ds = source.getRecordset();
1485
//
1486
//                if (ds == null) {
1487
//                    return null;
1488
//                }
1489
//
1490
//                sds = ds;
1491
//                sds.setSelectionSupport(selectionSupport);
1492
//
1493
//        }
1494
//        return sds;
1495
//    }
1496

    
1497
    public void setEditing(boolean b) throws StartEditionLayerException {
1498
        super.setEditing(b);
1499
        try {
1500
                        getDataStore().startEditing();
1501
                } catch (ReadException e) {
1502
                        throw new StartEditionLayerException(getName(),e);
1503
                }
1504
//        try {
1505
//            if (b) {
1506
//                VectorialEditableAdapter vea = null;
1507
//                // TODO: Qu? pasa si hay m?s tipos de adapters?
1508
//                // FJP: Se podr?a pasar como argumento el
1509
//                // VectorialEditableAdapter
1510
//                // que se quiera usar para evitar meter c?digo aqu? de este
1511
//                // estilo.
1512
//                if (getSource() instanceof VectorialDBAdapter) {
1513
//                    vea = new VectorialEditableDBAdapter();
1514
//                } else if (this instanceof FLyrAnnotation) {
1515
//                    vea = new AnnotationEditableAdapter(
1516
//                            (FLyrAnnotation) this);
1517
//                } else {
1518
//                    vea = new VectorialEditableAdapter();
1519
//                }
1520
//                vea.setOriginalVectorialAdapter(getSource());
1521
////                                azo: implementations of readablevectorial need
1522
//                //references of projection and spatial index
1523
//                vea.setProjection(getProjection());
1524
//                vea.setSpatialIndex(spatialIndex);
1525
//
1526
//
1527
//                // /vea.setSpatialIndex(getSpatialIndex());
1528
//                // /vea.setFullExtent(getFullExtent());
1529
//                vea.setCoordTrans(getCoordTrans());
1530
//                vea.startEdition(EditionEvent.GRAPHIC);
1531
//                setSource(vea);
1532
//                getRecordset().setSelectionSupport(
1533
//                        vea.getOriginalAdapter().getRecordset()
1534
//                                .getSelectionSupport());
1535
//
1536
//            } else {
1537
//                VectorialEditableAdapter vea = (VectorialEditableAdapter) getSource();
1538
//                setSource(vea.getOriginalAdapter());
1539
//            }
1540
//            // Si tenemos una leyenda, hay que pegarle el cambiazo a su
1541
//            // recordset
1542
//            setRecordset(getSource().getRecordset());
1543
//            if (getLegend() instanceof IVectorLegend) {
1544
//                IVectorLegend ley = (IVectorLegend) getLegend();
1545
//                ley.setDataSource(getSource().getRecordset());
1546
//                // Esto lo pongo para evitar que al dibujar sobre un
1547
//                // dxf, dwg, o dgn no veamos nada. Es debido al checkbox
1548
//                // de la leyenda de textos "dibujar solo textos".
1549
////jaume
1550
////                                if (!(getSource().getDriver() instanceof IndexedShpDriver)){
1551
////                                        FSymbol symbol=new FSymbol(getShapeType());
1552
////                                        symbol.setFontSizeInPixels(false);
1553
////                                        symbol.setFont(new Font("SansSerif", Font.PLAIN, 9));
1554
////                                        Color color=symbol.getColor();
1555
////                                        int alpha=symbol.getColor().getAlpha();
1556
////                                        if (alpha>250) {
1557
////                                                symbol.setColor(new Color(color.getRed(),color.getGreen(),color.getBlue(),100));
1558
////                                        }
1559
////                                        ley.setDefaultSymbol(symbol);
1560
////                                }
1561
////jaume//
1562
//                ley.useDefaultSymbol(true);
1563
//            }
1564
//        } catch (ReadDriverException e) {
1565
//            throw new StartEditionLayerException(getName(),e);
1566
//        } catch (FieldNotFoundException e) {
1567
//            throw new StartEditionLayerException(getName(),e);
1568
//        } catch (StartWriterVisitorException e) {
1569
//            throw new StartEditionLayerException(getName(),e);
1570
//        }
1571

    
1572
        setSpatialCacheEnabled(b);
1573
        callEditionChanged(LayerEvent
1574
                .createEditionChangedEvent(this, "edition"));
1575

    
1576
    }
1577

    
1578
    /**
1579
     * Para cuando haces una uni?n, sustituyes el recorset por el nuevo. De esta
1580
     * forma, podr?s poner leyendas basadas en el nuevo recordset
1581
     *
1582
     * @param newSds
1583
     */
1584
//    public void setRecordset(SelectableDataSource newSds) {
1585
//        sds = newSds;
1586
//        sds.setSelectionSupport(selectionSupport);
1587
//    }
1588

    
1589
    public void clearSpatialCache()
1590
    {
1591
        spatialCache.clearAll();
1592
    }
1593

    
1594
    public boolean isSpatialCacheEnabled() {
1595
        return spatialCacheEnabled;
1596
    }
1597

    
1598
    public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
1599
        this.spatialCacheEnabled = spatialCacheEnabled;
1600
    }
1601

    
1602
    public SpatialCache getSpatialCache() {
1603
        return spatialCache;
1604
    }
1605

    
1606
    /**
1607
     * Siempre es un numero mayor de 1000
1608
     * @param maxFeatures
1609
     */
1610
    public void setMaxFeaturesInEditionCache(int maxFeatures) {
1611
        if (maxFeatures > spatialCache.getMaxFeatures()) {
1612
                        spatialCache.setMaxFeatures(maxFeatures);
1613
                }
1614

    
1615
    }
1616

    
1617
    /**
1618
     * This method returns a boolean that is used by the FPopMenu
1619
     * to make visible the properties menu or not. It is visible by
1620
     * default, and if a later don't have to show this menu only
1621
     * has to override this method.
1622
     * @return
1623
     * If the properties menu is visible (or not)
1624
     */
1625
    public boolean isPropertiesMenuVisible(){
1626
        return true;
1627
    }
1628

    
1629
    public void reload() throws ReloadLayerException {
1630
        this.setAvailable(true);
1631
        super.reload();
1632
//        try {
1633
//            this.source.getDriver().reload();
1634
//            if (this.getLegend() == null) {
1635
//                if (this.getRecordset().getDriver() instanceof WithDefaultLegend) {
1636
//                    WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset().getDriver();
1637
//                    this.setLegend((IVectorLegend) aux.getDefaultLegend());
1638
//                    this.setLabelingStrategy(aux.getDefaultLabelingStrategy());
1639
//                } else {
1640
//                    this.setLegend(LegendFactory.createSingleSymbolLegend(
1641
//                            this.getShapeType()));
1642
//                }
1643
//            }
1644
//
1645
//        } catch (LegendLayerException e) {
1646
//            this.setAvailable(false);
1647
//            throw new ReloadLayerException(getName(),e);
1648
//        } catch (ReadException e) {
1649
//            this.setAvailable(false);
1650
//            throw new ReloadLayerException(getName(),e);
1651
//        }
1652

    
1653
    }
1654

    
1655
    protected void setLoadSelection(XMLEntity xml) {
1656
        this.loadSelection = xml;
1657
    }
1658

    
1659
    protected void setLoadLegend(IVectorLegend legend) {
1660
        this.loadLegend = legend;
1661
    }
1662

    
1663
    protected void putLoadSelection() throws XMLException {
1664
//        if (this.loadSelection == null) return;
1665
//        try {
1666
//            this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
1667
//        } catch (ReadDriverException e) {
1668
//            throw new XMLException(e);
1669
//        }
1670
//        this.loadSelection = null;
1671

    
1672
    }
1673
    protected void putLoadLegend() throws LegendLayerException {
1674
        if (this.loadLegend == null) {
1675
                        return;
1676
                }
1677
        this.setLegend(this.loadLegend);
1678
        this.loadLegend = null;
1679
    }
1680

    
1681
    protected void cleanLoadOptions() {
1682
        this.loadLegend = null;
1683
        this.loadSelection = null;
1684
    }
1685

    
1686
    public boolean isWritable() {
1687
        return getDataStore().isEditable();
1688
//            VectorialDriver drv = getSource().getDriver();
1689
//        if (!drv.isWritable())
1690
//            return false;
1691
//        if (drv instanceof IWriteable)
1692
//        {
1693
//            IWriter writer = ((IWriteable)drv).getWriter();
1694
//            if (writer != null)
1695
//            {
1696
//                if (writer instanceof ISpatialWriter)
1697
//                    return true;
1698
//            }
1699
//        }
1700
//        return false;
1701

    
1702
    }
1703

    
1704
    public FLayer cloneLayer() throws Exception {
1705
        FLyrVect clonedLayer = new FLyrVect();
1706
        clonedLayer.setDataStore(getDataStore());
1707
        if (isJoined()) {
1708
                        clonedLayer.setIsJoined(true);
1709
//                        clonedLayer.setRecordset(getRecordset());
1710
                }
1711
        clonedLayer.setVisible(isVisible());
1712
//        clonedLayer.setISpatialIndex(getISpatialIndex());
1713
        clonedLayer.setName(getName());
1714
        clonedLayer.setCoordTrans(getCoordTrans());
1715

    
1716
        clonedLayer.setLegend((IVectorLegend)getLegend().cloneLegend());
1717

    
1718
        clonedLayer.setIsLabeled(isLabeled());
1719
        clonedLayer.setLabelingStrategy(getLabelingStrategy());
1720

    
1721
        return clonedLayer;
1722
    }
1723

    
1724

    
1725
    private boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, double dpi, CartographicSupport csSym, Geometry geom, int[] xyCoords) {
1726
            return isOnePoint(graphicsTransform, viewPort, geom, xyCoords) && csSym.getCartographicSize(viewPort, dpi, null) <= 1;
1727
    }
1728

    
1729
    private boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, Geometry geom, int[] xyCoords) {
1730
            boolean onePoint = false;
1731
            int type=geom.getType() % Geometry.TYPES.Z;
1732
            if (type!=Geometry.TYPES.POINT && type!=Geometry.TYPES.MULTIPOINT) {
1733

    
1734
                        Rectangle2D geomBounds = geom.getBounds2D();
1735

    
1736
                        ICoordTrans ct = getCoordTrans();
1737

    
1738
                        if (ct!=null) {
1739
//                                geomBounds = ct.getInverted().convert(geomBounds);
1740
                                geomBounds = ct.convert(geomBounds);
1741
                        }
1742

    
1743
                        double dist1Pixel = viewPort.getDist1pixel();
1744

    
1745
                        onePoint = (geomBounds.getWidth()  <= dist1Pixel
1746
                                         && geomBounds.getHeight() <= dist1Pixel);
1747

    
1748
                        if (onePoint) {
1749
                                // avoid out of range exceptions
1750
                                org.gvsig.fmap.geom.primitive.Point2D p = new org.gvsig.fmap.geom.primitive.Point2D(geomBounds.getMinX(), geomBounds.getMinY());
1751
                                p.transform(viewPort.getAffineTransform());
1752
                                p.transform(graphicsTransform);
1753
                                xyCoords[0] = (int) p.getX();
1754
                                xyCoords[1] = (int) p.getY();
1755

    
1756
                        }
1757

    
1758
                }
1759
            return onePoint;
1760
    }
1761
    /*
1762
     * jaume. Stuff from ILabeled.
1763
     */
1764
    private boolean isLabeled;
1765
    protected ILabelingStrategy strategy;
1766

    
1767
    public boolean isLabeled() {
1768
        return isLabeled;
1769
    }
1770

    
1771
    public void setIsLabeled(boolean isLabeled) {
1772
        this.isLabeled = isLabeled;
1773
    }
1774

    
1775
    public ILabelingStrategy getLabelingStrategy() {
1776
        return strategy;
1777
    }
1778

    
1779
    public void setLabelingStrategy(ILabelingStrategy strategy) {
1780
        this.strategy = strategy;
1781
    }
1782

    
1783
    public void drawLabels(BufferedImage image, Graphics2D g, ViewPort viewPort,
1784
                    Cancellable cancel, double scale, double dpi) throws ReadException {
1785
        if (strategy!=null && isWithinScale(scale)) {
1786
                strategy.draw(image, g, viewPort, cancel, dpi);
1787
        }
1788
    }
1789

    
1790

    
1791

    
1792
    //M?todos para el uso de HyperLinks en capas FLyerVect
1793

    
1794
    /**
1795
     * Return true, because a Vectorial Layer supports HyperLink
1796
     */
1797
    public boolean allowLinks()
1798
    {
1799
            return true;
1800
    }
1801

    
1802
    /**
1803
         * Returns an instance of AbstractLinkProperties that contains the information
1804
         * of the HyperLink
1805
         * @return Abstra
1806
         */
1807
    public AbstractLinkProperties getLinkProperties()
1808
    {
1809
            return linkProperties;
1810
    }
1811

    
1812
    /**
1813
         * Provides an array with URIs. Returns one URI by geometry that includes the point
1814
         * in its own geometry limits with a allowed tolerance.
1815
         * @param layer, the layer
1816
         * @param point, the point to check that is contained or not in the geometries in the layer
1817
         * @param tolerance, the tolerance allowed. Allowed margin of error to detect if the  point
1818
         *                 is contained in some geometries of the layer
1819
         * @return
1820
     * @throws ReadException
1821
     * @throws BehaviorException
1822
         */
1823
    public URI[] getLink(Point2D point, double tolerance) throws ReadException
1824
    {
1825
            //return linkProperties.getLink(this)
1826
            return linkProperties.getLink(this,point,tolerance);
1827
    }
1828
//    /**
1829
//     * @deprecated Don?t use Strategy, you should be use iterators.
1830
//     */
1831
//        public boolean isUseStrategy() {
1832
//                return useStrategy;
1833
//        }
1834
//        /**
1835
//     * @deprecated Don?t use Strategy, you should be use iterators.
1836
//     */
1837
//        public void setUseStrategy(boolean useStrategy) {
1838
//                this.useStrategy = useStrategy;
1839
//        }
1840

    
1841
        public void load() throws LoadLayerException {
1842
                super.load();
1843
//                useStrategy=forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD;
1844
        }
1845

    
1846
        public FeatureStore getFeatureStore() throws ReadException {
1847
                return (FeatureStore)getDataStore();
1848
        }
1849

    
1850
        public FeatureCollection queryByPoint(Point2D mapPoint, double tol) throws ReadException {
1851
//                double halfTol=tol*0.5;
1852
//                Envelope envelope=new DefaultEnvelope(mapPoint.getX()-halfTol,mapPoint.getY()-halfTol,mapPoint.getX()+halfTol,mapPoint.getY()+halfTol);
1853
//                return queryByEnvelope(envelope);
1854
                Geometry geom = GeometryManager.getInstance().getGeometryFactory()
1855
                                .createCircle(mapPoint, tol);
1856

    
1857
                return queryByGeometry(geom);
1858
        }
1859

    
1860

    
1861
        public FeatureCollection queryByGeometry(Geometry geom) throws ReadException {
1862
                try {
1863
                        return (FeatureCollection)
1864
                                getFeatureStore().getDataCollection(
1865
                                        getFeatureStore().getDefaultFeatureType(),
1866
                                        getDataStoreFilterForGeomerty(
1867
                                                        geom,
1868
                                                        getFeatureStore().getDefaultFeatureType().getDefaultGeometry(),
1869
                                                        null),
1870
                                        null);
1871
                } catch (GeometryOperationNotSupportedException e) {
1872
                        throw new ReadException("queryByGeometry", e);
1873
                } catch (GeometryOperationException e) {
1874
                        throw new ReadException("queryByGeometry", e);
1875
                }
1876

    
1877
        }
1878

    
1879
        protected String getDataStoreFilterForGeomerty(Geometry geom,
1880
                        String geomFileName, String srs) throws ReadException,
1881
                        GeometryOperationException,
1882
                        GeometryOperationNotSupportedException {
1883
                String txtGeom;
1884

    
1885
                txtGeom = (String) geom.invokeOperation(ToWKT.CODE, null);
1886

    
1887
                if (srs == null) {
1888
                        try {
1889
                                srs = (String) getFeatureStore().getMetadata().get("srs");
1890
                        } catch (BaseException e) {
1891
                                throw new ReadException("getDataStoreFilterForGeomerty", e);
1892
                        }
1893
                }
1894

    
1895

    
1896
                return " intersects(GeomFromText('" + txtGeom + "', " + "'" + srs + "'"
1897
                                + "), " + geomFileName + ") ";
1898
        }
1899

    
1900
        public FeatureCollection queryByEnvelope(Envelope rect)
1901
                        throws ReadException {
1902
                return this.queryByGeometry(rect.getGeometry());
1903
        }
1904

    
1905
        public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadException, LoadLayerException {
1906
                Point2D pReal = this.getMapContext().getViewPort().toMapPoint(p);
1907
        FeatureCollection featureCollection = queryByPoint(pReal, tolerance);
1908
        VectorialXMLItem[] item = new VectorialXMLItem[1];
1909
        item[0] = new VectorialXMLItem(featureCollection, this);
1910

    
1911
        return item;
1912
        }
1913
 }