Statistics
| Revision:

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

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
                                            boolean bDrawCartographicSupport = false;
858

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

    
863
                                                    csSym = (CartographicSupport) sym;
864
                                                    bDrawCartographicSupport = (csSym.getUnit() != -1);
865
                                            }
866

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

    
869
//                                            if (!bDrawCartographicSupport) {
870
//                                                    geom.drawInts(g, viewPort, sym, null);
871
//                                            } else {
872
                                                    geom.drawInts(g, viewPort, dpi, (CartographicSupport) csSym, cancel);
873
//                                            }
874

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

    
886

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

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

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

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

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

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

    
991
    public void createSpatialIndex() {
992
        createSpatialIndex(null);
993
    }
994

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

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

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

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

    
1015
        return s.queryByRect(rect);
1016
    }
1017

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

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

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

    
1036
        return item;
1037
    }
1038

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

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

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

    
1091
        return typeShape;
1092
    }
1093

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

    
1129
            IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) source
1130
                    .getDriver();
1131

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

    
1150
            VectorialDriver driver = source.getDriver();
1151

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

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

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

    
1195
        super.setXMLEntity(xml);
1196
        legend = LegendFactory.createFromXML03(xml.getChild(0));
1197

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

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

    
1212
    /*
1213
     * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
1214
     */
1215
    public void setXMLEntity(XMLEntity xml) throws XMLException {
1216
        try {
1217
                    super.setXMLEntity(xml);
1218
                    XMLEntity legendXML = xml.getChild(0);
1219
                    IVectorLegend leg = LegendFactory.createFromXML(legendXML);
1220
                    /* (jaume) begin patch;
1221
                     * for backward compatibility purposes. Since gvSIG v1.1 labeling is
1222
                     * no longer managed by the Legend but by the ILabelingStrategy. The
1223
                     * following allows restoring older projects' labelings.
1224
                     */
1225
                    if (legendXML.contains("labelFieldName")) {
1226
                            String labelTextField = legendXML.getStringProperty("labelFieldName");
1227
                            if (labelTextField != null) {
1228
                                    AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1229
                                    labeling.setLayer(this);
1230
                                    labeling.setTextField(legendXML.getStringProperty("labelFieldName"));
1231
                                    labeling.setHeightField(legendXML.getStringProperty("labelHeightFieldName"));
1232
                                    labeling.setRotationField(legendXML.getStringProperty("labelRotationFieldName"));
1233
                                    this.setLabelingStrategy(labeling);
1234
                                    this.setIsLabeled(true);
1235
                            }
1236
                    }
1237
                    /* end patch */
1238
                    try {
1239
                            getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
1240
                            // JMVIVO: Esto sirve para algo????
1241
                            /*
1242
                             *  Jaume: si, para restaurar el selectable datasource cuando se
1243
                             *  clona la capa, cuando se carga de un proyecto. Si no esta ya
1244
                             *  no se puede ni hacer consultas sql, ni hacer selecciones,
1245
                             *  ni usar la mayor parte de las herramientas.
1246
                             *
1247
                             *  Lo vuelvo a poner.
1248
                             */
1249

    
1250
                            String recordsetName = xml.getStringProperty("recordset-name");
1251

    
1252
//                            SelectableDataSource sds = new SelectableDataSource(LayerFactory
1253
//                                            .getDataSourceFactory().createRandomDataSource(
1254
//                                                            recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
1255

    
1256
                            LayerFactory.getDataSourceFactory().changeDataSourceName(
1257
                                            getSource().getRecordset().getName(), recordsetName);
1258
                            SelectableDataSource sds = new SelectableDataSource(LayerFactory
1259
                                            .getDataSourceFactory().createRandomDataSource(
1260
                                                            recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
1261

    
1262
                    } catch (NoSuchTableException e1) {
1263
                            this.setAvailable(false);
1264
                            throw new XMLException(e1);
1265
                    } catch (ReadDriverException e1) {
1266
                            this.setAvailable(false);
1267
                            throw new XMLException(e1);
1268
                    }
1269
                    // Si tiene una uni?n, lo marcamos para que no se cree la leyenda hasta
1270
                    // el final
1271
                    // de la lectura del proyecto
1272
                    if (xml.contains("hasJoin")) {
1273
                            setIsJoined(true);
1274
                            PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
1275
                    } else {
1276
                            try {
1277
                                    setLegend(leg);
1278
                            } catch (LegendLayerException e) {
1279
                                    throw new XMLException(e);
1280
                            }
1281
                    }
1282

    
1283
                    //Por compatibilidad con proyectos anteriores a la 1.0
1284
                    boolean containsIsLabeled = xml.contains("isLabeled");
1285
                    if (containsIsLabeled){
1286
                            isLabeled = xml.getBooleanProperty("isLabeled");
1287
                    }
1288
                    // set properties for ILabelable
1289
                    XMLEntity labelingXML = xml.firstChild("labelingStrategy", "labelingStrategy");
1290
                    if (labelingXML!= null) {
1291
                            if(!containsIsLabeled){
1292
                                    isLabeled = true;
1293
                            }
1294
                            try {
1295
                                    this.strategy = LabelingFactory.createStrategyFromXML(labelingXML, this);
1296
                            } catch (NotExistInXMLEntity neXMLEX) {
1297
                                    // no strategy was set, just continue;
1298
                                    logger.warn("Reached what should be unreachable code");
1299
                            }
1300
                    } else {
1301
                            if(!containsIsLabeled){
1302
                                    isLabeled = false;
1303
                            }
1304
                    }
1305

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

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

    
1334
            }
1335

    
1336

    
1337
    }
1338

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

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

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

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

    
1385

    
1386
    }
1387

    
1388

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

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

    
1405
    public boolean isJoined() {
1406
        return bHasJoin;
1407
    }
1408

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

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

    
1436
        if (getISpatialIndex() != null)
1437
            return true;
1438
        return false;
1439
    }
1440

    
1441
    public void setIsJoined(boolean hasJoin) {
1442
        bHasJoin = hasJoin;
1443
    }
1444

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

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

    
1466
                SelectableDataSource ds = source.getRecordset();
1467

    
1468
                if (ds == null) {
1469
                    return null;
1470
                }
1471

    
1472
                sds = ds;
1473
                sds.setSelectionSupport(selectionSupport);
1474
                selectionSupport.addSelectionListener(this);
1475

    
1476
        }
1477
        return sds;
1478
    }
1479

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

    
1505

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

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

    
1552
        setSpatialCacheEnabled(b);
1553
        callEditionChanged(LayerEvent
1554
                .createEditionChangedEvent(this, "edition"));
1555

    
1556
    }
1557

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

    
1572
    public void clearSpatialCache()
1573
    {
1574
        spatialCache.clearAll();
1575
    }
1576

    
1577
    public boolean isSpatialCacheEnabled() {
1578
        return spatialCacheEnabled;
1579
    }
1580

    
1581
    public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
1582
        this.spatialCacheEnabled = spatialCacheEnabled;
1583
    }
1584

    
1585
    public SpatialCache getSpatialCache() {
1586
        return spatialCache;
1587
    }
1588

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

    
1597
    }
1598

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

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

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

    
1636
    }
1637

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

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

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

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

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

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

    
1682
    }
1683

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

    
1696
        clonedLayer.setLegend((IVectorLegend)getLegend().cloneLegend());
1697

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

    
1703
        return clonedLayer;
1704
    }
1705

    
1706

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

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

    
1716
                        Rectangle2D geomBounds = geom.getBounds2D();
1717

    
1718
                //        ICoordTrans ct = getCoordTrans();
1719

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

    
1728
                        double dist1Pixel = viewPort.getDist1pixel();
1729

    
1730
                        onePoint = (geomBounds.getWidth()  <= dist1Pixel
1731
                                         && geomBounds.getHeight() <= dist1Pixel);
1732

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

    
1741
                        }
1742

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

    
1752
    public boolean isLabeled() {
1753
        return isLabeled;
1754
    }
1755

    
1756
    public void setIsLabeled(boolean isLabeled) {
1757
        this.isLabeled = isLabeled;
1758
    }
1759

    
1760
    public ILabelingStrategy getLabelingStrategy() {
1761
        return strategy;
1762
    }
1763

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

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

    
1787

    
1788
    //M?todos para el uso de HyperLinks en capas FLyerVect
1789

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

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

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

    
1841
        public void selectionChanged(SelectionEvent e) {
1842
                this.updateDrawVersion();
1843
        }
1844

    
1845
        public void afterFieldEditEvent(AfterFieldEditEvent e) {
1846
                this.updateDrawVersion();
1847
        }
1848

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

    
1852
        }
1853

    
1854
        public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
1855

    
1856
        }
1857

    
1858
        public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
1859

    
1860
        }
1861

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

    
1867
        }
1868

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

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