Statistics
| Revision:

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

History | View | Annotate | Download (64 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

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

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

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

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

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

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

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

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

    
199

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

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

    
241
    }
242

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

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

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

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

    
300
            // Si existe reproyecci?n, reproyectar el extent
301
            ICoordTrans ct = getCoordTrans();
302

    
303
            if (ct != null) {
304
                Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
305
                Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
306
                pt1 = ct.convert(pt1, null);
307
                pt2 = ct.convert(pt2, null);
308
                rAux = new Rectangle2D.Double();
309
                rAux.setFrameFromDiagonal(pt1, pt2);
310
            }
311

    
312
            //Esto es para cuando se crea una capa nueva con el fullExtent de ancho y alto 0.
313
            if (rAux.getWidth()==0 && rAux.getHeight()==0) {
314
                rAux=new Rectangle2D.Double(0,0,100,100);
315
            }
316

    
317
            return rAux;
318
    }
319

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

    
339

    
340

    
341
            if (bDrawShapes) {
342
                    boolean cacheFeatures = isSpatialCacheEnabled();
343
                    SpatialCache cache = null;
344
                    if (cacheFeatures) {
345
                            getSpatialCache().clearAll();
346
                            cache = getSpatialCache();
347
                    }
348

    
349
                    try {
350
                            ArrayList<String> fieldList = new ArrayList<String>();
351

    
352
                            // fields from legend
353
                            String[] aux = null;
354

    
355
                            if (legend instanceof IClassifiedVectorLegend) {
356
                                    aux = ((IClassifiedVectorLegend) legend).getClassifyingFieldNames();
357
                                    if (aux!=null)
358
                                            for (int i = 0; i < aux.length; i++) {
359
                                                    fieldList.add(aux[i]);
360
                                            }
361
                            }
362

    
363
                            // Get the iterator over the visible features
364
                            IFeatureIterator it = getSource().getFeatureIterator(
365
                                            viewPort.getAdjustedExtent(),
366
                                            fieldList.toArray(new String[fieldList.size()]),
367
                                            viewPort.getProjection(),
368
                                            true);
369

    
370
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
371

    
372
                            boolean bSymbolLevelError = false;
373

    
374
                            // if layer has map levels it will use a ZSort
375
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
376

    
377
                            // -- visual FX stuff
378
                            long time = System.currentTimeMillis();
379
                            BufferedImage virtualBim;
380
                            Graphics2D virtualGraphics;
381

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

    
398

    
399
                            // Iteration over each feature
400
                            while ( !cancel.isCanceled() && it.hasNext()) {
401
                                    IFeature feat = it.next();
402
                                    IGeometry geom = feat.getGeometry();
403

    
404
                                    if (cacheFeatures) {
405
                                            if (cache.getMaxFeatures() >= cache.size()) {
406
                                                    // already reprojected
407
                                                    cache.insert(geom.getBounds2D(), geom);
408
                                            }
409
                                    }
410

    
411
                                    // retrieve the symbol associated to such feature
412
                                    ISymbol sym = legend.getSymbolByFeature(feat);
413

    
414
                                    if (sym == null) continue;
415

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

    
430
                                    // Check if this symbol is sized with CartographicSupport
431
                                    CartographicSupport csSym = null;
432
                                    int symbolType = sym.getSymbolType();
433
                                    boolean bDrawCartographicSupport = false;
434

    
435
                                    if (   symbolType == FShape.POINT
436
                                                    || symbolType == FShape.LINE
437
                                                    || sym instanceof CartographicSupport) {
438

    
439
                                            // patch
440
                                            if (!sym.getClass().equals(FSymbol.class)) {
441
                                                    csSym = (CartographicSupport) sym;
442
                                                    bDrawCartographicSupport = (csSym.getUnit() != -1);
443
                                            }
444
                                    }
445

    
446
                                    int x = -1;
447
                                    int y = -1;
448
                                    int[] xyCoords = new int[2];
449

    
450
                                    // Check if size is a pixel
451
                                    boolean onePoint = bDrawCartographicSupport ?
452
                                                    isOnePoint(g.getTransform(), viewPort, MapContext.getScreenDPI(), csSym, geom, xyCoords) :
453
                                                            isOnePoint(g.getTransform(), viewPort, geom, xyCoords);
454

    
455
                                                    // Avoid out of bounds exceptions
456
                                                    if (onePoint) {
457
                                                            x = xyCoords[0];
458
                                                            y = xyCoords[1];
459
                                                            if (x<0 || y<0 || x>= viewPort.getImageWidth() || y>=viewPort.getImageHeight()) continue;
460
                                                    }
461

    
462
                                                    if (useZSort) {
463
                                                            // Check if this symbol is a multilayer
464
                                                            if (sym instanceof IMultiLayerSymbol) {
465
                                                                    // if so, treat each of its layers as a single symbol
466
                                                                    // in its corresponding map level
467
                                                                    IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
468
                                                                    for (int i = 0; !cancel.isCanceled() && i < mlSym.getLayerCount(); i++) {
469
                                                                            ISymbol mySym = mlSym.getLayer(i);
470
                                                                            int symbolLevel = zSort.getSymbolLevel(mySym);
471

    
472
                                                                            if (symbolLevel == -1) {
473
                                                                                    /* an error occured when managing symbol levels.
474
                                                                                     * some of the legend changed events regarding the
475
                                                                                     * symbols did not finish satisfactory and the legend
476
                                                                                     * is now inconsistent. For this drawing, it will finish
477
                                                                                     * as it was at the bottom (level 0) but, when done, the
478
                                                                                     * ZSort will be reset to avoid app crashes. This is
479
                                                                                     * a bug that has to be fixed.
480
                                                                                     */
481
                                                                                    bSymbolLevelError = true;
482
                                                                                    symbolLevel=0;
483
                                                                            }
484

    
485
                                                                            if (onePoint) {
486
                                                                                    if (x<0 || y<0 || x>= imageLevels[symbolLevel].getWidth() || y>=imageLevels[symbolLevel].getHeight()) continue;
487
                                                                                    imageLevels[symbolLevel].setRGB(x, y, mySym.getOnePointRgb());
488
                                                                            } else {
489
                                                                                    if (!bDrawCartographicSupport) {
490
                                                                                            geom.drawInts(graphics[symbolLevel], viewPort, mySym, cancel);
491
                                                                                    } else {
492
                                                                                            geom.drawInts(graphics[symbolLevel], viewPort, dpi, (CartographicSupport) mySym, cancel);
493
                                                                                    }
494
                                                                            }
495
                                                                    }
496
                                                            } else {
497
                                                                    // else, just draw the symbol in its level
498
                                                                    int symbolLevel = zSort.getSymbolLevel(sym);
499
                                                                    if (symbolLevel == -1) {
500
                                                                            /* an error occured when managing symbol levels.
501
                                                                             * some of the legend changed events regarding the
502
                                                                             * symbols did not finish satisfactory and the legend
503
                                                                             * is now inconsistent. For this drawing, it will finish
504
                                                                             * as it was at the bottom (level 0). This is
505
                                                                             * a bug that has to be fixed.
506
                                                                             */
507
//                                                                            bSymbolLevelError = true;
508
                                                                            symbolLevel=0;
509
                                                                    }
510

    
511
                                                                    if (!bDrawCartographicSupport) {
512
                                                                            geom.drawInts(graphics[symbolLevel], viewPort, sym, cancel);
513
                                                                    } else {
514
                                                                            geom.drawInts(graphics[symbolLevel], viewPort, dpi, (CartographicSupport) csSym, cancel);
515
                                                                    }
516
                                                            }
517

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

    
534
                                                    } else {
535
                                                            // no ZSort, so there is only a map level, symbols are
536
                                                            // just drawn.
537
                                                            if (onePoint) {
538
                                                                    if (x<0 || y<0 || x>= image.getWidth() || y>=image.getHeight()) continue;
539
                                                                    image.setRGB(x, y, sym.getOnePointRgb());
540
                                                            } else {
541
                                                                    if (!bDrawCartographicSupport) {
542
                                                                            geom.drawInts(g, viewPort, sym, cancel);
543
                                                                    } else {
544
                                                                            geom.drawInts(g, viewPort, dpi, csSym, cancel);
545
                                                                    }
546
                                                            }
547
                                                    }
548
                            }
549

    
550
                            if (useZSort) {
551
                                    g.drawImage(image, 0, 0, null);
552
                                    g.translate(offset.getX(), offset.getY());
553
                                    for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
554
                                            g.drawImage(imageLevels[i],0,0, null);
555
                                            imageLevels[i] = null;
556
                                            graphics[i] = null;
557
                                    }
558
                                    g.translate(-offset.getX(), -offset.getY());
559
                                    imageLevels = null;
560
                                    graphics = null;
561
                            }
562
                            it.closeIterator();
563

    
564
                            if (bSymbolLevelError) {
565
                                    ((IVectorLegend) getLegend()).setZSort(null);
566
                            }
567

    
568
                    } catch (ReadDriverException e) {
569
                            this.setVisible(false);
570
                            this.setActive(false);
571
                            throw e;
572
                    }
573

    
574

    
575
            }
576
    }
577

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

    
613
    /**
614
     * Se llama antes de empezar a pintar.
615
     * Es ?til para preparar la cache a emplear, las leyendas, etc.
616
     * @param image
617
     * @param g
618
     * @param viewPort
619
     */
620
    private void prepareDrawing(BufferedImage image, Graphics2D g, ViewPort viewPort) {
621

    
622
    }
623

    
624
    public void _print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
625
                    double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
626
            // TEST METHOD
627

    
628

    
629
                    /* SVN */
630

    
631
    /*        boolean bDrawShapes = true;
632
            if (legend instanceof SingleSymbolLegend) {
633
                    bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
634
            }
635

636

637
            if (bDrawShapes) {
638
                    double dpi = 72;
639

640
                    PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
641
                    if (resolution.equals(PrintQuality.NORMAL)){
642
                            dpi = 300;
643
                    } else if (resolution.equals(PrintQuality.HIGH)){
644
                            dpi = 600;
645
                    } else if (resolution.equals(PrintQuality.DRAFT)){
646
                            dpi = 72;
647
                    }
648

649

650
                    try {
651
                            prepareDrawing(null, g, viewPort);
652
                            ArrayList<String> fieldList = new ArrayList<String>();
653
                            String[] aux;
654

655
                            // fields from legend
656
                            if (legend instanceof IClassifiedVectorLegend) {
657
                                    aux = ((IClassifiedVectorLegend) legend).
658
                                                                            getClassifyingFieldNames();
659
                                    for (int i = 0; i < aux.length; i++) {
660
                                            fieldList.add(aux[i]);
661
                                    }
662
                            }
663

664
                            // fields from labeling
665
                            if (isLabeled()) {
666
                                    aux = getLabelingStrategy().getUsedFields();
667
                                    for (int i = 0; i < aux.length; i++) {
668
                                            fieldList.add(aux[i]);
669
                                    }
670
                            }
671

672
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
673

674
                            // if layer has map levels it will use a ZSort
675
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
676

677

678
                            int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
679
                            for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
680
                                    // Get the iterator over the visible features
681
                                    IFeatureIterator it = getSource().getFeatureIterator(
682
                                                    viewPort.getAdjustedExtent(),
683
                                                    fieldList.toArray(new String[fieldList.size()]),
684
                                                    viewPort.getProjection(),
685
                                                    true);
686

687
                                    // Iteration over each feature
688
                                    while ( !cancel.isCanceled() && it.hasNext()) {
689
                                            IFeature feat = it.next();
690
                                            IGeometry geom = feat.getGeometry();
691

692
                                            // retreive the symbol associated to such feature
693
                                            ISymbol sym = legend.getSymbolByFeature(feat);
694

695
                                            if (useZSort) {
696
                                                    // Check if this symbol is a multilayer
697
                                                        if (sym instanceof IMultiLayerSymbol) {
698
                                                                // if so, get the layer corresponding to the current
699
                                                                // level. If none, continue to next iteration
700
                                                                IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
701
                                                                for (int i = 0; i < mlSym.getLayerCount(); i++) {
702
                                                                        ISymbol mySym = mlSym.getLayer(i);
703
                                                                        if (zSort.getSymbolLevel(mySym) == mapPass) {
704
                                                                                sym = mySym;
705
                                                                                break;
706
                                                                        }
707
                                                                        System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")");
708
                                                                }
709

710
                                                                if (sym == null) {
711
                                                                        continue;
712
                                                                }
713
                                                        } else {
714
                                                                // else, just draw the symbol in its level
715
                                                                if (zSort.getSymbolLevel(sym) != mapPass) {
716
                                                                        System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")");
717
                                                                        continue;
718
                                                                }
719
                                                        }
720
                                            }
721

722
                                            // Check if this symbol is sized with CartographicSupport
723
                                            CartographicSupport csSym = null;
724
                                            int symbolType = sym.getSymbolType();
725
                                            boolean bDrawCartographicSupport = false;
726

727
                                            if (   symbolType == FShape.POINT
728
                                                            || symbolType == FShape.LINE
729
                                                            || sym instanceof CartographicSupport) {
730

731
                                                    csSym = (CartographicSupport) sym;
732
                                                    bDrawCartographicSupport = (csSym.getUnit() != -1);
733
                                            }
734

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

737
                                            if (!bDrawCartographicSupport) {
738
                                                    geom.drawInts(g, viewPort, sym, null);
739
                                            } else {
740
                                                    geom.drawInts(g, viewPort, dpi, (CartographicSupport) csSym);
741
                                            }
742

743
                                    }
744
                                    it.closeIterator();
745
                            }
746
                    } catch (ReadDriverException e) {
747
                            this.setVisible(false);
748
                            this.setActive(false);
749
                            throw e;
750
                    }
751
        */
752

    
753

    
754
            // TEST METHOD
755
            boolean bDrawShapes = true;
756
            if (legend instanceof SingleSymbolLegend) {
757
                    bDrawShapes = legend.getDefaultSymbol().isShapeVisible();
758
            }
759

    
760

    
761
            if (bDrawShapes) {
762

    
763
                    try {
764
                            double dpi = 72;
765

    
766
                            PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
767
                            if (resolution.equals(PrintQuality.NORMAL)){
768
                                    dpi = 300;
769
                            } else if (resolution.equals(PrintQuality.HIGH)){
770
                                    dpi = 600;
771
                            } else if (resolution.equals(PrintQuality.DRAFT)){
772
                                    dpi = 72;
773
                            }
774
                            ArrayList<String> fieldList = new ArrayList<String>();
775
                            String[] aux;
776

    
777
                            // fields from legend
778
                            if (legend instanceof IClassifiedVectorLegend) {
779
                                    aux = ((IClassifiedVectorLegend) legend).
780
                                    getClassifyingFieldNames();
781
                                    for (int i = 0; i < aux.length; i++) {
782
                                            fieldList.add(aux[i]);
783
                                    }
784
                            }
785
//
786
//                            // fields from labeling
787
//                            if (isLabeled()) {
788
//                                    aux = getLabelingStrategy().getUsedFields();
789
//                                    for (int i = 0; i < aux.length; i++) {
790
//                                            fieldList.add(aux[i]);
791
//                                    }
792
//                            }
793

    
794
                            ZSort zSort = ((IVectorLegend) getLegend()).getZSort();
795

    
796
                            // if layer has map levels it will use a ZSort
797
                            boolean useZSort = zSort != null && zSort.isUsingZSort();
798

    
799

    
800
                            int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
801
                            for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
802
                                    // Get the iterator over the visible features
803
                                    IFeatureIterator it = getSource().getFeatureIterator(
804
                                                    viewPort.getAdjustedExtent(),
805
                                                    fieldList.toArray(new String[fieldList.size()]),
806
                                                    viewPort.getProjection(),
807
                                                    true);
808

    
809
                                    // Iteration over each feature
810
                                    while ( !cancel.isCanceled() && it.hasNext()) {
811
                                            IFeature feat = it.next();
812
                                            IGeometry geom = feat.getGeometry();
813

    
814
                                            // retreive the symbol associated to such feature
815
                                            ISymbol sym = legend.getSymbolByFeature(feat);
816

    
817
                                            if (useZSort) {
818
                                                    // Check if this symbol is a multilayer
819
                                                    if (sym instanceof IMultiLayerSymbol) {
820
                                                            // if so, get the layer corresponding to the current
821
                                                            // level. If none, continue to next iteration
822
                                                            IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
823
                                                            for (int i = 0; i < mlSym.getLayerCount(); i++) {
824
                                                                    ISymbol mySym = mlSym.getLayer(i);
825
                                                                    if (zSort.getSymbolLevel(mySym) == mapPass) {
826
                                                                            sym = mySym;
827
                                                                            break;
828
                                                                    }
829
                                                                    System.out.println("avoided layer "+i+"of symbol '"+mlSym.getDescription()+"' (pass "+mapPass+")");
830
                                                            }
831

    
832
                                                            if (sym == null) {
833
                                                                    continue;
834
                                                            }
835
                                                    } else {
836
                                                            // else, just draw the symbol in its level
837
                                                            if (zSort.getSymbolLevel(sym) != mapPass) {
838
                                                                    System.out.println("avoided single layer symbol '"+sym.getDescription()+"' (pass "+mapPass+")");
839
                                                                    continue;
840
                                                            }
841
                                                    }
842
                                            }
843

    
844
                                            // Check if this symbol is sized with CartographicSupport
845
                                            CartographicSupport csSym = null;
846
                                            int symbolType = sym.getSymbolType();
847
                                            boolean bDrawCartographicSupport = false;
848

    
849
                                            if (   symbolType == FShape.POINT
850
                                                            || symbolType == FShape.LINE
851
                                                            || sym instanceof CartographicSupport) {
852

    
853
                                                    csSym = (CartographicSupport) sym;
854
                                                    bDrawCartographicSupport = (csSym.getUnit() != -1);
855
                                            }
856

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

    
859
                                            if (!bDrawCartographicSupport) {
860
                                                    geom.drawInts(g, viewPort, sym, null);
861
                                            } else {
862
                                                    geom.drawInts(g, viewPort, dpi, (CartographicSupport) csSym, cancel);
863
                                            }
864

    
865
                                    }
866
                                    it.closeIterator();
867
                            }
868
                    } catch (ReadDriverException e) {
869
                            this.setVisible(false);
870
                            this.setActive(false);
871
                            throw e;
872
                    }
873
            }
874
    }
875

    
876

    
877
    public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
878
            double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
879
//            if (forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD) {
880
                    _print(g, viewPort, cancel, scale, properties);
881
//            } else {
882
////                    moved up to Flayers
883
////                    if (isVisible() && isWithinScale(scale)) {
884
//                            Strategy strategy = StrategyManager.getStrategy(this);
885
//
886
//                            strategy.print(g, viewPort, cancel, properties);
887
//                            ILabelingStrategy labeling;
888
//                            if ( (labeling = getLabelingStrategy() ) != null) {
889
//                                    // contains labels
890
//                                    labeling.print(g, viewPort, cancel, properties);
891
//                            }
892
////                    }
893
//            }
894
    }
895

    
896
    public void deleteSpatialIndex() {
897
        //must we delete possible spatial indexes files?
898
        spatialIndex = null;
899
    }
900

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

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

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

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

    
981
    public void createSpatialIndex() {
982
        createSpatialIndex(null);
983
    }
984

    
985
    public void process(FeatureVisitor visitor, FBitSet subset)
986
            throws ReadDriverException, ExpansionFileReadException, VisitorException {
987
        Strategy s = StrategyManager.getStrategy(this);
988
        s.process(visitor, subset);
989
    }
990

    
991
    public void process(FeatureVisitor visitor) throws ReadDriverException, VisitorException {
992
        Strategy s = StrategyManager.getStrategy(this);
993
        s.process(visitor);
994
    }
995

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

    
1002
    public FBitSet queryByRect(Rectangle2D rect) throws ReadDriverException, VisitorException {
1003
        Strategy s = StrategyManager.getStrategy(this);
1004

    
1005
        return s.queryByRect(rect);
1006
    }
1007

    
1008
    public FBitSet queryByPoint(Point2D p, double tolerance)
1009
            throws ReadDriverException, VisitorException {
1010
        Strategy s = StrategyManager.getStrategy(this);
1011
        return s.queryByPoint(p, tolerance);
1012
    }
1013

    
1014
    public FBitSet queryByShape(IGeometry g, int relationship)
1015
            throws ReadDriverException, VisitorException {
1016
        Strategy s = StrategyManager.getStrategy(this);
1017
        return s.queryByShape(g, relationship);
1018
    }
1019

    
1020
    public XMLItem[] getInfo(Point p, double tolerance, Cancellable cancel) throws ReadDriverException, VisitorException {
1021
        Point2D pReal = this.getMapContext().getViewPort().toMapPoint(p);
1022
        FBitSet bs = queryByPoint(pReal, tolerance);
1023
        VectorialXMLItem[] item = new VectorialXMLItem[1];
1024
        item[0] = new VectorialXMLItem(bs, this);
1025

    
1026
        return item;
1027
    }
1028

    
1029
    public void setLegend(IVectorLegend r) throws LegendLayerException {
1030
            if (this.legend == r){
1031
                    return;
1032
            }
1033
                if (this.legend != null && this.legend.equals(r)){
1034
                        return;
1035
                }
1036
        IVectorLegend oldLegend = legend;
1037
        legend = r;
1038
        try {
1039
            legend.setDataSource(getRecordset());
1040
        } catch (FieldNotFoundException e1) {
1041
            throw new LegendLayerException(getName(),e1);
1042
        } catch (ReadDriverException e1) {
1043
            throw new LegendLayerException(getName(),e1);
1044
        } finally{
1045
                this.updateDrawVersion();
1046
        }
1047
        if (oldLegend != null){
1048
                oldLegend.removeLegendListener(this);
1049
        }
1050
        if (legend != null){
1051
                legend.addLegendListener(this);
1052
        }
1053
        LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
1054
                oldLegend, legend);
1055
        callLegendChanged(e);
1056
    }
1057

    
1058
    /**
1059
     * Devuelve la Leyenda de la capa.
1060
     *
1061
     * @return Leyenda.
1062
     */
1063
    public ILegend getLegend() {
1064
        return legend;
1065
    }
1066

    
1067
    /**
1068
     * Devuelve el tipo de shape que contiene la capa.
1069
     *
1070
     * @return tipo de shape.
1071
     *
1072
     * @throws DriverException
1073
     */
1074
    public int getShapeType() throws ReadDriverException {
1075
        if (typeShape == -1) {
1076
            getSource().start();
1077
            typeShape = getSource().getShapeType();
1078
            getSource().stop();
1079
        }
1080

    
1081
        return typeShape;
1082
    }
1083

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

    
1119
            IVectorialDatabaseDriver dbDriver = (IVectorialDatabaseDriver) source
1120
                    .getDriver();
1121

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

    
1140
            VectorialDriver driver = source.getDriver();
1141

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

    
1169
        // properties from ILabelable
1170
        xml.putProperty("isLabeled", isLabeled);
1171
        if (strategy != null) {
1172
            XMLEntity strategyXML = strategy.getXMLEntity();
1173
            strategyXML.putProperty("Strategy", strategy.getClassName());
1174
            xml.addChild(strategy.getXMLEntity());
1175
        }
1176
        xml.addChild(getLinkProperties().getXMLEntity());
1177
        return xml;
1178
    }
1179

    
1180
    /**
1181
     * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
1182
     */
1183
    public void setXMLEntity03(XMLEntity xml) throws XMLException {
1184

    
1185
        super.setXMLEntity(xml);
1186
        legend = LegendFactory.createFromXML03(xml.getChild(0));
1187

    
1188
        try {
1189
            setLegend(legend);
1190
        } catch (LegendLayerException e) {
1191
            throw new XMLException(e);
1192
        }
1193

    
1194
        try {
1195
            getRecordset().getSelectionSupport()
1196
                    .setXMLEntity03(xml.getChild(1));
1197
        } catch (ReadDriverException e) {
1198
            e.printStackTrace();
1199
        }
1200
    }
1201

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

    
1240
                            String recordsetName = xml.getStringProperty("recordset-name");
1241

    
1242
//                            SelectableDataSource sds = new SelectableDataSource(LayerFactory
1243
//                                            .getDataSourceFactory().createRandomDataSource(
1244
//                                                            recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
1245

    
1246
                            LayerFactory.getDataSourceFactory().changeDataSourceName(
1247
                                            getSource().getRecordset().getName(), recordsetName);
1248
                            SelectableDataSource sds = new SelectableDataSource(LayerFactory
1249
                                            .getDataSourceFactory().createRandomDataSource(
1250
                                                            recordsetName, DataSourceFactory.AUTOMATIC_OPENING));
1251

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

    
1273
                    // set properties for ILabelable
1274
                    XMLEntity labelingXML = xml.firstChild("labelingStrategy", "labelingStrategy");
1275
                    if (labelingXML!= null) {
1276
                            isLabeled = true;
1277
                            try {
1278
                                    this.strategy = LabelingFactory.createStrategyFromXML(labelingXML, this);
1279
                            } catch (NotExistInXMLEntity neXMLEX) {
1280
                                    // no strategy was set, just continue;
1281
                                    logger.warn("Reached what should be unreachable code");
1282
                            }
1283
                    } else {
1284
                            isLabeled = false;
1285
                    }
1286

    
1287
                    XMLEntity xmlLinkProperties=xml.firstChild("typeChild","linkProperties");
1288
                    if (xmlLinkProperties != null){
1289
                            getLinkProperties().setXMLEntity(xmlLinkProperties);
1290
                    }
1291

    
1292
            } catch (XMLException e) {
1293
                    this.setAvailable(false);
1294
                    this.orgXMLEntity = xml;
1295
            } catch (Exception e) {
1296
                    e.printStackTrace();
1297
                    this.setAvailable(false);
1298
                    this.orgXMLEntity = xml;
1299

    
1300
            }
1301

    
1302

    
1303
    }
1304

    
1305
    public void setXMLEntityNew(XMLEntity xml) throws XMLException {
1306
        try {
1307
            super.setXMLEntity(xml);
1308

    
1309
            XMLEntity legendXML = xml.getChild(0);
1310
            IVectorLegend leg = LegendFactory.createFromXML(legendXML);
1311
            /* (jaume) begin patch;
1312
             * for backward compatibility purposes. Since gvSIG v1.1 labeling is
1313
             * no longer managed by the Legend but by the ILabelingStrategy. The
1314
             * following allows restoring older projects' labelings.
1315
             */
1316
            if (legendXML.contains("labelFieldHeight")) {
1317
                AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1318
                labeling.setLayer(this);
1319
                labeling.setTextField(legendXML.getStringProperty("labelFieldHeight"));
1320
                labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
1321
                this.setLabelingStrategy(labeling);
1322
                this.setIsLabeled(true);
1323
              }
1324
            /* end patch */
1325
            try {
1326
                getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
1327

    
1328
                this.setLoadSelection(xml.getChild(1));
1329
            } catch (ReadDriverException e1) {
1330
                this.setAvailable(false);
1331
                throw new XMLException(e1);
1332
            }
1333
            // Si tiene una uni?n, lo marcamos para que no se cree la leyenda hasta
1334
            // el final
1335
            // de la lectura del proyecto
1336
            if (xml.contains("hasJoin")) {
1337
                setIsJoined(true);
1338
                PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
1339
            } else {
1340
                this.setLoadLegend(leg);
1341
            }
1342

    
1343
        } catch (XMLException e) {
1344
            this.setAvailable(false);
1345
            this.orgXMLEntity = xml;
1346
        } catch (Exception e) {
1347
            this.setAvailable(false);
1348
            this.orgXMLEntity = xml;
1349
        }
1350

    
1351

    
1352
    }
1353

    
1354

    
1355
    /**
1356
     * Sobreimplementaci?n del m?todo toString para que las bases de datos
1357
     * identifiquen la capa.
1358
     *
1359
     * @return DOCUMENT ME!
1360
     */
1361
    public String toString() {
1362
        /*
1363
         * Se usa internamente para que la parte de datos identifique de forma
1364
         * un?voca las tablas
1365
         */
1366
        String ret = super.toString();
1367

    
1368
        return "layer" + ret.substring(ret.indexOf('@') + 1);
1369
    }
1370

    
1371
    public boolean isJoined() {
1372
        return bHasJoin;
1373
    }
1374

    
1375
    /**
1376
     * Returns if a layer is spatially indexed
1377
     *
1378
     * @return if this layer has the ability to proces spatial queries without
1379
     *         secuential scans.
1380
     */
1381
    public boolean isSpatiallyIndexed() {
1382
        ReadableVectorial source = getSource();
1383
        if (source instanceof ISpatialDB)
1384
            return true;
1385

    
1386
//FIXME azabala
1387
/*
1388
 * Esto es muy dudoso, y puede cambiar.
1389
 * Estoy diciendo que las que no son fichero o no son
1390
 * BoundedShapes estan indexadas. Esto es mentira, pero
1391
 * as? quien pregunte no querr? generar el indice.
1392
 * Esta por ver si interesa generar el indice para capas
1393
 * HSQLDB, WFS, etc.
1394
 */
1395
        if(!(source instanceof VectorialFileAdapter)){
1396
            return true;
1397
        }
1398
        if (!(source.getDriver() instanceof BoundedShapes)) {
1399
            return true;
1400
        }
1401

    
1402
        if (getISpatialIndex() != null)
1403
            return true;
1404
        return false;
1405
    }
1406

    
1407
    public void setIsJoined(boolean hasJoin) {
1408
        bHasJoin = hasJoin;
1409
    }
1410

    
1411
    /**
1412
     * @return Returns the spatialIndex.
1413
     */
1414
    public ISpatialIndex getISpatialIndex() {
1415
        return spatialIndex;
1416
    }
1417
    /**
1418
     * Sets the spatial index. This could be useful if, for some
1419
     * reasons, you want to work with a distinct spatial index
1420
     * (for example, a spatial index which could makes nearest
1421
     * neighbour querys)
1422
     * @param spatialIndex
1423
     */
1424
    public void setISpatialIndex(ISpatialIndex spatialIndex){
1425
        this.spatialIndex = spatialIndex;
1426
    }
1427

    
1428
    public SelectableDataSource getRecordset() throws ReadDriverException {
1429
        if (!this.isAvailable()) return null;
1430
        if (sds == null) {
1431

    
1432
                SelectableDataSource ds = source.getRecordset();
1433

    
1434
                if (ds == null) {
1435
                    return null;
1436
                }
1437

    
1438
                sds = ds;
1439
                sds.setSelectionSupport(selectionSupport);
1440
                selectionSupport.addSelectionListener(this);
1441

    
1442
        }
1443
        return sds;
1444
    }
1445

    
1446
    public void setEditing(boolean b) throws StartEditionLayerException {
1447
        super.setEditing(b);
1448
        try {
1449
            if (b) {
1450
                VectorialEditableAdapter vea = null;
1451
                // TODO: Qu? pasa si hay m?s tipos de adapters?
1452
                // FJP: Se podr?a pasar como argumento el
1453
                // VectorialEditableAdapter
1454
                // que se quiera usar para evitar meter c?digo aqu? de este
1455
                // estilo.
1456
                if (getSource() instanceof VectorialDBAdapter) {
1457
                    vea = new VectorialEditableDBAdapter();
1458
                } else if (this instanceof FLyrAnnotation) {
1459
                    vea = new AnnotationEditableAdapter(
1460
                            (FLyrAnnotation) this);
1461
                } else {
1462
                    vea = new VectorialEditableAdapter();
1463
                }
1464
                vea.addEditionListener(this);
1465
                vea.setOriginalVectorialAdapter(getSource());
1466
//                                azo: implementations of readablevectorial need
1467
                //references of projection and spatial index
1468
                vea.setProjection(getProjection());
1469
                vea.setSpatialIndex(spatialIndex);
1470

    
1471

    
1472
                // /vea.setSpatialIndex(getSpatialIndex());
1473
                // /vea.setFullExtent(getFullExtent());
1474
                vea.setCoordTrans(getCoordTrans());
1475
                vea.startEdition(EditionEvent.GRAPHIC);
1476
                setSource(vea);
1477
                getRecordset().setSelectionSupport(
1478
                        vea.getOriginalAdapter().getRecordset()
1479
                                .getSelectionSupport());
1480

    
1481
            } else {
1482
                VectorialEditableAdapter vea = (VectorialEditableAdapter) getSource();
1483
                vea.removeEditionListener(this);
1484
                setSource(vea.getOriginalAdapter());
1485
            }
1486
            // Si tenemos una leyenda, hay que pegarle el cambiazo a su
1487
            // recordset
1488
            setRecordset(getSource().getRecordset());
1489
            if (getLegend() instanceof IVectorLegend) {
1490
                IVectorLegend ley = (IVectorLegend) getLegend();
1491
                ley.setDataSource(getSource().getRecordset());
1492
                // Esto lo pongo para evitar que al dibujar sobre un
1493
                // dxf, dwg, o dgn no veamos nada. Es debido al checkbox
1494
                // de la leyenda de textos "dibujar solo textos".
1495
//jaume
1496
//                                if (!(getSource().getDriver() instanceof IndexedShpDriver)){
1497
//                                        FSymbol symbol=new FSymbol(getShapeType());
1498
//                                        symbol.setFontSizeInPixels(false);
1499
//                                        symbol.setFont(new Font("SansSerif", Font.PLAIN, 9));
1500
//                                        Color color=symbol.getColor();
1501
//                                        int alpha=symbol.getColor().getAlpha();
1502
//                                        if (alpha>250) {
1503
//                                                symbol.setColor(new Color(color.getRed(),color.getGreen(),color.getBlue(),100));
1504
//                                        }
1505
//                                        ley.setDefaultSymbol(symbol);
1506
//                                }
1507
//jaume//
1508
                ley.useDefaultSymbol(true);
1509
            }
1510
        } catch (ReadDriverException e) {
1511
            throw new StartEditionLayerException(getName(),e);
1512
        } catch (FieldNotFoundException e) {
1513
            throw new StartEditionLayerException(getName(),e);
1514
        } catch (StartWriterVisitorException e) {
1515
            throw new StartEditionLayerException(getName(),e);
1516
        }
1517

    
1518
        setSpatialCacheEnabled(b);
1519
        callEditionChanged(LayerEvent
1520
                .createEditionChangedEvent(this, "edition"));
1521

    
1522
    }
1523

    
1524
    /**
1525
     * Para cuando haces una uni?n, sustituyes el recorset por el nuevo. De esta
1526
     * forma, podr?s poner leyendas basadas en el nuevo recordset
1527
     *
1528
     * @param newSds
1529
     */
1530
    public void setRecordset(SelectableDataSource newSds) {
1531
            // TODO: Deberiamos hacer comprobaciones del cambio
1532
        sds = newSds;
1533
        sds.setSelectionSupport(selectionSupport);
1534
                selectionSupport.addSelectionListener(this);
1535
                this.updateDrawVersion();
1536
    }
1537

    
1538
    public void clearSpatialCache()
1539
    {
1540
        spatialCache.clearAll();
1541
    }
1542

    
1543
    public boolean isSpatialCacheEnabled() {
1544
        return spatialCacheEnabled;
1545
    }
1546

    
1547
    public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
1548
        this.spatialCacheEnabled = spatialCacheEnabled;
1549
    }
1550

    
1551
    public SpatialCache getSpatialCache() {
1552
        return spatialCache;
1553
    }
1554

    
1555
    /**
1556
     * Siempre es un numero mayor de 1000
1557
     * @param maxFeatures
1558
     */
1559
    public void setMaxFeaturesInEditionCache(int maxFeatures) {
1560
        if (maxFeatures > spatialCache.maxFeatures)
1561
            spatialCache.setMaxFeatures(maxFeatures);
1562

    
1563
    }
1564

    
1565
    /**
1566
     * This method returns a boolean that is used by the FPopMenu
1567
     * to make visible the properties menu or not. It is visible by
1568
     * default, and if a later don't have to show this menu only
1569
     * has to override this method.
1570
     * @return
1571
     * If the properties menu is visible (or not)
1572
     */
1573
    public boolean isPropertiesMenuVisible(){
1574
        return true;
1575
    }
1576

    
1577
    public void reload() throws ReloadLayerException {
1578
        this.setAvailable(true);
1579
        super.reload();
1580
        this.updateDrawVersion();
1581
        try {
1582
            this.source.getDriver().reload();
1583
            if (this.getLegend() == null) {
1584
                if (this.getRecordset().getDriver() instanceof WithDefaultLegend) {
1585
                    WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset().getDriver();
1586
                    this.setLegend((IVectorLegend) aux.getDefaultLegend());
1587
                    this.setLabelingStrategy(aux.getDefaultLabelingStrategy());
1588
                } else {
1589
                    this.setLegend(LegendFactory.createSingleSymbolLegend(
1590
                            this.getShapeType()));
1591
                }
1592
            }
1593

    
1594
        } catch (LegendLayerException e) {
1595
            this.setAvailable(false);
1596
            throw new ReloadLayerException(getName(),e);
1597
        } catch (ReadDriverException e) {
1598
            this.setAvailable(false);
1599
            throw new ReloadLayerException(getName(),e);
1600
        }
1601

    
1602
    }
1603

    
1604
    protected void setLoadSelection(XMLEntity xml) {
1605
        this.loadSelection = xml;
1606
    }
1607

    
1608
    protected void setLoadLegend(IVectorLegend legend) {
1609
        this.loadLegend = legend;
1610
    }
1611

    
1612
    protected void putLoadSelection() throws XMLException {
1613
        if (this.loadSelection == null) return;
1614
        try {
1615
            this.getRecordset().getSelectionSupport().setXMLEntity(this.loadSelection);
1616
        } catch (ReadDriverException e) {
1617
            throw new XMLException(e);
1618
        }
1619
        this.loadSelection = null;
1620

    
1621
    }
1622
    protected void putLoadLegend() throws LegendLayerException {
1623
        if (this.loadLegend == null) return;
1624
        this.setLegend(this.loadLegend);
1625
        this.loadLegend = null;
1626
    }
1627

    
1628
    protected void cleanLoadOptions() {
1629
        this.loadLegend = null;
1630
        this.loadSelection = null;
1631
    }
1632

    
1633
    public boolean isWritable() {
1634
        VectorialDriver drv = getSource().getDriver();
1635
        if (!drv.isWritable())
1636
            return false;
1637
        if (drv instanceof IWriteable)
1638
        {
1639
            IWriter writer = ((IWriteable)drv).getWriter();
1640
            if (writer != null)
1641
            {
1642
                if (writer instanceof ISpatialWriter)
1643
                    return true;
1644
            }
1645
        }
1646
        return false;
1647

    
1648
    }
1649

    
1650
    public FLayer cloneLayer() throws Exception {
1651
        FLyrVect clonedLayer = new FLyrVect();
1652
        clonedLayer.setSource(getSource());
1653
        if (isJoined()) {
1654
                        clonedLayer.setIsJoined(true);
1655
                        clonedLayer.setRecordset(getRecordset());
1656
                }
1657
        clonedLayer.setVisible(isVisible());
1658
        clonedLayer.setISpatialIndex(getISpatialIndex());
1659
        clonedLayer.setName(getName());
1660
        clonedLayer.setCoordTrans(getCoordTrans());
1661

    
1662
        clonedLayer.setLegend((IVectorLegend)getLegend().cloneLegend());
1663

    
1664
        clonedLayer.setIsLabeled(isLabeled());
1665
        clonedLayer.setLabelingStrategy(getLabelingStrategy());
1666

    
1667
        return clonedLayer;
1668
    }
1669

    
1670

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

    
1675
    private boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, IGeometry geom, int[] xyCoords) {
1676
            boolean onePoint = false;
1677
            int type=geom.getGeometryType() % FShape.Z;
1678
            if (type!=FShape.POINT && type!=FShape.MULTIPOINT && type!=FShape.NULL) {
1679

    
1680
                        Rectangle2D geomBounds = geom.getBounds2D();
1681

    
1682
                        ICoordTrans ct = getCoordTrans();
1683

    
1684
                        if (ct!=null) {
1685
//                                geomBounds = ct.getInverted().convert(geomBounds);
1686
                                geomBounds = ct.convert(geomBounds);
1687
                        }
1688

    
1689
                        double dist1Pixel = viewPort.getDist1pixel();
1690

    
1691
                        onePoint = (geomBounds.getWidth()  <= dist1Pixel
1692
                                         && geomBounds.getHeight() <= dist1Pixel);
1693

    
1694
                        if (onePoint) {
1695
                                // avoid out of range exceptions
1696
                                FPoint2D p = new FPoint2D(geomBounds.getMinX(), geomBounds.getMinY());
1697
                                p.transform(viewPort.getAffineTransform());
1698
                                p.transform(graphicsTransform);
1699
                                xyCoords[0] = (int) p.getX();
1700
                                xyCoords[1] = (int) p.getY();
1701

    
1702
                        }
1703

    
1704
                }
1705
            return onePoint;
1706
    }
1707
    /*
1708
     * jaume. Stuff from ILabeled.
1709
     */
1710
    private boolean isLabeled;
1711
    private ILabelingStrategy strategy;
1712

    
1713
    public boolean isLabeled() {
1714
        return isLabeled;
1715
    }
1716

    
1717
    public void setIsLabeled(boolean isLabeled) {
1718
        this.isLabeled = isLabeled;
1719
    }
1720

    
1721
    public ILabelingStrategy getLabelingStrategy() {
1722
        return strategy;
1723
    }
1724

    
1725
    public void setLabelingStrategy(ILabelingStrategy strategy) {
1726
        this.strategy = strategy;
1727
        try {
1728
                        strategy.setLayer(this);
1729
                } catch (ReadDriverException e) {
1730
                        // TODO Auto-generated catch block
1731
                        e.printStackTrace();
1732
                }
1733
    }
1734

    
1735
    public void drawLabels(BufferedImage image, Graphics2D g, ViewPort viewPort,
1736
                    Cancellable cancel, double scale, double dpi) throws ReadDriverException {
1737
        if (strategy!=null && isWithinScale(scale)) {
1738
                strategy.draw(image, g, viewPort, cancel, dpi);
1739
        }
1740
    }
1741
    public void printLabels(Graphics2D g, ViewPort viewPort,
1742
                    Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
1743
        if (strategy!=null) {
1744
                strategy.print(g, viewPort, cancel, properties);
1745
        }
1746
    }
1747

    
1748

    
1749
    //M?todos para el uso de HyperLinks en capas FLyerVect
1750

    
1751
    /**
1752
     * Return true, because a Vectorial Layer supports HyperLink
1753
     */
1754
    public boolean allowLinks()
1755
    {
1756
            return true;
1757
    }
1758

    
1759
    /**
1760
         * Returns an instance of AbstractLinkProperties that contains the information
1761
         * of the HyperLink
1762
         * @return Abstra
1763
         */
1764
    public AbstractLinkProperties getLinkProperties()
1765
    {
1766
            return linkProperties;
1767
    }
1768

    
1769
    /**
1770
         * Provides an array with URIs. Returns one URI by geometry that includes the point
1771
         * in its own geometry limits with a allowed tolerance.
1772
         * @param layer, the layer
1773
         * @param point, the point to check that is contained or not in the geometries in the layer
1774
         * @param tolerance, the tolerance allowed. Allowed margin of error to detect if the  point
1775
         *                 is contained in some geometries of the layer
1776
         * @return
1777
         */
1778
    public URI[] getLink(Point2D point, double tolerance)
1779
    {
1780
            //return linkProperties.getLink(this)
1781
            return linkProperties.getLink(this,point,tolerance);
1782
    }
1783
//    /**
1784
//     * @deprecated Don?t use Strategy, you should be use iterators.
1785
//     */
1786
//        public boolean isUseStrategy() {
1787
//                return useStrategy;
1788
//        }
1789
//        /**
1790
//     * @deprecated Don?t use Strategy, you should be use iterators.
1791
//     */
1792
//        public void setUseStrategy(boolean useStrategy) {
1793
//                this.useStrategy = useStrategy;
1794
//        }
1795
//
1796
//        @Override
1797
//        public void load() throws LoadLayerException {
1798
//                super.load();
1799
//                useStrategy=forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD;
1800
//        }
1801

    
1802
        public void selectionChanged(SelectionEvent e) {
1803
                this.updateDrawVersion();
1804
        }
1805

    
1806
        public void afterFieldEditEvent(AfterFieldEditEvent e) {
1807
                this.updateDrawVersion();
1808
        }
1809

    
1810
        public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) {
1811
                this.updateDrawVersion();
1812

    
1813
        }
1814

    
1815
        public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
1816

    
1817
        }
1818

    
1819
        public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
1820

    
1821
        }
1822

    
1823
        public void processEvent(EditionEvent e) {
1824
                if (e.getChangeType()== e.ROW_EDITION){
1825
                        this.updateDrawVersion();
1826
                }
1827

    
1828
        }
1829

    
1830
        public void legendCleared(LegendClearEvent event) {
1831
                this.updateDrawVersion();
1832
        LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
1833
                legend, legend);
1834
        this.callLegendChanged(e);
1835
        }
1836

    
1837
        public boolean symbolChanged(SymbolLegendEvent e) {
1838
                this.updateDrawVersion();
1839
        LegendChangedEvent event = LegendChangedEvent.createLegendChangedEvent(
1840
                legend, legend);
1841
        this.callLegendChanged(event);
1842
        return true;
1843
        }
1844

    
1845
 }