Statistics
| Revision:

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

History | View | Annotate | Download (68.5 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.fmap.layers;
42

    
43
import java.awt.Graphics2D;
44
import java.awt.Point;
45
import java.awt.geom.AffineTransform;
46
import java.awt.geom.Point2D;
47
import java.awt.geom.Rectangle2D;
48
import java.awt.image.BufferedImage;
49
import java.io.File;
50
import java.net.URI;
51
import java.util.ArrayList;
52

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

    
56
import org.apache.log4j.Logger;
57
import org.cresques.cts.ICoordTrans;
58
import org.gvsig.exceptions.BaseException;
59

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

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

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

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

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

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

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

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

    
201

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

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

    
243
    }
244

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

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

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

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

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

    
322
            return rAux;
323
    }
324

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

    
344

    
345

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

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

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

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

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

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

    
377
                            boolean bSymbolLevelError = false;
378

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

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

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

    
403

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

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

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

    
419
                                    if (sym == null) continue;
420

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
583

    
584
            }
585
    }
586

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

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

    
631
    }
632

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

    
637

    
638
                    /* SVN */
639

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

645

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

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

658

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

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

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

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

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

686

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

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

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

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

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

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

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

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

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

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

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

    
762

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

    
769

    
770
            if (bDrawShapes) {
771

    
772
                    try {
773
                            double dpi = 72;
774

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

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

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

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

    
808

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

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

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

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

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

    
862
                                                    csSym = (CartographicSupport) sym;
863
                                            }
864

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

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

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

    
884

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1034
        return item;
1035
    }
1036

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

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

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

    
1090
        return typeShape;
1091
    }
1092

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

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

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

    
1149
            VectorialDriver driver = source.getDriver();
1150

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

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

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

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

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

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

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

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

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

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

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

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

    
1266
                    //Por compatibilidad con proyectos anteriores a la 1.0
1267
                    boolean containsIsLabeled = xml.contains("isLabeled");
1268
                    if (containsIsLabeled){
1269
                            isLabeled = xml.getBooleanProperty("isLabeled");
1270
                    }
1271
                    // set properties for ILabelable
1272
                    XMLEntity labelingXML = xml.firstChild("labelingStrategy", "labelingStrategy");
1273
                    if (labelingXML!= null) {
1274
                            if(!containsIsLabeled){
1275
                                    isLabeled = true;
1276
                            }
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 if (legendXML.contains("labelFieldName")|| legendXML.contains("labelfield")) {
1284
                            /* (jaume) begin patch;
1285
                         * for backward compatibility purposes. Since gvSIG v1.1 labeling is
1286
                         * no longer managed by the Legend but by the ILabelingStrategy. The
1287
                         * following allows restoring older projects' labelings.
1288
                         */
1289
                            String labelTextField =        null;
1290
                            if (legendXML.contains("labelFieldName")){
1291
                                    labelTextField = legendXML.getStringProperty("labelFieldName");
1292
                                    if (labelTextField != null) {
1293
                                            AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1294
                                            labeling.setLayer(this);
1295
                                            labeling.setUsesFixedSize(true);
1296
                                            labeling.setFixedSize(10);
1297
                                            labeling.setTextField(labelTextField);
1298
                                            labeling.setHeightField(legendXML.getStringProperty("labelHeightFieldName"));
1299
                                            labeling.setRotationField(legendXML.getStringProperty("labelRotationFieldName"));
1300
                                            this.setLabelingStrategy(labeling);
1301
                                            this.setIsLabeled(true);
1302
                                    }
1303
                            }else{
1304
                                    labelTextField = legendXML.getStringProperty("labelfield");
1305
                                    if (labelTextField != null) {
1306
                                            AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1307
                                            labeling.setLayer(this);
1308
                                            labeling.setUsesFixedSize(true);
1309
                                            labeling.setFixedSize(10);
1310
                                            labeling.setTextField(labelTextField);
1311
                                            labeling.setHeightField(legendXML.getStringProperty("labelFieldHeight"));
1312
                                            labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
1313
                                            this.setLabelingStrategy(labeling);
1314
                                            this.setIsLabeled(true);
1315
                                    }
1316
                            }
1317

    
1318
                    }else if(!containsIsLabeled){
1319
                            isLabeled = false;
1320
                    }
1321

    
1322
                    // compatibility with hyperlink from 1.9 alpha version... do we really need to be compatible with alpha versions??
1323
                    XMLEntity xmlLinkProperties=xml.firstChild("typeChild", "linkProperties");
1324
                    if (xmlLinkProperties != null){
1325
                            try {
1326
                                    String fieldName=xmlLinkProperties.getStringProperty("fieldName");
1327
                                    xmlLinkProperties.remove("fieldName");
1328
                                    String extName = xmlLinkProperties.getStringProperty("extName");
1329
                                    xmlLinkProperties.remove("extName");
1330
                                    int typeLink = xmlLinkProperties.getIntProperty("typeLink");
1331
                                    xmlLinkProperties.remove("typeLink");
1332
                                    if (fieldName!=null) {
1333
                                            setProperty("legacy.hyperlink.selectedField", fieldName);
1334
                                            setProperty("legacy.hyperlink.type", new Integer(typeLink));
1335
                                            if (extName!=null) {
1336
                                                    setProperty("legacy.hyperlink.extension", extName);
1337
                                            }
1338
                                    }
1339
                            }
1340
                            catch (NotExistInXMLEntity ex) {
1341
                                    logger.warn("Error getting old hyperlink configuration", ex);
1342
                            }
1343
                    }
1344

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

    
1353
            }
1354

    
1355

    
1356
    }
1357

    
1358
    public void setXMLEntityNew(XMLEntity xml) throws XMLException {
1359
        try {
1360
            super.setXMLEntity(xml);
1361

    
1362
            XMLEntity legendXML = xml.getChild(0);
1363
            IVectorLegend leg = LegendFactory.createFromXML(legendXML);
1364
            /* (jaume) begin patch;
1365
             * for backward compatibility purposes. Since gvSIG v1.1 labeling is
1366
             * no longer managed by the Legend but by the ILabelingStrategy. The
1367
             * following allows restoring older projects' labelings.
1368
             */
1369
            if (legendXML.contains("labelFieldHeight")) {
1370
                AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
1371
                labeling.setLayer(this);
1372
                labeling.setTextField(legendXML.getStringProperty("labelFieldHeight"));
1373
                labeling.setRotationField(legendXML.getStringProperty("labelFieldRotation"));
1374
                this.setLabelingStrategy(labeling);
1375
                this.setIsLabeled(true);
1376
              }
1377
            /* end patch */
1378
            try {
1379
                getRecordset().getSelectionSupport().setXMLEntity(xml.getChild(1));
1380

    
1381
                this.setLoadSelection(xml.getChild(1));
1382
            } catch (ReadDriverException e1) {
1383
                this.setAvailable(false);
1384
                throw new XMLException(e1);
1385
            }
1386
            // Si tiene una uni?n, lo marcamos para que no se cree la leyenda hasta
1387
            // el final
1388
            // de la lectura del proyecto
1389
            if (xml.contains("hasJoin")) {
1390
                setIsJoined(true);
1391
                PostProcessSupport.addToPostProcess(this, "setLegend", leg, 1);
1392
            } else {
1393
                this.setLoadLegend(leg);
1394
            }
1395

    
1396
        } catch (XMLException e) {
1397
            this.setAvailable(false);
1398
            this.orgXMLEntity = xml;
1399
        } catch (Exception e) {
1400
            this.setAvailable(false);
1401
            this.orgXMLEntity = xml;
1402
        }
1403

    
1404

    
1405
    }
1406

    
1407

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

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

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

    
1428
    /**
1429
     * Returns if a layer is spatially indexed
1430
     *
1431
     * @return if this layer has the ability to proces spatial queries without
1432
     *         secuential scans.
1433
     */
1434
    public boolean isSpatiallyIndexed() {
1435
        ReadableVectorial source = getSource();
1436
        if (source instanceof ISpatialDB)
1437
            return true;
1438

    
1439
//FIXME azabala
1440
/*
1441
 * Esto es muy dudoso, y puede cambiar.
1442
 * Estoy diciendo que las que no son fichero o no son
1443
 * BoundedShapes estan indexadas. Esto es mentira, pero
1444
 * as? quien pregunte no querr? generar el indice.
1445
 * Esta por ver si interesa generar el indice para capas
1446
 * HSQLDB, WFS, etc.
1447
 */
1448
        if(!(source instanceof VectorialFileAdapter)){
1449
            return true;
1450
        }
1451
        if (!(source.getDriver() instanceof BoundedShapes)) {
1452
            return true;
1453
        }
1454

    
1455
        if (getISpatialIndex() != null)
1456
            return true;
1457
        return false;
1458
    }
1459

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

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

    
1481
    public SelectableDataSource getRecordset() throws ReadDriverException {
1482
        if (!this.isAvailable()) return null;
1483
        if (sds == null) {
1484

    
1485
                SelectableDataSource ds = source.getRecordset();
1486

    
1487
                if (ds == null) {
1488
                    return null;
1489
                }
1490

    
1491
                sds = ds;
1492
                sds.setSelectionSupport(selectionSupport);
1493
                selectionSupport.addSelectionListener(this);
1494

    
1495
        }
1496
        return sds;
1497
    }
1498

    
1499
    public void setEditing(boolean b) throws StartEditionLayerException {
1500
        super.setEditing(b);
1501
        try {
1502
            if (b) {
1503
                VectorialEditableAdapter vea = null;
1504
                // TODO: Qu? pasa si hay m?s tipos de adapters?
1505
                // FJP: Se podr?a pasar como argumento el
1506
                // VectorialEditableAdapter
1507
                // que se quiera usar para evitar meter c?digo aqu? de este
1508
                // estilo.
1509
                if (getSource() instanceof VectorialDBAdapter) {
1510
                    vea = new VectorialEditableDBAdapter();
1511
                } else if (this instanceof FLyrAnnotation) {
1512
                    vea = new AnnotationEditableAdapter(
1513
                            (FLyrAnnotation) this);
1514
                } else {
1515
                    vea = new VectorialEditableAdapter();
1516
                }
1517
                vea.addEditionListener(this);
1518
                vea.setOriginalVectorialAdapter(getSource());
1519
//                                azo: implementations of readablevectorial need
1520
                //references of projection and spatial index
1521
                vea.setProjection(getProjection());
1522
                vea.setSpatialIndex(spatialIndex);
1523

    
1524

    
1525
                // /vea.setSpatialIndex(getSpatialIndex());
1526
                // /vea.setFullExtent(getFullExtent());
1527
                vea.setCoordTrans(getCoordTrans());
1528
                vea.startEdition(EditionEvent.GRAPHIC);
1529
                setSource(vea);
1530
                getRecordset().setSelectionSupport(
1531
                        vea.getOriginalAdapter().getRecordset()
1532
                                .getSelectionSupport());
1533

    
1534
            } else {
1535
                VectorialEditableAdapter vea = (VectorialEditableAdapter) getSource();
1536
                vea.removeEditionListener(this);
1537
                setSource(vea.getOriginalAdapter());
1538
            }
1539
            // Si tenemos una leyenda, hay que pegarle el cambiazo a su
1540
            // recordset
1541
            setRecordset(getSource().getRecordset());
1542
            if (getLegend() instanceof IVectorLegend) {
1543
                IVectorLegend ley = (IVectorLegend) getLegend();
1544
                ley.setDataSource(getSource().getRecordset());
1545
                // Esto lo pongo para evitar que al dibujar sobre un
1546
                // dxf, dwg, o dgn no veamos nada. Es debido al checkbox
1547
                // de la leyenda de textos "dibujar solo textos".
1548
//jaume
1549
//                                if (!(getSource().getDriver() instanceof IndexedShpDriver)){
1550
//                                        FSymbol symbol=new FSymbol(getShapeType());
1551
//                                        symbol.setFontSizeInPixels(false);
1552
//                                        symbol.setFont(new Font("SansSerif", Font.PLAIN, 9));
1553
//                                        Color color=symbol.getColor();
1554
//                                        int alpha=symbol.getColor().getAlpha();
1555
//                                        if (alpha>250) {
1556
//                                                symbol.setColor(new Color(color.getRed(),color.getGreen(),color.getBlue(),100));
1557
//                                        }
1558
//                                        ley.setDefaultSymbol(symbol);
1559
//                                }
1560
//jaume//
1561
                ley.useDefaultSymbol(true);
1562
            }
1563
        } catch (ReadDriverException e) {
1564
            throw new StartEditionLayerException(getName(),e);
1565
        } catch (FieldNotFoundException e) {
1566
            throw new StartEditionLayerException(getName(),e);
1567
        } catch (StartWriterVisitorException e) {
1568
            throw new StartEditionLayerException(getName(),e);
1569
        }
1570

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

    
1575
    }
1576

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

    
1591
    public void clearSpatialCache()
1592
    {
1593
        spatialCache.clearAll();
1594
    }
1595

    
1596
    public boolean isSpatialCacheEnabled() {
1597
        return spatialCacheEnabled;
1598
    }
1599

    
1600
    public void setSpatialCacheEnabled(boolean spatialCacheEnabled) {
1601
        this.spatialCacheEnabled = spatialCacheEnabled;
1602
    }
1603

    
1604
    public SpatialCache getSpatialCache() {
1605
        return spatialCache;
1606
    }
1607

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

    
1616
    }
1617

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

    
1630
    public void reload() throws ReloadLayerException {
1631
        this.setAvailable(true);
1632
        super.reload();
1633
        this.updateDrawVersion();
1634
        try {
1635
            this.source.getDriver().reload();
1636
            if (this.getLegend() == null) {
1637
                if (this.getRecordset().getDriver() instanceof WithDefaultLegend) {
1638
                    WithDefaultLegend aux = (WithDefaultLegend) this.getRecordset().getDriver();
1639
                    this.setLegend((IVectorLegend) aux.getDefaultLegend());
1640
                    this.setLabelingStrategy(aux.getDefaultLabelingStrategy());
1641
                } else {
1642
                    this.setLegend(LegendFactory.createSingleSymbolLegend(
1643
                            this.getShapeType()));
1644
                }
1645
            }
1646

    
1647
        } catch (LegendLayerException e) {
1648
            this.setAvailable(false);
1649
            throw new ReloadLayerException(getName(),e);
1650
        } catch (ReadDriverException e) {
1651
            this.setAvailable(false);
1652
            throw new ReloadLayerException(getName(),e);
1653
        }
1654

    
1655
    }
1656

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

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

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

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

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

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

    
1701
    }
1702

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

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

    
1717
        clonedLayer.setIsLabeled(isLabeled());
1718
        ILabelingStrategy labelingStrategy=getLabelingStrategy();
1719
        if (labelingStrategy!=null)
1720
                clonedLayer.setLabelingStrategy(labelingStrategy);
1721

    
1722
        return clonedLayer;
1723
    }
1724

    
1725

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

    
1730
    private boolean isOnePoint(AffineTransform graphicsTransform, ViewPort viewPort, IGeometry geom, int[] xyCoords) {
1731
            boolean onePoint = false;
1732
            int type=geom.getGeometryType() % FShape.Z;
1733
            if (type!=FShape.POINT && type!=FShape.MULTIPOINT && type!=FShape.NULL) {
1734

    
1735
                        Rectangle2D geomBounds = geom.getBounds2D();
1736

    
1737
                //        ICoordTrans ct = getCoordTrans();
1738

    
1739
                        // Se supone que la geometria ya esta
1740
                        // repoyectada y no hay que hacer
1741
                        // ninguna transformacion
1742
//                        if (ct!=null) {
1743
////                                geomBounds = ct.getInverted().convert(geomBounds);
1744
//                                geomBounds = ct.convert(geomBounds);
1745
//                        }
1746

    
1747
                        double dist1Pixel = viewPort.getDist1pixel();
1748

    
1749
                        onePoint = (geomBounds.getWidth()  <= dist1Pixel
1750
                                         && geomBounds.getHeight() <= dist1Pixel);
1751

    
1752
                        if (onePoint) {
1753
                                // avoid out of range exceptions
1754
                                FPoint2D p = new FPoint2D(geomBounds.getMinX(), geomBounds.getMinY());
1755
                                p.transform(viewPort.getAffineTransform());
1756
                                p.transform(graphicsTransform);
1757
                                xyCoords[0] = (int) p.getX();
1758
                                xyCoords[1] = (int) p.getY();
1759

    
1760
                        }
1761

    
1762
                }
1763
            return onePoint;
1764
    }
1765
    /*
1766
     * jaume. Stuff from ILabeled.
1767
     */
1768
    private boolean isLabeled;
1769
    private ILabelingStrategy strategy;
1770

    
1771
    public boolean isLabeled() {
1772
        return isLabeled;
1773
    }
1774

    
1775
    public void setIsLabeled(boolean isLabeled) {
1776
        this.isLabeled = isLabeled;
1777
    }
1778

    
1779
    public ILabelingStrategy getLabelingStrategy() {
1780
        return strategy;
1781
    }
1782

    
1783
    public void setLabelingStrategy(ILabelingStrategy strategy) {
1784
        this.strategy = strategy;
1785
        try {
1786
                        strategy.setLayer(this);
1787
                } catch (ReadDriverException e) {
1788
                        // TODO Auto-generated catch block
1789
                        e.printStackTrace();
1790
                }
1791
    }
1792

    
1793
    public void drawLabels(BufferedImage image, Graphics2D g, ViewPort viewPort,
1794
                    Cancellable cancel, double scale, double dpi) throws ReadDriverException {
1795
        if (strategy!=null && isWithinScale(scale)) {
1796
                strategy.draw(image, g, viewPort, cancel, dpi);
1797
        }
1798
    }
1799
    public void printLabels(Graphics2D g, ViewPort viewPort,
1800
                    Cancellable cancel, double scale, PrintRequestAttributeSet properties) throws ReadDriverException {
1801
        if (strategy!=null) {
1802
                strategy.print(g, viewPort, cancel, properties);
1803
        }
1804
    }
1805

    
1806

    
1807
    //M?todos para el uso de HyperLinks en capas FLyerVect
1808

    
1809
    /**
1810
     * Return true, because a Vectorial Layer supports HyperLink
1811
     */
1812
    public boolean allowLinks()
1813
    {
1814
            return true;
1815
    }
1816

    
1817
    /**
1818
         * Returns an instance of AbstractLinkProperties that contains the information
1819
         * of the HyperLink
1820
         * @return Abstra
1821
         */
1822
    public AbstractLinkProperties getLinkProperties()
1823
    {
1824
            return linkProperties;
1825
    }
1826

    
1827
    /**
1828
         * Provides an array with URIs. Returns one URI by geometry that includes the point
1829
         * in its own geometry limits with a allowed tolerance.
1830
         * @param layer, the layer
1831
         * @param point, the point to check that is contained or not in the geometries in the layer
1832
         * @param tolerance, the tolerance allowed. Allowed margin of error to detect if the  point
1833
         *                 is contained in some geometries of the layer
1834
         * @return
1835
         */
1836
    public URI[] getLink(Point2D point, double tolerance)
1837
    {
1838
            //return linkProperties.getLink(this)
1839
            return linkProperties.getLink(this,point,tolerance);
1840
    }
1841
//    /**
1842
//     * @deprecated Don?t use Strategy, you should be use iterators.
1843
//     */
1844
//        public boolean isUseStrategy() {
1845
//                return useStrategy;
1846
//        }
1847
//        /**
1848
//     * @deprecated Don?t use Strategy, you should be use iterators.
1849
//     */
1850
//        public void setUseStrategy(boolean useStrategy) {
1851
//                this.useStrategy = useStrategy;
1852
//        }
1853
//
1854
//        @Override
1855
//        public void load() throws LoadLayerException {
1856
//                super.load();
1857
//                useStrategy=forTestOnlyVariableUseIterators_REMOVE_THIS_FIELD;
1858
//        }
1859

    
1860
        public void selectionChanged(SelectionEvent e) {
1861
                this.updateDrawVersion();
1862
        }
1863

    
1864
        public void afterFieldEditEvent(AfterFieldEditEvent e) {
1865
                this.updateDrawVersion();
1866
        }
1867

    
1868
        public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) {
1869
                this.updateDrawVersion();
1870

    
1871
        }
1872

    
1873
        public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
1874

    
1875
        }
1876

    
1877
        public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
1878

    
1879
        }
1880

    
1881
        public void processEvent(EditionEvent e) {
1882
                if (e.getChangeType()== e.ROW_EDITION){
1883
                        this.updateDrawVersion();
1884
                }
1885

    
1886
        }
1887

    
1888
        public void legendCleared(LegendClearEvent event) {
1889
                this.updateDrawVersion();
1890
        LegendChangedEvent e = LegendChangedEvent.createLegendChangedEvent(
1891
                legend, legend);
1892
        this.callLegendChanged(e);
1893
        }
1894

    
1895
        public boolean symbolChanged(SymbolLegendEvent e) {
1896
                this.updateDrawVersion();
1897
        LegendChangedEvent event = LegendChangedEvent.createLegendChangedEvent(
1898
                legend, legend);
1899
        this.callLegendChanged(event);
1900
        return true;
1901
        }
1902
        public String getTypeStringVectorLayer() throws ReadDriverException {
1903
                String typeString="";
1904
                int typeShape=((FLyrVect)this).getShapeType();
1905
                if (FShape.MULTI==typeShape){
1906
                        ReadableVectorial rv=((FLyrVect)this).getSource();
1907
                        if (rv.getShapeCount()>0){
1908
                                if ((rv.getShape(0).getGeometryType() & FShape.Z) == FShape.Z){
1909
                                        typeString="Geometries3D";
1910
                                }else{
1911
                                        typeString="Geometries2D";
1912
                                 }
1913
                         }
1914
                }else{
1915
                        ReadableVectorial rv=((FLyrVect)this).getSource();
1916
                        if (rv.getShapeCount()>0){
1917
                                int type=rv.getShape(0).getGeometryType();
1918
                                if (FShape.POINT == type){
1919
                                        typeString="Point2D";
1920
                                } else if (FShape.LINE == type){
1921
                                        typeString="Line2D";
1922
                                } else if (FShape.POLYGON == type){
1923
                                        typeString="Polygon2D";
1924
                                } else if (FShape.MULTIPOINT == type){
1925
                                        typeString="MultiPint2D";
1926
                                } else if ((FShape.POINT | FShape.Z)  == type ){
1927
                                        typeString="Point3D";
1928
                                } else if ((FShape.LINE | FShape.Z)  == type ){
1929
                                        typeString="Line3D";
1930
                                } else if ((FShape.POLYGON | FShape.Z)  == type ){
1931
                                        typeString="Polygon3D";
1932
                                } else if ((FShape.MULTIPOINT | FShape.Z)  == type ){
1933
                                        typeString="MultiPoint3D";
1934
                                } else if ((FShape.POINT | FShape.M)  == type ){
1935
                                        typeString="PointM";
1936
                                } else if ((FShape.LINE | FShape.M)  == type ){
1937
                                        typeString="LineM";
1938
                                } else if ((FShape.POLYGON | FShape.M)  == type ){
1939
                                        typeString="PolygonM";
1940
                                } else if ((FShape.MULTIPOINT | FShape.M)  == type ){
1941
                                        typeString="MultiPointM";
1942
                                } else if ((FShape.MULTI | FShape.M)  == type ){
1943
                                        typeString="M";
1944
                                }
1945
                        }
1946
                        return typeString;
1947
                }
1948
                return "";
1949
        }
1950
        public int getTypeIntVectorLayer() throws ReadDriverException {
1951
                int typeInt=0;
1952
                int typeShape=((FLyrVect)this).getShapeType();
1953
                if (FShape.MULTI==typeShape){
1954
                        ReadableVectorial rv=((FLyrVect)this).getSource();
1955
                        if (rv.getShapeCount()>0){
1956
                                if ((rv.getShape(0).getGeometryType() & FShape.Z) == FShape.Z){
1957
                                        typeInt=FShape.MULTI | FShape.Z;
1958
                                }else{
1959
                                        typeInt=FShape.MULTI;
1960
                                }
1961
                        }
1962
                }else{
1963
                        ReadableVectorial rv=((FLyrVect)this).getSource();
1964
                        if (rv.getShapeCount()>0){
1965
                                int type=rv.getShape(0).getGeometryType();
1966
                                typeInt=type;
1967
                        }
1968
                        return typeInt;
1969
                }
1970
                return typeInt;
1971
        }
1972
 }