Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / FLyrVect.java @ 28544

History | View | Annotate | Download (67.7 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 com.iver.cit.gvsig.fmap.layers;
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.io.File;
50
import java.net.URI;
51
import java.util.ArrayList;
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

    
60
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
61
import com.hardcode.gdbms.engine.data.DataSourceFactory;
62
import com.hardcode.gdbms.engine.data.NoSuchTableException;
63
import com.hardcode.gdbms.engine.data.driver.DriverException;
64
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
65
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
66
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
67
import com.iver.cit.gvsig.exceptions.layers.ReloadLayerException;
68
import com.iver.cit.gvsig.exceptions.layers.ReprojectLayerException;
69
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
70
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException;
71
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
72
import com.iver.cit.gvsig.fmap.MapContext;
73
import com.iver.cit.gvsig.fmap.MapControl;
74
import com.iver.cit.gvsig.fmap.ViewPort;
75
import com.iver.cit.gvsig.fmap.core.CartographicSupport;
76
import com.iver.cit.gvsig.fmap.core.FPoint2D;
77
import com.iver.cit.gvsig.fmap.core.FShape;
78
import com.iver.cit.gvsig.fmap.core.IFeature;
79
import com.iver.cit.gvsig.fmap.core.IGeometry;
80
import com.iver.cit.gvsig.fmap.core.ILabelable;
81
import com.iver.cit.gvsig.fmap.core.IRow;
82
import com.iver.cit.gvsig.fmap.core.symbols.IMultiLayerSymbol;
83
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
84
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
85
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
86
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
87
import com.iver.cit.gvsig.fmap.drivers.IVectorialDatabaseDriver;
88
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
89
import com.iver.cit.gvsig.fmap.drivers.WithDefaultLegend;
90
import com.iver.cit.gvsig.fmap.edition.AfterFieldEditEvent;
91
import com.iver.cit.gvsig.fmap.edition.AfterRowEditEvent;
92
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
93
import com.iver.cit.gvsig.fmap.edition.BeforeFieldEditEvent;
94
import com.iver.cit.gvsig.fmap.edition.BeforeRowEditEvent;
95
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
96
import com.iver.cit.gvsig.fmap.edition.IEditionListener;
97
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
98
import com.iver.cit.gvsig.fmap.edition.IWriteable;
99
import com.iver.cit.gvsig.fmap.edition.IWriter;
100
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
101
import com.iver.cit.gvsig.fmap.edition.VectorialEditableDBAdapter;
102
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
103
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
104
import com.iver.cit.gvsig.fmap.layers.layerOperations.InfoByPoint;
105
import com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData;
106
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
107
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialData;
108
import com.iver.cit.gvsig.fmap.layers.layerOperations.VectorialXMLItem;
109
import com.iver.cit.gvsig.fmap.layers.layerOperations.XMLItem;
110
import com.iver.cit.gvsig.fmap.operations.strategies.FeatureVisitor;
111
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
112
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
113
import com.iver.cit.gvsig.fmap.rendering.IClassifiedVectorLegend;
114
import com.iver.cit.gvsig.fmap.rendering.ILegend;
115
import com.iver.cit.gvsig.fmap.rendering.IVectorLegend;
116
import com.iver.cit.gvsig.fmap.rendering.LegendClearEvent;
117
import com.iver.cit.gvsig.fmap.rendering.LegendContentsChangedListener;
118
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
119
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
120
import com.iver.cit.gvsig.fmap.rendering.SymbolLegendEvent;
121
import com.iver.cit.gvsig.fmap.rendering.ZSort;
122
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.AttrInTableLabelingStrategy;
123
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.ILabelingStrategy;
124
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.LabelClass;
125
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.LabelingFactory;
126
import com.iver.cit.gvsig.fmap.spatialindex.IPersistentSpatialIndex;
127
import com.iver.cit.gvsig.fmap.spatialindex.ISpatialIndex;
128
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeGt2;
129
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
130
import com.iver.cit.gvsig.fmap.spatialindex.SpatialIndexException;
131
import com.iver.utiles.FileUtils;
132
import com.iver.utiles.IPersistence;
133
import com.iver.utiles.NotExistInXMLEntity;
134
import com.iver.utiles.PostProcessSupport;
135
import com.iver.utiles.XMLEntity;
136
import com.iver.utiles.swing.threads.Cancellable;
137
import com.iver.utiles.swing.threads.CancellableMonitorable;
138

    
139
/**
140
 * Capa b?sica Vectorial.
141
 *
142
 * @author Fernando Gonz?lez Cort?s
143
 */
144

    
145
// TODO Cuando no sea para pruebas debe no ser public
146
public class FLyrVect extends FLyrDefault implements ILabelable,
147
        ClassifiableVectorial, SingleLayer, VectorialData, RandomVectorialData,
148
        AlphanumericData, InfoByPoint, SelectionListener, IEditionListener, LegendContentsChangedListener {
149
    private static Logger logger = Logger.getLogger(FLyrVect.class.getName());
150
    /**
151
     * @deprecated Don?t use Strategy, you should be use iterators.
152
     */
153
//    public static boolean forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD = true;
154
    /**
155
     * @deprecated Don?t use Strategy, you should be use iterators.
156
     */
157
//    private boolean useStrategy=false;
158

    
159
    /** Leyenda de la capa vectorial */
160
    private IVectorLegend legend;
161
    private int typeShape = -1;
162
    private ReadableVectorial source;
163
    private SelectableDataSource sds;
164
    private SelectionSupport selectionSupport = new SelectionSupport();
165
    private SpatialCache spatialCache = new SpatialCache();
166
    private boolean spatialCacheEnabled = false;
167

    
168
    /**
169
     * An implementation of gvSIG spatial index
170
     */
171
    protected ISpatialIndex spatialIndex = null;
172
    private boolean bHasJoin = false;
173
    private XMLEntity orgXMLEntity = null;
174
    private XMLEntity loadSelection = null;
175
    private IVectorLegend loadLegend = null;
176

    
177
    //Lo a?ado. Caracter?sticas de HyperEnlace (LINK)
178
    private FLyrVectLinkProperties linkProperties=new FLyrVectLinkProperties();
179
    //private ArrayList linkProperties=null;
180

    
181
    /**
182
     * Devuelve el VectorialAdapater de la capa.
183
     *
184
     * @return VectorialAdapter.
185
     */
186
    public ReadableVectorial getSource() {
187
        if (!this.isAvailable()) return null;
188
        return source;
189
    }
190

    
191
    /**
192
     * If we use a persistent spatial index associated with this layer, and the
193
     * index is not intrisic to the layer (for example spatial databases) this
194
     * method looks for existent spatial index, and loads it.
195
     *
196
     */
197
    private void loadSpatialIndex() {
198
        //FIXME: Al abrir el indice en fichero...
199
        //?C?mo lo liberamos? un metodo Layer.shutdown()
200

    
201

    
202
        ReadableVectorial source = getSource();
203
        //REVISAR QUE PASA CON LOS DRIVERS DXF, DGN, etc.
204
        //PUES SON VECTORIALFILEADAPTER
205
        if (!(source instanceof VectorialFileAdapter)) {
206
            // we are not interested in db adapters
207
            return;
208
        }
209
        VectorialDriver driver = source.getDriver();
210
        if (!(driver instanceof BoundedShapes)) {
211
            // we dont spatially index layers that are not bounded
212
            return;
213
        }
214
        File file = ((VectorialFileAdapter) source).getFile();
215
        String fileName = file.getAbsolutePath();
216
        File sptFile = new File(fileName + ".qix");
217
        if (!sptFile.exists() || (!(sptFile.length() > 0))) {
218
            // before to exit, look for it in temp path
219
            String tempPath = System.getProperty("java.io.tmpdir");
220
            fileName = tempPath + File.separator + sptFile.getName();
221
            sptFile = new File(fileName);
222
            // it doesnt exists, must to create
223
            if (!sptFile.exists() || (!(sptFile.length() > 0))) {
224
                return;
225
            }// if
226
        }// if
227

    
228
        try {
229
            source.start();
230
            spatialIndex = new QuadtreeGt2(FileUtils.getFileWithoutExtension(sptFile),
231
                    "NM", source.getFullExtent(), source.getShapeCount(), false);
232
            source.setSpatialIndex(spatialIndex);
233
        } catch (SpatialIndexException e) {
234
            spatialIndex = null;
235
            e.printStackTrace();
236
            return;
237
        } catch (ReadDriverException e) {
238
            spatialIndex = null;
239
            e.printStackTrace();
240
            return;
241
        }
242

    
243
    }
244

    
245
    /**
246
     * Checks if it has associated an external spatial index
247
     * (an spatial index file).
248
     *
249
     * It looks for it in main file path, or in temp system path.
250
     * If main file is rivers.shp, it looks for a file called
251
     * rivers.shp.qix.
252

253
     * @return
254
     */
255
    public boolean isExternallySpatiallyIndexed() {
256
        /*
257
         * FIXME (AZABALA): Independizar del tipo de fichero de ?ndice
258
          * con el que se trabaje (ahora mismo considera la extension .qix,
259
         * pero esto depender? del tipo de ?ndice)
260
         * */
261
        ReadableVectorial source = getSource();
262
        if (!(source instanceof VectorialFileAdapter)) {
263
            // we are not interested in db adapters.
264
            // think in non spatial dbs, like HSQLDB
265
            return false;
266
        }
267
        File file = ((VectorialFileAdapter) source).getFile();
268
        String fileName = file.getAbsolutePath();
269
        File sptFile = new File(fileName + ".qix");
270
        if (!sptFile.exists() || (!(sptFile.length() > 0))) {
271
            // before to exit, look for it in temp path
272
            // it doesnt exists, must to create
273
            String tempPath = System.getProperty("java.io.tmpdir");
274
            fileName = tempPath + File.separator + sptFile.getName();
275
            sptFile = new File(fileName);
276
            if (!sptFile.exists() || (!(sptFile.length() > 0))) {
277
                return false;
278
            }// if
279
        }// if
280
        return true;
281
    }
282

    
283
    /**
284
     * Inserta el VectorialAdapter a la capa.
285
     *
286
     * @param va
287
     *            VectorialAdapter.
288
     */
289
    public void setSource(ReadableVectorial rv) {
290
        source = rv;
291
        // azabala: we check if this layer could have a file spatial index
292
        // and load it if it exists
293
        loadSpatialIndex();
294
    }
295

    
296
    public Rectangle2D getFullExtent() throws ReadDriverException, ExpansionFileReadException {
297
            Rectangle2D rAux;
298
            source.start();
299
            rAux = (Rectangle2D)source.getFullExtent().clone();
300
            source.stop();
301

    
302
            // Si existe reproyecci?n, reproyectar el extent
303
            ICoordTrans ct = getCoordTrans();
304
                        try{
305
                    if (ct != null) {
306
                        Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
307
                        Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
308
                        pt1 = ct.convert(pt1, null);
309
                        pt2 = ct.convert(pt2, null);
310
                        rAux = new Rectangle2D.Double();
311
                        rAux.setFrameFromDiagonal(pt1, pt2);
312
                    }
313
                        }catch (IllegalStateException e) {
314
                                this.setAvailable(false);
315
                                this.addError(new ReprojectLayerException(getName(), e));
316
                        }
317
            //Esto es para cuando se crea una capa nueva con el fullExtent de ancho y alto 0.
318
            if (rAux.getWidth()==0 && rAux.getHeight()==0) {
319
                rAux=new Rectangle2D.Double(0,0,100,100);
320
            }
321

    
322
            return rAux;
323
    }
324

    
325
    /**
326
     * Draws using IFeatureIterator. This method will replace the old draw(...) one.
327
     * @autor jaume dominguez faus - jaume.dominguez@iver.es
328
     * @param image
329
     * @param g
330
     * @param viewPort
331
     * @param cancel
332
     * @param scale
333
     * @throws ReadDriverException
334
     */
335
    private void _draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
336
                    Cancellable cancel, double scale) throws ReadDriverException {
337
            boolean bDrawShapes = true;
338
            if (legend instanceof SingleSymbolLegend) {
339
                    bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
340
            }
341
            Point2D offset = viewPort.getOffset();
342
            double dpi = MapContext.getScreenDPI();
343

    
344

    
345

    
346
            if (bDrawShapes) {
347
                    boolean cacheFeatures = isSpatialCacheEnabled();
348
                    SpatialCache cache = null;
349
                    if (cacheFeatures) {
350
                            getSpatialCache().clearAll();
351
                            cache = getSpatialCache();
352
                    }
353

    
354
                    try {
355
                            ArrayList<String> fieldList = new ArrayList<String>();
356

    
357
                            // fields from legend
358
                            String[] aux = null;
359

    
360
                            if (legend instanceof IClassifiedVectorLegend) {
361
                                    aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames();
362
                                    if (aux!=null)
363
                                            for (int i = 0; i < aux.length; i++) {
364
                                                    fieldList.add(aux[i]);
365
                                            }
366
                            }
367

    
368
                            // Get the iterator over the visible features
369
                            IFeatureIterator it = getSource().getFeatureIterator(
370
                                            viewPort.getAdjustedExtent(),
371
                                            fieldList.toArray(new String[fieldList.size()]),
372
                                            viewPort.getProjection(),
373
                                            true);
374

    
375
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
376

    
377
                            boolean bSymbolLevelError = false;
378

    
379
                            // if layer has map levels it will use a ZSort
380
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
381

    
382
                            // -- visual FX stuff
383
                            long time = System.currentTimeMillis();
384
                            BufferedImage virtualBim;
385
                            Graphics2D virtualGraphics;
386

    
387
                            // render temporary map each screenRefreshRate milliseconds;
388
                            int screenRefreshDelay = (int) ((1D/MapControl.getDrawFrameRate())*3*1000);
389
                            BufferedImage[] imageLevels = null;
390
                            Graphics2D[] graphics = null;
391
                            if (useZSort) {
392
                                    imageLevels = new BufferedImage[zSort.getLevelCount()];
393
                                    graphics = new Graphics2D[imageLevels.length];
394
                                    for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
395
                                            imageLevels[i] = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
396
                                            graphics[i] = imageLevels[i].createGraphics();
397
                                            graphics[i].setTransform(g.getTransform());
398
                                            graphics[i].setRenderingHints(g.getRenderingHints());
399
                                    }
400
                            }
401
                            // -- end visual FX stuff
402

    
403

    
404
                            // Iteration over each feature
405
                            while ( !cancel.isCanceled() && it.hasNext()) {
406
                                    IFeature feat = it.next();
407
                                    IGeometry geom = feat.getGeometry();
408

    
409
                                    if (cacheFeatures) {
410
                                            if (cache.getMaxFeatures() >= cache.size()) {
411
                                                    // already reprojected
412
                                                    cache.insert(geom.getBounds2D(), geom);
413
                                            }
414
                                    }
415

    
416
                                    // retrieve the symbol associated to such feature
417
                                    ISymbol sym = legend.getSymbolByFeature(feat);
418

    
419
                                    if (sym == null) continue;
420

    
421
                                    //C?digo para poder acceder a los ?ndices para ver si est? seleccionado un Feature
422
                                    ReadableVectorial rv=getSource();
423
                                    int selectionIndex=-1;
424
                                    if (rv instanceof ISpatialDB){
425
                                            selectionIndex = ((ISpatialDB)rv).getRowIndexByFID(feat);
426
                                    }else{
427
                                            selectionIndex = Integer.parseInt(feat.getID());
428
                                    }
429
                                    if (selectionIndex!=-1) {
430
                                            if (selectionSupport.isSelected(selectionIndex)) {
431
                                                    sym = sym.getSymbolForSelection();
432
                                            }
433
                                    }
434

    
435
                                    // Check if this symbol is sized with CartographicSupport
436
                                    CartographicSupport csSym = null;
437
                                    int symbolType = sym.getSymbolType();
438
                                    boolean bDrawCartographicSupport = false;
439

    
440
                                    if (   symbolType == FShape.POINT
441
                                                    || symbolType == FShape.LINE
442
                                                    || sym instanceof CartographicSupport) {
443

    
444
                                            // patch
445
                                            if (!sym.getClass().equals(FSymbol.class)) {
446
                                                    csSym = (CartographicSupport) sym;
447
                                                    bDrawCartographicSupport = (csSym.getUnit() != -1);
448
                                            }
449
                                    }
450

    
451
                                    int x = -1;
452
                                    int y = -1;
453
                                    int[] xyCoords = new int[2];
454

    
455
                                    // Check if size is a pixel
456
                                    boolean onePoint = bDrawCartographicSupport ?
457
                                                    isOnePoint(g.getTransform(), viewPort, MapContext.getScreenDPI(), csSym, geom, xyCoords) :
458
                                                            isOnePoint(g.getTransform(), viewPort, geom, xyCoords);
459

    
460
                                                    // Avoid out of bounds exceptions
461
                                                    if (onePoint) {
462
                                                            x = xyCoords[0];
463
                                                            y = xyCoords[1];
464
                                                            if (x<0 || y<0 || x>= viewPort.getImageWidth() || y>=viewPort.getImageHeight()) continue;
465
                                                    }
466

    
467
                                                    if (useZSort) {
468
                                                            // Check if this symbol is a multilayer
469
                                                                int[] symLevels = zSort.getLevels(sym);
470
                                                            if (sym instanceof IMultiLayerSymbol) {
471
                                                                    // if so, treat each of its layers as a single symbol
472
                                                                    // in its corresponding map level
473
                                                                    IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
474
                                                                    for (int i = 0; !cancel.isCanceled() && i < mlSym.getLayerCount(); i++) {
475
                                                                            ISymbol mySym = mlSym.getLayer(i);
476
                                                                        int symbolLevel = 0;
477
                                                                        if (symLevels != null) {
478
                                                                                symbolLevel = symLevels[i];
479
                                                                        } else {
480
                                                                                    /* an error occured when managing symbol levels.
481
                                                                                     * some of the legend changed events regarding the
482
                                                                                     * symbols did not finish satisfactory and the legend
483
                                                                                     * is now inconsistent. For this drawing, it will finish
484
                                                                                     * as it was at the bottom (level 0) but, when done, the
485
                                                                                     * ZSort will be reset to avoid app crashes. This is
486
                                                                                     * a bug that has to be fixed.
487
                                                                                     */
488
                                                                                    bSymbolLevelError = true;
489
                                                                            }
490

    
491
                                                                            if (onePoint) {
492
                                                                                    if (x<0 || y<0 || x>= imageLevels[symbolLevel].getWidth() || y>=imageLevels[symbolLevel].getHeight()) continue;
493
                                                                                    imageLevels[symbolLevel].setRGB(x, y, mySym.getOnePointRgb());
494
                                                                            } else {
495
                                                                                    if (!bDrawCartographicSupport) {
496
                                                                                            geom.drawInts(graphics[symbolLevel], viewPort, mySym, cancel);
497
                                                                                    } else {
498
                                                                                            geom.drawInts(graphics[symbolLevel], viewPort, dpi, (CartographicSupport) mySym, cancel);
499
                                                                                    }
500
                                                                            }
501
                                                                    }
502
                                                            } else {
503
                                                                    // else, just draw the symbol in its level
504
                                                                    int symbolLevel = 0;
505
                                                                    if (symLevels != null) {
506

    
507
                                                                            symbolLevel=symLevels[0];
508
                                                                    } else {
509
                                                                            /* If symLevels == null
510
                                                                             * an error occured when managing symbol levels.
511
                                                                             * some of the legend changed events regarding the
512
                                                                             * symbols did not finish satisfactory and the legend
513
                                                                             * is now inconsistent. For this drawing, it will finish
514
                                                                             * as it was at the bottom (level 0). This is
515
                                                                             * a bug that has to be fixed.
516
                                                                             */
517
//                                                                            bSymbolLevelError = true;
518
                                                                    }
519

    
520
                                                                    if (!bDrawCartographicSupport) {
521
                                                                            geom.drawInts(graphics[symbolLevel], viewPort, sym, cancel);
522
                                                                    } else {
523
                                                                            geom.drawInts(graphics[symbolLevel], viewPort, dpi, (CartographicSupport) csSym, cancel);
524
                                                                    }
525
                                                            }
526

    
527
                                                            // -- visual FX stuff
528
                                                            // Cuando el offset!=0 se est? dibujando sobre el Layout y por tanto no tiene que ejecutar el siguiente c?digo.
529
                                                            if (offset.getX()==0 && offset.getY()==0)
530
                                                                    if ((System.currentTimeMillis() - time) > screenRefreshDelay) {
531
                                                                            virtualBim = new BufferedImage(image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB);
532
                                                                            virtualGraphics = virtualBim.createGraphics();
533
                                                                            virtualGraphics.drawImage(image,0,0, null);
534
                                                                            for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
535
                                                                                    virtualGraphics.drawImage(imageLevels[i],0,0, null);
536
                                                                            }
537
                                                                            g.clearRect(0, 0, image.getWidth(), image.getHeight());
538
                                                                            g.drawImage(virtualBim, 0, 0, null);
539
                                                                            time = System.currentTimeMillis();
540
                                                                    }
541
                                                            // -- end visual FX stuff
542

    
543
                                                    } else {
544
                                                            // no ZSort, so there is only a map level, symbols are
545
                                                            // just drawn.
546
                                                            if (onePoint) {
547
                                                                    if (x<0 || y<0 || x>= image.getWidth() || y>=image.getHeight()) continue;
548
                                                                    image.setRGB(x, y, sym.getOnePointRgb());
549
                                                            } else {
550
                                                                    if (!bDrawCartographicSupport) {
551
                                                                            geom.drawInts(g, viewPort, sym, cancel);
552
                                                                    } else {
553
                                                                            geom.drawInts(g, viewPort, dpi, csSym, cancel);
554
                                                                    }
555
                                                            }
556
                                                    }
557
                            }
558

    
559
                            if (useZSort) {
560
                                    g.drawImage(image, 0, 0, null);
561
                                    g.translate(offset.getX(), offset.getY());
562
                                    for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
563
                                            g.drawImage(imageLevels[i],0,0, null);
564
                                            imageLevels[i] = null;
565
                                            graphics[i] = null;
566
                                    }
567
                                    g.translate(-offset.getX(), -offset.getY());
568
                                    imageLevels = null;
569
                                    graphics = null;
570
                            }
571
                            it.closeIterator();
572

    
573
                            if (bSymbolLevelError) {
574
                                    ((IVectorLegend) getLegend()).setZSort(null);
575
                            }
576

    
577
                    } catch (ReadDriverException e) {
578
                            this.setVisible(false);
579
                            this.setActive(false);
580
                            throw e;
581
                    }
582

    
583

    
584
            }
585
    }
586

    
587
           public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
588
            Cancellable cancel, double scale) throws ReadDriverException {
589
//            forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD = true;
590
//            if (!isUseStrategy()) {
591
                    _draw(image, g, viewPort, cancel, scale);
592
//            } else {
593
////                    moved up to FLayers
594
////                    if (isWithinScale(scale)) {
595
//
596
//
597
//                            // Las que solo tienen etiquetado sin pintar el shape,
598
//                            // no pasamos por ellas
599
//                            boolean bDrawShapes = true;
600
//                            if (legend instanceof SingleSymbolLegend) {
601
//                                    if (legend.getDefaultSymbol().isShapeVisible() == false)
602
//                                            bDrawShapes = false;
603
//                            }
604
//                            if (bDrawShapes) {
605
//                                    Strategy strategy = StrategyManager.getStrategy(this);
606
//                                    try {
607
//                                            prepareDrawing(image, g, viewPort);
608
//                                            strategy.draw(image, g, viewPort, cancel);
609
//                                    } catch (ReadDriverException e) {
610
//                                            this.setVisible(false);
611
//                                            this.setActive(false);
612
//                                            throw e;
613
//                                    }
614
//                            }
615
//                            if (getVirtualLayers() != null) {
616
//                                    getVirtualLayers().draw(image, g, viewPort, cancel, scale);
617
//                            }
618
////                    }
619
//            }
620
    }
621

    
622
    /**
623
     * Se llama antes de empezar a pintar.
624
     * Es ?til para preparar la cache a emplear, las leyendas, etc.
625
     * @param image
626
     * @param g
627
     * @param viewPort
628
     */
629
    private void prepareDrawing(BufferedImage image, Graphics2D g, ViewPort viewPort) {
630

    
631
    }
632

    
633
    public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
634
                    double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
635
            // TEST METHOD
636

    
637

    
638
                    /* SVN */
639

    
640
    /*        boolean bDrawShapes = true;
641
            if (legend instanceof SingleSymbolLegend) {
642
                    bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
643
            }
644

645

646
            if (bDrawShapes) {
647
                    double dpi = 72;
648

649
                    PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
650
                    if (resolution.equals(PrintQuality.NORMAL)){
651
                            dpi = 300;
652
                    } else if (resolution.equals(PrintQuality.HIGH)){
653
                            dpi = 600;
654
                    } else if (resolution.equals(PrintQuality.DRAFT)){
655
                            dpi = 72;
656
                    }
657

658

659
                    try {
660
                            prepareDrawing(null, g, viewPort);
661
                            ArrayList<String> fieldList = new ArrayList<String>();
662
                            String[] aux;
663

664
                            // fields from legend
665
                            if (legend instanceof IClassifiedVectorLegend) {
666
                                    aux = ((IClassifiedVectorLegend) legend).
667
                                                                            getClassifyingFieldNames();
668
                                    for (int i = 0; i < aux.length; i++) {
669
                                            fieldList.add(aux[i]);
670
                                    }
671
                            }
672

673
                            // fields from labeling
674
                            if (isLabeled()) {
675
                                    aux = getLabelingStrategy().getUsedFields();
676
                                    for (int i = 0; i < aux.length; i++) {
677
                                            fieldList.add(aux[i]);
678
                                    }
679
                            }
680

681
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
682

683
                            // if layer has map levels it will use a ZSort
684
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
685

686

687
                            int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
688
                            for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
689
                                    // Get the iterator over the visible features
690
                                    IFeatureIterator it = getSource().getFeatureIterator(
691
                                                    viewPort.getAdjustedExtent(),
692
                                                    fieldList.toArray(new String[fieldList.size()]),
693
                                                    viewPort.getProjection(),
694
                                                    true);
695

696
                                    // Iteration over each feature
697
                                    while ( !cancel.isCanceled() && it.hasNext()) {
698
                                            IFeature feat = it.next();
699
                                            IGeometry geom = feat.getGeometry();
700

701
                                            // retreive the symbol associated to such feature
702
                                            ISymbol sym = legend.getSymbolByFeature(feat);
703

704
                                            if (useZSort) {
705
                                                    // Check if this symbol is a multilayer
706
                                                        if (sym instanceof IMultiLayerSymbol) {
707
                                                                // if so, get the layer corresponding to the current
708
                                                                // level. If none, continue to next iteration
709
                                                                IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
710
                                                                for (int i = 0; i < mlSym.getLayerCount(); i++) {
711
                                                                        ISymbol mySym = mlSym.getLayer(i);
712
                                                                        if (zSort.getSymbolLevel(mySym) == mapPass) {
713
                                                                                sym = mySym;
714
                                                                                break;
715
                                                                        }
716
                                                                        System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")");
717
                                                                }
718

719
                                                                if (sym == null) {
720
                                                                        continue;
721
                                                                }
722
                                                        } else {
723
                                                                // else, just draw the symbol in its level
724
                                                                if (zSort.getSymbolLevel(sym) != mapPass) {
725
                                                                        System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")");
726
                                                                        continue;
727
                                                                }
728
                                                        }
729
                                            }
730

731
                                            // Check if this symbol is sized with CartographicSupport
732
                                            CartographicSupport csSym = null;
733
                                            int symbolType = sym.getSymbolType();
734
                                            boolean bDrawCartographicSupport = false;
735

736
                                            if (   symbolType == FShape.POINT
737
                                                            || symbolType == FShape.LINE
738
                                                            || sym instanceof CartographicSupport) {
739

740
                                                    csSym = (CartographicSupport) sym;
741
                                                    bDrawCartographicSupport = (csSym.getUnit() != -1);
742
                                            }
743

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

746
                                            if (!bDrawCartographicSupport) {
747
                                                    geom.drawInts(g, viewPort, sym, null);
748
                                            } else {
749
                                                    geom.drawInts(g, viewPort, dpi, (CartographicSupport) csSym);
750
                                            }
751

752
                                    }
753
                                    it.closeIterator();
754
                            }
755
                    } catch (ReadDriverException e) {
756
                            this.setVisible(false);
757
                            this.setActive(false);
758
                            throw e;
759
                    }
760
        */
761

    
762

    
763
            // TEST METHOD
764
            boolean bDrawShapes = true;
765
            if (legend instanceof SingleSymbolLegend) {
766
                    bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
767
            }
768

    
769

    
770
            if (bDrawShapes) {
771

    
772
                    try {
773
                            double dpi = 72;
774

    
775
                            PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
776
                            if (resolution.equals(PrintQuality.NORMAL)){
777
                                    dpi = 300;
778
                            } else if (resolution.equals(PrintQuality.HIGH)){
779
                                    dpi = 600;
780
                            } else if (resolution.equals(PrintQuality.DRAFT)){
781
                                    dpi = 72;
782
                            }
783
                            ArrayList<String> fieldList = new ArrayList<String>();
784
                            String[] aux;
785

    
786
                            // fields from legend
787
                            if (legend instanceof IClassifiedVectorLegend) {
788
                                    aux = ((IClassifiedVectorLegend) legend).
789
                                    getClassifyingFieldNames();
790
                                    for (int i = 0; i < aux.length; i++) {
791
                                            fieldList.add(aux[i]);
792
                                    }
793
                            }
794
//
795
//                            // fields from labeling
796
//                            if (isLabeled()) {
797
//                                    aux = getLabelingStrategy().getUsedFields();
798
//                                    for (int i = 0; i < aux.length; i++) {
799
//                                            fieldList.add(aux[i]);
800
//                                    }
801
//                            }
802

    
803
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
804

    
805
                            // if layer has map levels it will use a ZSort
806
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
807

    
808

    
809
                            int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
810
                            for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
811
                                    // Get the iterator over the visible features
812
                                    IFeatureIterator it = getSource().getFeatureIterator(
813
                                                    viewPort.getAdjustedExtent(),
814
                                                    fieldList.toArray(new String[fieldList.size()]),
815
                                                    viewPort.getProjection(),
816
                                                    true);
817

    
818
                                    // Iteration over each feature
819
                                    while ( !cancel.isCanceled() && it.hasNext()) {
820
                                            IFeature feat = it.next();
821
                                            IGeometry geom = feat.getGeometry();
822

    
823
                                            // retreive the symbol associated to such feature
824
                                            ISymbol sym = legend.getSymbolByFeature(feat);
825
                                            if (sym == null) {
826
                                                        continue;
827
                                                }
828
                                            if (useZSort) {
829
                                                        int[] symLevels = zSort.getLevels(sym);
830
                                                        if(symLevels != null){
831
                                                                // Check if this symbol is a multilayer
832
                                                                if (sym instanceof IMultiLayerSymbol) {
833
                                                                        // if so, get the layer corresponding to the current
834
                                                                        // level. If none, continue to next iteration
835
                                                                        IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
836
                                                                        for (int i = 0; i < mlSym.getLayerCount(); i++) {
837
                                                                                ISymbol mySym = mlSym.getLayer(i);
838
                                                                                if (symLevels[i] == mapPass) {
839
                                                                                        sym = mySym;
840
                                                                                        break;
841
                                                                                }
842
                                                                                System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")");
843
                                                                        }
844
                                                                } else {
845
                                                                        // else, just draw the symbol in its level
846
                                                                        if (symLevels[0] != mapPass) {
847
                                                                                System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")");
848
                                                                                continue;
849
                                                                        }
850
                                                                }
851
                                                        }
852
                                            }
853

    
854
                                            // Check if this symbol is sized with CartographicSupport
855
                                            CartographicSupport csSym = null;
856
                                            int symbolType = sym.getSymbolType();
857

    
858
                                            if (   symbolType == FShape.POINT
859
                                                            || symbolType == FShape.LINE
860
                                                            || sym instanceof CartographicSupport) {
861

    
862
                                                    csSym = (CartographicSupport) sym;
863
                                            }
864

    
865
//                                            System.err.println("passada "+mapPass+" pinte s?mboll "+sym.getDescription());
866

    
867
                                            if (csSym == null) {
868
                                                    geom.drawInts(g, viewPort, sym, null);
869
                                            } else {
870
                                                    geom.drawInts(g, viewPort, dpi, (CartographicSupport) csSym, cancel);
871
                                            }
872

    
873
                                    }
874
                                    it.closeIterator();
875
                            }
876
                    } catch (ReadDriverException e) {
877
                            this.setVisible(false);
878
                            this.setActive(false);
879
                            throw e;
880
                    }
881
            }
882
    }
883

    
884

    
885
    public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
886
            double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
887
//            if (forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD) {
888
                    _print(g, viewPort, cancel, scale, properties);
889
//            } else {
890
////                    moved up to Flayers
891
////                    if (isVisible() && isWithinScale(scale)) {
892
//                            Strategy strategy = StrategyManager.getStrategy(this);
893
//
894
//                            strategy.print(g, viewPort, cancel, properties);
895
//                            ILabelingStrategy labeling;
896
//                            if ( (labeling = getLabelingStrategy() ) != null) {
897
//                                    // contains labels
898
//                                    labeling.print(g, viewPort, cancel, properties);
899
//                            }
900
////                    }
901
//            }
902
    }
903

    
904
    public void deleteSpatialIndex() {
905
        //must we delete possible spatial indexes files?
906
        spatialIndex = null;
907
    }
908

    
909
   /**
910
    * <p>
911
    * Creates an spatial index associated to this layer.
912
    * The spatial index will used
913
    * the native projection of the layer, so if the layer is reprojected, it will
914
    * be ignored.
915
    * </p>
916
    * @param cancelMonitor instance of CancellableMonitorable that allows
917
    * to monitor progress of spatial index creation, and cancel the process
918
    */
919
    public void createSpatialIndex(CancellableMonitorable cancelMonitor){
920
         // FJP: ESTO HABR? QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
921
        // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
922
        // para que acepten recorrer sin geometria, solo con rectangulos.
923

    
924
        //If this vectorial layer is based in a spatial database, the spatial
925
        //index is already implicit. We only will index file drivers
926
        ReadableVectorial va = getSource();
927
        //We must think in non spatial databases, like HSQLDB
928
        if(!(va instanceof VectorialFileAdapter)){
929
            return;
930
        }
931
        if (!(va.getDriver() instanceof BoundedShapes)) {
932
            return;
933
        }
934
        File file = ((VectorialFileAdapter) va).getFile();
935
        String fileName = file.getAbsolutePath();
936
        ISpatialIndex localCopy = null;
937
        try {
938
            va.start();
939
            localCopy = new QuadtreeGt2(fileName, "NM", va.getFullExtent(),
940
                    va.getShapeCount(), true);
941

    
942
        } catch (SpatialIndexException e1) {
943
            // Probably we dont have writing permissions
944
            String directoryName = System.getProperty("java.io.tmpdir");
945
            File newFile = new File(directoryName +
946
                    File.separator +
947
                    file.getName());
948
            String newFileName = newFile.getName();
949
            try {
950
                localCopy = new QuadtreeGt2(newFileName, "NM", va.getFullExtent(),
951
                        va.getShapeCount(), true);
952
            } catch (SpatialIndexException e) {
953
                // if we cant build a file based spatial index, we'll build
954
                // a pure memory spatial index
955
                localCopy = new QuadtreeJts();
956
            } catch (ReadDriverException e) {
957
                localCopy = new QuadtreeJts();
958
            }
959

    
960
        } catch(Exception e){
961
            e.printStackTrace();
962
        }//try
963
        BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
964
        try {
965
            for (int i=0; i < va.getShapeCount(); i++)
966
            {
967
                if(cancelMonitor != null){
968
                    if(cancelMonitor.isCanceled())
969
                        return;
970
                    cancelMonitor.reportStep();
971
                }
972
                Rectangle2D r = shapeBounds.getShapeBounds(i);
973
                if(r != null)
974
                    localCopy.insert(r, i);
975
            } // for
976
            va.stop();
977
            if(localCopy instanceof IPersistentSpatialIndex)
978
                ((IPersistentSpatialIndex) localCopy).flush();
979
            spatialIndex = localCopy;
980
            //vectorial adapter needs a reference to the spatial index, to solve
981
            //request for feature iteration based in spatial queries
982
            source.setSpatialIndex(spatialIndex);
983
        } catch (ReadDriverException e) {
984
            // TODO Auto-generated catch block
985
            e.printStackTrace();
986
        }
987
    }
988

    
989
    public void createSpatialIndex() {
990
        createSpatialIndex(null);
991
    }
992

    
993
    public void process(FeatureVisitor visitor, FBitSet subset)
994
            throws ReadDriverException, ExpansionFileReadException, VisitorException {
995
        Strategy s = StrategyManager.getStrategy(this);
996
        s.process(visitor, subset);
997
    }
998

    
999
    public void process(FeatureVisitor visitor) throws ReadDriverException, VisitorException {
1000
        Strategy s = StrategyManager.getStrategy(this);
1001
        s.process(visitor);
1002
    }
1003

    
1004
    public void process(FeatureVisitor visitor, Rectangle2D rect)
1005
            throws ReadDriverException, ExpansionFileReadException, VisitorException {
1006
        Strategy s = StrategyManager.getStrategy(this);
1007
        s.process(visitor, rect);
1008
    }
1009

    
1010
    public FBitSet queryByRect(Rectangle2D rect) throws ReadDriverException, VisitorException {
1011
        Strategy s = StrategyManager.getStrategy(this);
1012

    
1013
        return s.queryByRect(rect);
1014
    }
1015

    
1016
    public FBitSet queryByPoint(Point2D p, double tolerance)
1017
            throws ReadDriverException, VisitorException {
1018
        Strategy s = StrategyManager.getStrategy(this);
1019
        return s.queryByPoint(p, tolerance);
1020
    }
1021

    
1022
    public FBitSet queryByShape(IGeometry g, int relationship)
1023
            throws ReadDriverException, VisitorException {
1024
        Strategy s = StrategyManager.getStrategy(this);
1025
        return s.queryByShape(g, relationship);
1026
    }
1027

    
1028
    public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException, VisitorException {
1029
        Point2D pReal = this.getMapContext().getViewPort().toMapPoint(p);
1030
        FBitSet bs = queryByPoint(pReal, tolerance);
1031
        VectorialXMLItem[] item = new VectorialXMLItem[1];
1032
        item[0] = new VectorialXMLItem(bs, this);
1033

    
1034
        return item;
1035
    }
1036

    
1037
    public void setLegend(IVectorLegend r) throws LegendLayerException {
1038
            if (this.legend == r){
1039
                    return;
1040
            }
1041
                if (this.legend != null && this.legend.equals(r)){
1042
                        return;
1043
                }
1044
        IVectorLegend oldLegend = legend;
1045
        legend = r;
1046
        try {
1047
            legend.setDataSource(getRecordset());
1048
        } catch (FieldNotFoundException e1) {
1049
            throw new LegendLayerException(getName(),e1);
1050
        } catch (ReadDriverException e1) {
1051
            throw new LegendLayerException(getName(),e1);
1052
        } finally{
1053
                this.updateDrawVersion();
1054
        }
1055
        if (oldLegend != null){
1056
                oldLegend.removeLegendListener(this);
1057
        }
1058
        if (legend != null){
1059
                legend.addLegendListener(this);
1060
        }
1061
        LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
1062
                oldLegend, legend);
1063
        callLegendChanged(e);
1064
    }
1065

    
1066
    /**
1067
     * Devuelve la Leyenda de la capa.
1068
     *
1069
     * @return Leyenda.
1070
     */
1071
    public ILegend getLegend() {
1072
        return legend;
1073
    }
1074

    
1075
    /**
1076
     * Devuelve el tipo de shape que contiene la capa.
1077
     *
1078
     * @return tipo de shape.
1079
     *
1080
     * @throws DriverException
1081
     */
1082
    public int getShapeType() throws ReadDriverException {
1083
        if (typeShape == -1) {
1084
            getSource().start();
1085
            typeShape = getSource().getShapeType();
1086
            getSource().stop();
1087
        }
1088

    
1089
        return typeShape;
1090
    }
1091

    
1092
    public XMLEntity getXMLEntity() throws XMLException {
1093
        if (!this.isAvailable() && this.orgXMLEntity != null) {
1094
            return this.orgXMLEntity;
1095
        }
1096
        XMLEntity xml = super.getXMLEntity();
1097
        if (getLegend()!=null)
1098
            xml.addChild(getLegend().getXMLEntity());
1099
        try {
1100
            if (getRecordset()!=null)
1101
                xml.addChild(getRecordset().getSelectionSupport().getXMLEntity());
1102
        } catch (ReadDriverException e1) {
1103
            e1.printStackTrace();
1104
            throw new XMLException(e1);
1105
        }
1106
        // Repongo el mismo ReadableVectorial m?s abajo para cuando se guarda el proyecto.
1107
        ReadableVectorial rv=getSource();
1108
        xml.putProperty("type", "vectorial");
1109
        if (source instanceof VectorialEditableAdapter) {
1110
            setSource(((VectorialEditableAdapter) source).getOriginalAdapter());
1111
        }
1112
        if (source instanceof VectorialFileAdapter) {
1113
            xml.putProperty("type", "vectorial");
1114
            xml.putProperty("file", ((VectorialFileAdapter) source)
1115
                    .getFile());
1116
            try {
1117
                xml.putProperty("recordset-name", source.getRecordset()
1118
                        .getName());
1119
            } catch (ReadDriverException e) {
1120
                throw new XMLException(e);
1121
            } catch (RuntimeException e) {
1122
                e.printStackTrace();
1123
            }
1124
        } else if (source instanceof VectorialDBAdapter) {
1125
            xml.putProperty("type", "vectorial");
1126

    
1127
            IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) source
1128
                    .getDriver();
1129

    
1130
            // Guardamos el nombre del driver para poder recuperarlo
1131
            // con el DriverManager de Fernando.
1132
            xml.putProperty("db", dbDriver.getName());
1133
            try {
1134
                xml.putProperty("recordset-name", source.getRecordset()
1135
                        .getName());
1136
            } catch (ReadDriverException e) {
1137
                throw new XMLException(e);
1138
            } catch (RuntimeException e) {
1139
                e.printStackTrace();
1140
            }
1141
            xml.addChild(dbDriver.getXMLEntity()); // Tercer child. Antes hemos
1142
                                                    // metido la leyenda y el
1143
                                                    // selection support
1144
        } else if (source instanceof VectorialAdapter) {
1145
            // Se supone que hemos hecho algo gen?rico.
1146
            xml.putProperty("type", "vectorial");
1147

    
1148
            VectorialDriver driver = source.getDriver();
1149

    
1150
            // Guardamos el nombre del driver para poder recuperarlo
1151
            // con el DriverManager de Fernando.
1152
            xml.putProperty("other", driver.getName());
1153
            // try {
1154
            try {
1155
                xml.putProperty("recordset-name", source.getRecordset()
1156
                        .getName());
1157
            } catch (ReadDriverException e) {
1158
                throw new XMLException(e);
1159
            } catch (RuntimeException e) {
1160
                e.printStackTrace();
1161
            }
1162
            if (driver instanceof IPersistence) {
1163
                // xml.putProperty("className", driver.getClass().getName());
1164
                    IPersistence persist = (IPersistence) driver;
1165
                xml.addChild(persist.getXMLEntity()); // Tercer child. Antes
1166
                                                        // hemos metido la
1167
                                                        // leyenda y el
1168
                                                        // selection support
1169
            }
1170
        }
1171
        if (rv!=null)
1172
            setSource(rv);
1173
        xml.putProperty("driverName", source.getDriver().getName());
1174
        if (bHasJoin)
1175
            xml.putProperty("hasJoin", "true");
1176

    
1177
        // properties from ILabelable
1178
        xml.putProperty("isLabeled", isLabeled);
1179
        if (strategy != null) {
1180
            XMLEntity strategyXML = strategy.getXMLEntity();
1181
            strategyXML.putProperty("Strategy", strategy.getClassName());
1182
            xml.addChild(strategy.getXMLEntity());
1183
        }
1184
        xml.addChild(getLinkProperties().getXMLEntity());
1185
        return xml;
1186
    }
1187

    
1188
    /**
1189
     * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
1190
     */
1191
    public void setXMLEntity03(XMLEntity xml) throws XMLException {
1192

    
1193
        super.setXMLEntity(xml);
1194
        legend = LegendFactory.createFromXML03(xml.getChild(0));
1195

    
1196
        try {
1197
            setLegend(legend);
1198
        } catch (LegendLayerException e) {
1199
            throw new XMLException(e);
1200
        }
1201

    
1202
        try {
1203
            getRecordset().getSelectionSupport()
1204
                    .setXMLEntity03(xml.getChild(1));
1205
        } catch (ReadDriverException e) {
1206
            e.printStackTrace();
1207
        }
1208
    }
1209

    
1210
    /*
1211
     * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
1212
     */
1213
    public void setXMLEntity(XMLEntity xml) throws XMLException {
1214
        try {
1215
                    super.setXMLEntity(xml);
1216
                    XMLEntity legendXML = xml.getChild(0);
1217
                    IVectorLegend leg = LegendFactory.createFromXML(legendXML);
1218

    
1219
                    /* end patch */
1220
                    try {
1221
                            getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
1222
                            // JMVIVO: Esto sirve para algo????
1223
                            /*
1224
                             *  Jaume: si, para restaurar el selectable datasource cuando se
1225
                             *  clona la capa, cuando se carga de un proyecto. Si no esta ya
1226
                             *  no se puede ni hacer consultas sql, ni hacer selecciones,
1227
                             *  ni usar la mayor parte de las herramientas.
1228
                             *
1229
                             *  Lo vuelvo a poner.
1230
                             */
1231

    
1232
                            String recordsetName = xml.getStringProperty("recordset-name");
1233

    
1234
//                            SelectableDataSource sds = new SelectableDataSource(LayerFactory
1235
//                                            .getDataSourceFactory().createRandomDataSource(
1236
//                                                            recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
1237

    
1238
                            LayerFactory.getDataSourceFactory().changeDataSourceName(
1239
                                            getSource().getRecordset().getName(), recordsetName);
1240
                            SelectableDataSource sds = new SelectableDataSource(LayerFactory
1241
                                            .getDataSourceFactory().createRandomDataSource(
1242
                                                            recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
1243

    
1244
                    } catch (NoSuchTableException e1) {
1245
                            this.setAvailable(false);
1246
                            throw new XMLException(e1);
1247
                    } catch (ReadDriverException e1) {
1248
                            this.setAvailable(false);
1249
                            throw new XMLException(e1);
1250
                    }
1251
                    // Si tiene una uni?n, lo marcamos para que no se cree la leyenda hasta
1252
                    // el final
1253
                    // de la lectura del proyecto
1254
                    if (xml.contains("hasJoin")) {
1255
                            setIsJoined(true);
1256
                            PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
1257
                    } else {
1258
                            try {
1259
                                    setLegend(leg);
1260
                            } catch (LegendLayerException e) {
1261
                                    throw new XMLException(e);
1262
                            }
1263
                    }
1264

    
1265
                    //Por compatibilidad con proyectos anteriores a la 1.0
1266
                    boolean containsIsLabeled = xml.contains("isLabeled");
1267
                    if (containsIsLabeled){
1268
                            isLabeled = xml.getBooleanProperty("isLabeled");
1269
                    }
1270
                    // set properties for ILabelable
1271
                    XMLEntity labelingXML = xml.firstChild("labelingStrategy", "labelingStrategy");
1272
                    if (labelingXML!= null) {
1273
                            if(!containsIsLabeled){
1274
                                    isLabeled = true;
1275
                            }
1276
                            try {
1277
                                    this.strategy = LabelingFactory.createStrategyFromXML(labelingXML, this);
1278
                            } catch (NotExistInXMLEntity neXMLEX) {
1279
                                    // no strategy was set, just continue;
1280
                                    logger.warn("Reached what should be unreachable code");
1281
                            }
1282
                    } else if (legendXML.contains("labelFieldName")) {
1283
                            /* (jaume) begin patch;
1284
                         * for backward compatibility purposes. Since gvSIG v1.1 labeling is
1285
                         * no longer managed by the Legend but by the ILabelingStrategy. The
1286
                         * following allows restoring older projects' labelings.
1287
                         */
1288
                                String labelTextField = legendXML.getStringProperty("labelFieldName");
1289
                                if (labelTextField != null) {
1290
                                        AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1291
                                        labeling.setLayer(this);
1292
                                        labeling.setUsesFixedSize(true);
1293
                                        labeling.setFixedSize(10);
1294
                                        labeling.setTextField(legendXML.getStringProperty("labelFieldName"));
1295
                                        labeling.setHeightField(legendXML.getStringProperty("labelHeightFieldName"));
1296
                                        labeling.setRotationField(legendXML.getStringProperty("labelRotationFieldName"));
1297
                                        this.setLabelingStrategy(labeling);
1298
                                        this.setIsLabeled(true);
1299
                                }
1300
                }else if(!containsIsLabeled){
1301
                                    isLabeled = false;
1302
                    }
1303

    
1304
                    // compatibility with hyperlink from 1.9 alpha version... do we really need to be compatible with alpha versions??
1305
                    XMLEntity xmlLinkProperties=xml.firstChild("typeChild", "linkProperties");
1306
                    if (xmlLinkProperties != null){
1307
                            try {
1308
                                    String fieldName=xmlLinkProperties.getStringProperty("fieldName");
1309
                                    String extName = xmlLinkProperties.getStringProperty("extName");
1310
                                    int typeLink = xmlLinkProperties.getIntProperty("typeLink");
1311
                                    if (fieldName!=null) {
1312
                                            setProperty("legacy.hyperlink.selectedField", fieldName);
1313
                                            setProperty("legacy.hyperlink.type", new Integer(typeLink));
1314
                                            if (extName!=null) {
1315
                                                    setProperty("legacy.hyperlink.extension", extName);
1316
                                            }
1317
                                    }
1318
                            }
1319
                            catch (NotExistInXMLEntity ex) {
1320
                                    logger.warn("Error getting old hyperlink configuration", ex);
1321
                            }
1322
                    }
1323

    
1324
            } catch (XMLException e) {
1325
                    this.setAvailable(false);
1326
                    this.orgXMLEntity = xml;
1327
            } catch (Exception e) {
1328
                    e.printStackTrace();
1329
                    this.setAvailable(false);
1330
                    this.orgXMLEntity = xml;
1331

    
1332
            }
1333

    
1334

    
1335
    }
1336

    
1337
    public void setXMLEntityNew(XMLEntity xml) throws XMLException {
1338
        try {
1339
            super.setXMLEntity(xml);
1340

    
1341
            XMLEntity legendXML = xml.getChild(0);
1342
            IVectorLegend leg = LegendFactory.createFromXML(legendXML);
1343
            /* (jaume) begin patch;
1344
             * for backward compatibility purposes. Since gvSIG v1.1 labeling is
1345
             * no longer managed by the Legend but by the ILabelingStrategy. The
1346
             * following allows restoring older projects' labelings.
1347
             */
1348
            if (legendXML.contains("labelFieldHeight")) {
1349
                AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1350
                labeling.setLayer(this);
1351
                labeling.setTextField(legendXML.getStringProperty("labelFieldHeight"));
1352
                labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
1353
                this.setLabelingStrategy(labeling);
1354
                this.setIsLabeled(true);
1355
              }
1356
            /* end patch */
1357
            try {
1358
                getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
1359

    
1360
                this.setLoadSelection(xml.getChild(1));
1361
            } catch (ReadDriverException e1) {
1362
                this.setAvailable(false);
1363
                throw new XMLException(e1);
1364
            }
1365
            // Si tiene una uni?n, lo marcamos para que no se cree la leyenda hasta
1366
            // el final
1367
            // de la lectura del proyecto
1368
            if (xml.contains("hasJoin")) {
1369
                setIsJoined(true);
1370
                PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
1371
            } else {
1372
                this.setLoadLegend(leg);
1373
            }
1374

    
1375
        } catch (XMLException e) {
1376
            this.setAvailable(false);
1377
            this.orgXMLEntity = xml;
1378
        } catch (Exception e) {
1379
            this.setAvailable(false);
1380
            this.orgXMLEntity = xml;
1381
        }
1382

    
1383

    
1384
    }
1385

    
1386

    
1387
    /**
1388
     * Sobreimplementaci?n del m?todo toString para que las bases de datos
1389
     * identifiquen la capa.
1390
     *
1391
     * @return DOCUMENT ME!
1392
     */
1393
    public String toString() {
1394
        /*
1395
         * Se usa internamente para que la parte de datos identifique de forma
1396
         * un?voca las tablas
1397
         */
1398
        String ret = super.toString();
1399

    
1400
        return "layer" + ret.substring(ret.indexOf('@') + 1);
1401
    }
1402

    
1403
    public boolean isJoined() {
1404
        return bHasJoin;
1405
    }
1406

    
1407
    /**
1408
     * Returns if a layer is spatially indexed
1409
     *
1410
     * @return if this layer has the ability to proces spatial queries without
1411
     *         secuential scans.
1412
     */
1413
    public boolean isSpatiallyIndexed() {
1414
        ReadableVectorial source = getSource();
1415
        if (source instanceof ISpatialDB)
1416
            return true;
1417

    
1418
//FIXME azabala
1419
/*
1420
 * Esto es muy dudoso, y puede cambiar.
1421
 * Estoy diciendo que las que no son fichero o no son
1422
 * BoundedShapes estan indexadas. Esto es mentira, pero
1423
 * as? quien pregunte no querr? generar el indice.
1424
 * Esta por ver si interesa generar el indice para capas
1425
 * HSQLDB, WFS, etc.
1426
 */
1427
        if(!(source instanceof VectorialFileAdapter)){
1428
            return true;
1429
        }
1430
        if (!(source.getDriver() instanceof BoundedShapes)) {
1431
            return true;
1432
        }
1433

    
1434
        if (getISpatialIndex() != null)
1435
            return true;
1436
        return false;
1437
    }
1438

    
1439
    public void setIsJoined(boolean hasJoin) {
1440
        bHasJoin = hasJoin;
1441
    }
1442

    
1443
    /**
1444
     * @return Returns the spatialIndex.
1445
     */
1446
    public ISpatialIndex getISpatialIndex() {
1447
        return spatialIndex;
1448
    }
1449
    /**
1450
     * Sets the spatial index. This could be useful if, for some
1451
     * reasons, you want to work with a distinct spatial index
1452
     * (for example, a spatial index which could makes nearest
1453
     * neighbour querys)
1454
     * @param spatialIndex
1455
     */
1456
    public void setISpatialIndex(ISpatialIndex spatialIndex){
1457
        this.spatialIndex = spatialIndex;
1458
    }
1459

    
1460
    public SelectableDataSource getRecordset() throws ReadDriverException {
1461
        if (!this.isAvailable()) return null;
1462
        if (sds == null) {
1463

    
1464
                SelectableDataSource ds = source.getRecordset();
1465

    
1466
                if (ds == null) {
1467
                    return null;
1468
                }
1469

    
1470
                sds = ds;
1471
                sds.setSelectionSupport(selectionSupport);
1472
                selectionSupport.addSelectionListener(this);
1473

    
1474
        }
1475
        return sds;
1476
    }
1477

    
1478
    public void setEditing(boolean b) throws StartEditionLayerException {
1479
        super.setEditing(b);
1480
        try {
1481
            if (b) {
1482
                VectorialEditableAdapter vea = null;
1483
                // TODO: Qu? pasa si hay m?s tipos de adapters?
1484
                // FJP: Se podr?a pasar como argumento el
1485
                // VectorialEditableAdapter
1486
                // que se quiera usar para evitar meter c?digo aqu? de este
1487
                // estilo.
1488
                if (getSource() instanceof VectorialDBAdapter) {
1489
                    vea = new VectorialEditableDBAdapter();
1490
                } else if (this instanceof FLyrAnnotation) {
1491
                    vea = new AnnotationEditableAdapter(
1492
                            (FLyrAnnotation) this);
1493
                } else {
1494
                    vea = new VectorialEditableAdapter();
1495
                }
1496
                vea.addEditionListener(this);
1497
                vea.setOriginalVectorialAdapter(getSource());
1498
//                                azo: implementations of readablevectorial need
1499
                //references of projection and spatial index
1500
                vea.setProjection(getProjection());
1501
                vea.setSpatialIndex(spatialIndex);
1502

    
1503

    
1504
                // /vea.setSpatialIndex(getSpatialIndex());
1505
                // /vea.setFullExtent(getFullExtent());
1506
                vea.setCoordTrans(getCoordTrans());
1507
                vea.startEdition(EditionEvent.GRAPHIC);
1508
                setSource(vea);
1509
                getRecordset().setSelectionSupport(
1510
                        vea.getOriginalAdapter().getRecordset()
1511
                                .getSelectionSupport());
1512

    
1513
            } else {
1514
                VectorialEditableAdapter vea = (VectorialEditableAdapter) getSource();
1515
                vea.removeEditionListener(this);
1516
                setSource(vea.getOriginalAdapter());
1517
            }
1518
            // Si tenemos una leyenda, hay que pegarle el cambiazo a su
1519
            // recordset
1520
            setRecordset(getSource().getRecordset());
1521
            if (getLegend() instanceof IVectorLegend) {
1522
                IVectorLegend ley = (IVectorLegend) getLegend();
1523
                ley.setDataSource(getSource().getRecordset());
1524
                // Esto lo pongo para evitar que al dibujar sobre un
1525
                // dxf, dwg, o dgn no veamos nada. Es debido al checkbox
1526
                // de la leyenda de textos "dibujar solo textos".
1527
//jaume
1528
//                                if (!(getSource().getDriver() instanceof IndexedShpDriver)){
1529
//                                        FSymbol symbol=new FSymbol(getShapeType());
1530
//                                        symbol.setFontSizeInPixels(false);
1531
//                                        symbol.setFont(new Font("SansSerif", Font.PLAIN, 9));
1532
//                                        Color color=symbol.getColor();
1533
//                                        int alpha=symbol.getColor().getAlpha();
1534
//                                        if (alpha>250) {
1535
//                                                symbol.setColor(new Color(color.getRed(),color.getGreen(),color.getBlue(),100));
1536
//                                        }
1537
//                                        ley.setDefaultSymbol(symbol);
1538
//                                }
1539
//jaume//
1540
                ley.useDefaultSymbol(true);
1541
            }
1542
        } catch (ReadDriverException e) {
1543
            throw new StartEditionLayerException(getName(),e);
1544
        } catch (FieldNotFoundException e) {
1545
            throw new StartEditionLayerException(getName(),e);
1546
        } catch (StartWriterVisitorException e) {
1547
            throw new StartEditionLayerException(getName(),e);
1548
        }
1549

    
1550
        setSpatialCacheEnabled(b);
1551
        callEditionChanged(LayerEvent
1552
                .createEditionChangedEvent(this, "edition"));
1553

    
1554
    }
1555

    
1556
    /**
1557
     * Para cuando haces una uni?n, sustituyes el recorset por el nuevo. De esta
1558
     * forma, podr?s poner leyendas basadas en el nuevo recordset
1559
     *
1560
     * @param newSds
1561
     */
1562
    public void setRecordset(SelectableDataSource newSds) {
1563
            // TODO: Deberiamos hacer comprobaciones del cambio
1564
        sds = newSds;
1565
        sds.setSelectionSupport(selectionSupport);
1566
                selectionSupport.addSelectionListener(this);
1567
                this.updateDrawVersion();
1568
    }
1569

    
1570
    public void clearSpatialCache()
1571
    {
1572
        spatialCache.clearAll();
1573
    }
1574

    
1575
    public boolean isSpatialCacheEnabled() {
1576
        return spatialCacheEnabled;
1577
    }
1578

    
1579
    public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
1580
        this.spatialCacheEnabled = spatialCacheEnabled;
1581
    }
1582

    
1583
    public SpatialCache getSpatialCache() {
1584
        return spatialCache;
1585
    }
1586

    
1587
    /**
1588
     * Siempre es un numero mayor de 1000
1589
     * @param maxFeatures
1590
     */
1591
    public void setMaxFeaturesInEditionCache(int maxFeatures) {
1592
        if (maxFeatures > spatialCache.maxFeatures)
1593
            spatialCache.setMaxFeatures(maxFeatures);
1594

    
1595
    }
1596

    
1597
    /**
1598
     * This method returns a boolean that is used by the FPopMenu
1599
     * to make visible the properties menu or not. It is visible by
1600
     * default, and if a later don't have to show this menu only
1601
     * has to override this method.
1602
     * @return
1603
     * If the properties menu is visible (or not)
1604
     */
1605
    public boolean isPropertiesMenuVisible(){
1606
        return true;
1607
    }
1608

    
1609
    public void reload() throws ReloadLayerException {
1610
        this.setAvailable(true);
1611
        super.reload();
1612
        this.updateDrawVersion();
1613
        try {
1614
            this.source.getDriver().reload();
1615
            if (this.getLegend() == null) {
1616
                if (this.getRecordset().getDriver() instanceof WithDefaultLegend) {
1617
                    WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset().getDriver();
1618
                    this.setLegend((IVectorLegend) aux.getDefaultLegend());
1619
                    this.setLabelingStrategy(aux.getDefaultLabelingStrategy());
1620
                } else {
1621
                    this.setLegend(LegendFactory.createSingleSymbolLegend(
1622
                            this.getShapeType()));
1623
                }
1624
            }
1625

    
1626
        } catch (LegendLayerException e) {
1627
            this.setAvailable(false);
1628
            throw new ReloadLayerException(getName(),e);
1629
        } catch (ReadDriverException e) {
1630
            this.setAvailable(false);
1631
            throw new ReloadLayerException(getName(),e);
1632
        }
1633

    
1634
    }
1635

    
1636
    protected void setLoadSelection(XMLEntity xml) {
1637
        this.loadSelection = xml;
1638
    }
1639

    
1640
    protected void setLoadLegend(IVectorLegend legend) {
1641
        this.loadLegend = legend;
1642
    }
1643

    
1644
    protected void putLoadSelection() throws XMLException {
1645
        if (this.loadSelection == null) return;
1646
        try {
1647
            this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
1648
        } catch (ReadDriverException e) {
1649
            throw new XMLException(e);
1650
        }
1651
        this.loadSelection = null;
1652

    
1653
    }
1654
    protected void putLoadLegend() throws LegendLayerException {
1655
        if (this.loadLegend == null) return;
1656
        this.setLegend(this.loadLegend);
1657
        this.loadLegend = null;
1658
    }
1659

    
1660
    protected void cleanLoadOptions() {
1661
        this.loadLegend = null;
1662
        this.loadSelection = null;
1663
    }
1664

    
1665
    public boolean isWritable() {
1666
        VectorialDriver drv = getSource().getDriver();
1667
        if (!drv.isWritable())
1668
            return false;
1669
        if (drv instanceof IWriteable)
1670
        {
1671
            IWriter writer = ((IWriteable)drv).getWriter();
1672
            if (writer != null)
1673
            {
1674
                if (writer instanceof ISpatialWriter)
1675
                    return true;
1676
            }
1677
        }
1678
        return false;
1679

    
1680
    }
1681

    
1682
    public FLayer cloneLayer() throws Exception {
1683
        FLyrVect clonedLayer = new FLyrVect();
1684
        clonedLayer.setSource(getSource());
1685
        if (isJoined()) {
1686
                        clonedLayer.setIsJoined(true);
1687
                        clonedLayer.setRecordset(getRecordset());
1688
                }
1689
        clonedLayer.setVisible(isVisible());
1690
        clonedLayer.setISpatialIndex(getISpatialIndex());
1691
        clonedLayer.setName(getName());
1692
        clonedLayer.setCoordTrans(getCoordTrans());
1693

    
1694
        clonedLayer.setLegend((IVectorLegend)getLegend().cloneLegend());
1695

    
1696
        clonedLayer.setIsLabeled(isLabeled());
1697
        ILabelingStrategy labelingStrategy=getLabelingStrategy();
1698
        if (labelingStrategy!=null)
1699
                clonedLayer.setLabelingStrategy(labelingStrategy);
1700

    
1701
        return clonedLayer;
1702
    }
1703

    
1704

    
1705
    private boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, double dpi, CartographicSupport csSym, IGeometry geom, int[] xyCoords) {
1706
            return isOnePoint(graphicsTransform, viewPort, geom, xyCoords) && csSym.getCartographicSize(viewPort, dpi, (FShape)geom.getInternalShape()) <= 1;
1707
    }
1708

    
1709
    private boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, IGeometry geom, int[] xyCoords) {
1710
            boolean onePoint = false;
1711
            int type=geom.getGeometryType() % FShape.Z;
1712
            if (type!=FShape.POINT && type!=FShape.MULTIPOINT && type!=FShape.NULL) {
1713

    
1714
                        Rectangle2D geomBounds = geom.getBounds2D();
1715

    
1716
                //        ICoordTrans ct = getCoordTrans();
1717

    
1718
                        // Se supone que la geometria ya esta
1719
                        // repoyectada y no hay que hacer
1720
                        // ninguna transformacion
1721
//                        if (ct!=null) {
1722
////                                geomBounds = ct.getInverted().convert(geomBounds);
1723
//                                geomBounds = ct.convert(geomBounds);
1724
//                        }
1725

    
1726
                        double dist1Pixel = viewPort.getDist1pixel();
1727

    
1728
                        onePoint = (geomBounds.getWidth()  <= dist1Pixel
1729
                                         && geomBounds.getHeight() <= dist1Pixel);
1730

    
1731
                        if (onePoint) {
1732
                                // avoid out of range exceptions
1733
                                FPoint2D p = new FPoint2D(geomBounds.getMinX(), geomBounds.getMinY());
1734
                                p.transform(viewPort.getAffineTransform());
1735
                                p.transform(graphicsTransform);
1736
                                xyCoords[0] = (int) p.getX();
1737
                                xyCoords[1] = (int) p.getY();
1738

    
1739
                        }
1740

    
1741
                }
1742
            return onePoint;
1743
    }
1744
    /*
1745
     * jaume. Stuff from ILabeled.
1746
     */
1747
    private boolean isLabeled;
1748
    private ILabelingStrategy strategy;
1749

    
1750
    public boolean isLabeled() {
1751
        return isLabeled;
1752
    }
1753

    
1754
    public void setIsLabeled(boolean isLabeled) {
1755
        this.isLabeled = isLabeled;
1756
    }
1757

    
1758
    public ILabelingStrategy getLabelingStrategy() {
1759
        return strategy;
1760
    }
1761

    
1762
    public void setLabelingStrategy(ILabelingStrategy strategy) {
1763
        this.strategy = strategy;
1764
        try {
1765
                        strategy.setLayer(this);
1766
                } catch (ReadDriverException e) {
1767
                        // TODO Auto-generated catch block
1768
                        e.printStackTrace();
1769
                }
1770
    }
1771

    
1772
    public void drawLabels(BufferedImage image, Graphics2D g, ViewPort viewPort,
1773
                    Cancellable cancel, double scale, double dpi) throws ReadDriverException {
1774
        if (strategy!=null && isWithinScale(scale)) {
1775
                strategy.draw(image, g, viewPort, cancel, dpi);
1776
        }
1777
    }
1778
    public void printLabels(Graphics2D g, ViewPort viewPort,
1779
                    Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
1780
        if (strategy!=null) {
1781
                strategy.print(g, viewPort, cancel, properties);
1782
        }
1783
    }
1784

    
1785

    
1786
    //M?todos para el uso de HyperLinks en capas FLyerVect
1787

    
1788
    /**
1789
     * Return true, because a Vectorial Layer supports HyperLink
1790
     */
1791
    public boolean allowLinks()
1792
    {
1793
            return true;
1794
    }
1795

    
1796
    /**
1797
         * Returns an instance of AbstractLinkProperties that contains the information
1798
         * of the HyperLink
1799
         * @return Abstra
1800
         */
1801
    public AbstractLinkProperties getLinkProperties()
1802
    {
1803
            return linkProperties;
1804
    }
1805

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

    
1839
        public void selectionChanged(SelectionEvent e) {
1840
                this.updateDrawVersion();
1841
        }
1842

    
1843
        public void afterFieldEditEvent(AfterFieldEditEvent e) {
1844
                this.updateDrawVersion();
1845
        }
1846

    
1847
        public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) {
1848
                this.updateDrawVersion();
1849

    
1850
        }
1851

    
1852
        public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
1853

    
1854
        }
1855

    
1856
        public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
1857

    
1858
        }
1859

    
1860
        public void processEvent(EditionEvent e) {
1861
                if (e.getChangeType()== e.ROW_EDITION){
1862
                        this.updateDrawVersion();
1863
                }
1864

    
1865
        }
1866

    
1867
        public void legendCleared(LegendClearEvent event) {
1868
                this.updateDrawVersion();
1869
        LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
1870
                legend, legend);
1871
        this.callLegendChanged(e);
1872
        }
1873

    
1874
        public boolean symbolChanged(SymbolLegendEvent e) {
1875
                this.updateDrawVersion();
1876
        LegendChangedEvent event = LegendChangedEvent.createLegendChangedEvent(
1877
                legend, legend);
1878
        this.callLegendChanged(event);
1879
        return true;
1880
        }
1881
        public String getTypeStringVectorLayer() throws ReadDriverException {
1882
                String typeString="";
1883
                int typeShape=((FLyrVect)this).getShapeType();
1884
                if (FShape.MULTI==typeShape){
1885
                        ReadableVectorial rv=((FLyrVect)this).getSource();
1886
                        if (rv.getShapeCount()>0){
1887
                                if ((rv.getShape(0).getGeometryType() & FShape.Z) == FShape.Z){
1888
                                        typeString="Geometries3D";
1889
                                }else{
1890
                                        typeString="Geometries2D";
1891
                                 }
1892
                         }
1893
                }else{
1894
                        ReadableVectorial rv=((FLyrVect)this).getSource();
1895
                        if (rv.getShapeCount()>0){
1896
                                int type=rv.getShape(0).getGeometryType();
1897
                                if (FShape.POINT == type){
1898
                                        typeString="Point2D";
1899
                                } else if (FShape.LINE == type){
1900
                                        typeString="Line2D";
1901
                                } else if (FShape.POLYGON == type){
1902
                                        typeString="Polygon2D";
1903
                                } else if (FShape.MULTIPOINT == type){
1904
                                        typeString="MultiPint2D";
1905
                                } else if ((FShape.POINT | FShape.Z)  == type ){
1906
                                        typeString="Point3D";
1907
                                } else if ((FShape.LINE | FShape.Z)  == type ){
1908
                                        typeString="Line3D";
1909
                                } else if ((FShape.POLYGON | FShape.Z)  == type ){
1910
                                        typeString="Polygon3D";
1911
                                } else if ((FShape.MULTIPOINT | FShape.Z)  == type ){
1912
                                        typeString="MultiPoint3D";
1913
                                } else if ((FShape.POINT | FShape.M)  == type ){
1914
                                        typeString="PointM";
1915
                                } else if ((FShape.LINE | FShape.M)  == type ){
1916
                                        typeString="LineM";
1917
                                } else if ((FShape.POLYGON | FShape.M)  == type ){
1918
                                        typeString="PolygonM";
1919
                                } else if ((FShape.MULTIPOINT | FShape.M)  == type ){
1920
                                        typeString="MultiPointM";
1921
                                } else if ((FShape.MULTI | FShape.M)  == type ){
1922
                                        typeString="M";
1923
                                }
1924
                        }
1925
                        return typeString;
1926
                }
1927
                return "";
1928
        }
1929
        public int getTypeIntVectorLayer() throws ReadDriverException {
1930
                int typeInt=0;
1931
                int typeShape=((FLyrVect)this).getShapeType();
1932
                if (FShape.MULTI==typeShape){
1933
                        ReadableVectorial rv=((FLyrVect)this).getSource();
1934
                        if (rv.getShapeCount()>0){
1935
                                if ((rv.getShape(0).getGeometryType() & FShape.Z) == FShape.Z){
1936
                                        typeInt=FShape.MULTI | FShape.Z;
1937
                                }else{
1938
                                        typeInt=FShape.MULTI;
1939
                                }
1940
                        }
1941
                }else{
1942
                        ReadableVectorial rv=((FLyrVect)this).getSource();
1943
                        if (rv.getShapeCount()>0){
1944
                                int type=rv.getShape(0).getGeometryType();
1945
                                typeInt=type;
1946
                        }
1947
                        return typeInt;
1948
                }
1949
                return typeInt;
1950
        }
1951
 }