Statistics
| Revision:

root / tags / v1_0_2_Build_907 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / operations / strategies / ShpStrategy.java @ 11015

History | View | Annotate | Download (23.2 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.operations.strategies;
42

    
43
import java.awt.Graphics2D;
44
import java.awt.geom.Point2D;
45
import java.awt.geom.Rectangle2D;
46
import java.awt.image.BufferedImage;
47
import java.io.IOException;
48
import java.util.BitSet;
49
import java.util.List;
50

    
51
import javax.print.attribute.PrintRequestAttributeSet;
52

    
53
import org.apache.log4j.Logger;
54
import org.cresques.cts.ICoordTrans;
55
import org.geotools.resources.geometry.XRectangle2D;
56

    
57
import com.hardcode.driverManager.DriverLoadException;
58
import com.iver.cit.gvsig.fmap.DriverException;
59
import com.iver.cit.gvsig.fmap.ViewPort;
60
import com.iver.cit.gvsig.fmap.core.FShape;
61
import com.iver.cit.gvsig.fmap.core.IGeometry;
62
import com.iver.cit.gvsig.fmap.core.ISymbol;
63
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
64
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
65
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
66
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
67
import com.iver.cit.gvsig.fmap.layers.FBitSet;
68
import com.iver.cit.gvsig.fmap.layers.FLayer;
69
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
70
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
71
import com.iver.cit.gvsig.fmap.layers.SpatialCache;
72
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
73
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
74
import com.iver.cit.gvsig.fmap.layers.layerOperations.Selectable;
75
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
76
import com.iver.cit.gvsig.fmap.rendering.ClassifiedLegendInfo;
77
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
78
import com.iver.utiles.swing.threads.Cancellable;
79
import com.iver.utiles.swing.threads.CancellableMonitorable;
80
import com.vividsolutions.jts.geom.Geometry;
81
import com.vividsolutions.jts.geom.IntersectionMatrix;
82

    
83
/**
84
 * Esta clase definir? las operaciones de la interfaz FLyrVect de la manera m?s
85
 * ?ptima para los ficheros shp.
86
 */
87
public class ShpStrategy extends DefaultStrategy {
88
        private static Logger logger = Logger
89
                        .getLogger(ShpStrategy.class.getName());
90

    
91
        /**
92
         * Crea una ShpStrategy.
93
         *
94
         * @param capa
95
         */
96
        public ShpStrategy(FLayer capa) {
97
                super(capa);
98
        }
99

    
100
        /**
101
         * @see com.iver.cit.gvsig.fmap.operations.LayerOperations#draw(java.awt.image.BufferedImage,
102
         *      java.awt.Graphics2D, ISymbol)
103
         */
104
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
105
                        Cancellable cancel) throws DriverException {
106
                try {
107
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
108
                        if (adapter.getShapeCount() <= 0) {
109
                                // logger.info("Layer:" + getCapa().getName() + " sin
110
                                // registros");
111
                                return;
112
                        }
113

    
114
                        // Selectable selection = (Selectable) getCapa();
115
                        FLyrVect lyr = (FLyrVect) getCapa();
116
                        Selectable selectable = lyr.getRecordset();
117
                        ICoordTrans ct = getCapa().getCoordTrans();
118
                        FBitSet bitSet = selectable.getSelection();
119
                        BoundedShapes shapeBounds;
120
                        if (adapter instanceof BoundedShapes)
121
                                shapeBounds = (BoundedShapes) adapter;
122
                        else
123
                                shapeBounds = (BoundedShapes) adapter.getDriver();
124
                        // VectorialFileDriver driver = (VectorialFileDriver)
125
                        // adapter.getDriver();
126
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
127
                        adapter.start();
128
                        IGeometry geom;
129
                        // if (adapter.getShapeCount() > 0) {
130
                        // geom = adapter.getShape(0);
131
                        // }
132
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa())
133
                                        .getLegend();
134

    
135
                        if (l instanceof ClassifiedLegendInfo) {
136
                                ClassifiedLegendInfo clsfLegend = (ClassifiedLegendInfo) l;
137
                                ISymbol[] symbs = clsfLegend.getSymbols();
138
                                // double rSym = 0;
139
                                // double maxRSym = -1;
140

    
141
                                for (int i = 0; i < symbs.length; i++) {
142
                                        // TODO: REVISAR LOS SIMBOLOS Y SUS TAMA?OS
143

    
144
                                        /*
145
                                         * Style2D pointSymbol = symbs[i].getPointStyle2D(); if
146
                                         * (pointSymbol instanceof MarkStyle2D) { MarkStyle2D mrk2D =
147
                                         * (MarkStyle2D) pointSymbol; rSym =
148
                                         * viewPort.toMapDistance(mrk2D.getSize()); if (maxRSym <
149
                                         * rSym) maxRSym = rSym; }
150
                                         */
151
                                }
152
                        }
153

    
154
                        Rectangle2D extent = viewPort.getAdjustedExtent();
155
                        // AffineTransform at = viewPort.getAffineTransform();
156

    
157
                        int sc;
158

    
159
                        Rectangle2D bounds;
160

    
161
                        long t1 = System.currentTimeMillis();
162
                        // logger.debug("getCapa().getRecordset().start()");
163
                        
164
                        //CHEMA
165
                        // En teorioa el al hacer el adapter.start()
166
                        // deja abierta las fuentes de datos
167
                        // geometrica y alfanumerica (cuando no son la misma
168
                        // excepto cuando se ha hecho una operacion de 'join' de la tabla 
169
                        // (join de las tablas de gvsig(gdbms) no join de sql), entoces
170
                        // el origen alfanumerico no es el mismo en el source
171
                        // que en la capa.
172
                        //
173
                        //((FLyrVect) getCapa()).getRecordset().start();
174
                        if (lyr.isJoined()){
175
                                lyr.getRecordset().start();
176
                        }
177
                        //CHEMA
178

    
179
                        // TODO: A revisar si es o no conveniente este sistema
180
                        // de comunicaci?n con los drivers.
181
                        DriverAttributes attr = adapter.getDriverAttributes();
182
                        boolean bMustClone = false;
183
                        if (attr != null) {
184
                                if (attr.isLoadedInMemory()) {
185
                                        bMustClone = attr.isLoadedInMemory();
186
                                }
187
                        }
188

    
189
                        List lstIndexes = null;
190

    
191
                        // If area of needed extent is less than fullExtent / 4,
192
                        // it will be worthy to use SpatialIndex.
193
                        // Otherwhise, we will not use it.
194
                        boolean bUseSpatialIndex = false;
195
                        sc = adapter.getShapeCount();
196
                        // if (lyr.getSpatialIndex() != null) AZABALA
197
                        // long t11 = System.currentTimeMillis();
198
                        if (lyr.getISpatialIndex() != null) {
199
                                if (isSpatialIndexNecessary(extent)) {
200
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
201
                                        // If the layer is reprojected, spatial index was created
202
                                        // in its own projection, so we must to apply an inverse
203
                                        // transform
204
                                        if (ct != null) {
205
                                                Rectangle2D newExtent = ct.getInverted()
206
                                                                .convert(extent);
207
                                                // Rectangle2D newExtent = ct.convert(extent);
208
                                                // lstIndexes = lyr.getISpatialIndex().query(extent);
209
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
210
                                        } else {
211
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
212
                                        }
213
                                        sc = lstIndexes.size();
214
                                        bUseSpatialIndex = true;
215
                                }// if
216
                        }// if
217
                        /*
218
                         * long t12 = System.currentTimeMillis(); System.out.println("Tiempo
219
                         * en mirar el ?ndice espacial y recuperar los ?ndices:" +
220
                         * (t12-t11)); System.out.println("Numero de ?ndices:" + sc);
221
                         */
222

    
223
                        // SpatialCache cache = lyr.createSpatialCache();
224
                        lyr.getSpatialCache().clearAll();
225
                        SpatialCache cache = lyr.getSpatialCache();
226
                        int i;
227

    
228
                        // En OS X con renderer Quartz (JRE<6), mezclar setRGB con dibujado
229
                        // geometrico en mismo BufferedImage
230
                        // provoca ralentizaci?n brutal. Lo evitamos separando los setRGB en
231
                        // otro BufferedImage y juntandolos luego.
232
                        boolean MAC_OS_X = System.getProperty("os.name").toLowerCase()
233
                                        .startsWith("mac os x");
234
                        BufferedImage auxBI = null;
235
                        if (MAC_OS_X) {
236
                                auxBI = new BufferedImage(image.getWidth(), image.getHeight(),
237
                                                image.getType());
238
                        }
239

    
240
                        for (int aux = 0; aux < sc; aux++) {
241
                                // Salimos si alguien cancela
242
                                if (cancel != null) {
243
                                        // azabala (por si acaso, al arreglar bug de process)
244
                                        if (cancel.isCanceled()) {
245
                                                break;
246
                                        }
247
                                }
248
                                if (bUseSpatialIndex) {
249
                                        Integer idRec = (Integer) lstIndexes.get(aux);
250
                                        i = idRec.intValue();
251
                                } else {
252
                                        i = aux;
253
                                }
254
                                bounds = shapeBounds.getShapeBounds(i);
255
                                if (ct != null) {
256
                                        bounds = ct.convert(bounds);
257
                                }
258
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
259
                                        ISymbol symbol = l.getSymbol(i);
260

    
261
                                        if (bitSet.get(i)) {
262
                                                symbol = symbol.getSymbolForSelection();
263
                                        }
264

    
265
                                        if (symbol == null)
266
                                                continue;
267

    
268
                                        boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
269

    
270
                                        if (bPoint
271
                                                        || ((bounds.getHeight() > viewPort.getDist1pixel()) || (bounds
272
                                                                        .getWidth() > viewPort.getDist1pixel()))) {
273
                                                geom = adapter.getShape(i);
274

    
275
                                                // PRUEBA DE VELOCIDAD
276
                                                // geom = ShapeFactory.createPolygon2D(new
277
                                                // GeneralPathX(bounds));
278

    
279
                                                
280
                                                //JMVIVO: OJO, No colnamos siempre porque
281
                                                // el FGeometry.drawInt (a diferencia del
282
                                                // FGeometry.draw) clona siempre la geometria
283
                                                // antes de pintarla (para transforma a enteros)
284
                                                if (ct != null) {
285
                                                        if (bMustClone)
286
                                                                geom = geom.cloneGeometry();
287
                                                        geom.reProject(ct);
288
                                                }
289
                                                if (lyr.isSpatialCacheEnabled()) {
290
                                                        if (cache.getMaxFeatures() >= cache.size()) {
291
                                                                // Ya reproyectado todo
292
                                                                cache.insert(bounds, geom);
293
                                                        }
294
                                                }
295

    
296
                                                // FJP: CAMBIO: Sabemos que vamos a dibujar sobre una
297
                                                // imagen, con coordenadas enteras, as?
298
                                                // que lo tenemos en cuenta.
299
                                                // ANTES: geom.draw(g, viewPort, symbol);
300
                                                // AHORA:
301
                                                geom.drawInts(g, viewPort, symbol);
302
                                                // geom.draw(g, viewPort, symbol);
303
                                                /*
304
                                                 * if (lyr.isEditing()) { if (bitSet.get(i)) { Handler[]
305
                                                 * handlers = geom.getHandlers(IGeometry.SELECTHANDLER);
306
                                                 * FGraphicUtilities.DrawHandlers(g,
307
                                                 * viewPort.getAffineTransform(), handlers); } }
308
                                                 */
309

    
310
                                        } else {
311
                                                Point2D.Double pOrig = new Point2D.Double(bounds
312
                                                                .getMinX(), bounds.getMinY());
313
                                                Point2D pDest, pDest2;
314

    
315
                                                pDest = viewPort.getAffineTransform().transform(pOrig,
316
                                                                null);
317
                                                pDest2 = g.getTransform().transform(pDest, null);
318

    
319
                                                int pixX = (int) pDest2.getX();
320
                                                int pixY = (int) pDest2.getY();
321
                                                if (symbol == null)
322
                                                        continue;
323
                                                if ((pixX > 0) && (pixX < image.getWidth())) {
324
                                                        if ((pixY > 0) && (pixY < image.getHeight())) {
325
                                                                if (MAC_OS_X) {
326
                                                                        auxBI.setRGB(pixX, pixY, symbol
327
                                                                                        .getOnePointRgb());
328
                                                                } else {
329
                                                                        image.setRGB(pixX, pixY, symbol
330
                                                                                        .getOnePointRgb());
331
                                                                }
332
                                                        }
333
                                                }
334
                                        }
335
                                }
336
                        }
337

    
338
                        if (MAC_OS_X) {
339
                                g.drawImage(auxBI, 0, 0, null);
340
                        }
341

    
342
                        // logger.debug("getCapa().getRecordset().stop()");
343
                        //CHEMA
344
                        // Cerramos la fuente alfanumerica cuando se ha hecho
345
                        // una operacion de 'join'                        
346
                        //((FLyrVect) getCapa()).getSource().getRecordset().stop();
347
                        if (lyr.isJoined()){
348
                                lyr.getRecordset().stop();
349
                        }
350
                        //CHEMA
351

    
352
                        long t2 = System.currentTimeMillis();
353
                        // logger.debug("adapter.stop()");
354
                        adapter.stop();
355

    
356
                        // System.out.println(t2 - t1);
357
                } catch (DriverIOException e) {
358
                        throw new DriverException(e);
359
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
360
                        throw new DriverException(e);
361
                } catch (DriverException e) {
362
                        throw new DriverException(e);
363
                } catch (IOException e) {
364
                        throw new DriverException(e);
365
                } catch (DriverLoadException e) {
366
                        // TODO Auto-generated catch block
367
                        e.printStackTrace();
368
                }
369
        }
370

    
371
        /**
372
         * M?todo utilizado para dibujar sobre el graphics que se pasa como
373
         * par?metro, pensado para utilizarse para imprimir.
374
         *
375
         * @param g
376
         *            Graphics2D
377
         * @param viewPort
378
         *            ViewPort.
379
         * @param cancel
380
         *
381
         * @throws DriverException
382
         */
383
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
384
                        PrintRequestAttributeSet printProperties) throws DriverException {
385
                // super.draw(null, g, viewPort, cancel); // Quiero ejecutar el draw del
386
                // padre, que es el que va sin acelaraci?n!!
387
                try {
388
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
389
                        if (adapter.getShapeCount() <= 0) {
390
                                // logger.info("Layer:" + getCapa().getName() + " sin
391
                                // registros");
392
                                return;
393
                        }
394
                        FLyrVect lyr = (FLyrVect) getCapa();
395
                        lyr.beforePrinting(printProperties);
396

    
397
                        Selectable selectable = lyr.getRecordset();
398
                        ICoordTrans ct = getCapa().getCoordTrans();
399
                        BitSet bitSet = selectable.getSelection();
400
                        BoundedShapes shapeBounds = (BoundedShapes) adapter.getDriver();
401
                        VectorialDriver driver = (VectorialDriver) adapter
402
                                        .getDriver();
403
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
404
                        adapter.start();
405
                        IGeometry geom;
406
                        if (adapter.getShapeCount() > 0) {
407
                                geom = adapter.getShape(0);
408
                        }
409
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa())
410
                                        .getLegend();
411

    
412
                        Rectangle2D extent = viewPort.getAdjustedExtent();
413
                        // AffineTransform at = viewPort.getAffineTransform();
414

    
415
                        int sc;
416

    
417
                        Rectangle2D bounds;
418

    
419
                        sc = adapter.getShapeCount();
420

    
421
                        long t1 = System.currentTimeMillis();
422
                        // logger.debug("getCapa().getRecordset().start()");
423
                        
424
                        //CHEMA
425
                        // En teorioa el al hacer el adapter.start()
426
                        // deja abierta las fuentes de datos
427
                        // geometrica y alfanumerica (cuando no son la misma
428
                        // excepto cuando se ha hecho una operacion de 'join' de la tabla 
429
                        // (join de las tablas de gvsig(gdbms) no join de sql), entoces
430
                        // el origen alfanumerico no es el mismo en el source
431
                        // que en la capa.
432
                        //
433
                        //((FLyrVect) getCapa()).getRecordset().start();
434
                        if (lyr.isJoined()){
435
                                lyr.getRecordset().start();
436
                        }
437
                        //CHEMA
438
                        
439
                        
440
                        // TODO: A revisar si es o no conveniente este sistema
441
                        // de comunicaci?n con los drivers.
442
                        DriverAttributes attr = adapter.getDriverAttributes();
443
                        boolean bMustClone = false;
444
                        if (attr != null) {
445
                                if (attr.isLoadedInMemory()) {
446
                                        bMustClone = attr.isLoadedInMemory();
447
                                }
448
                        }
449

    
450
                        List lstIndexes = null;
451

    
452
                        boolean bUseSpatialIndex = false;
453
                        if (lyr.getISpatialIndex() != null) {
454
                                if (isSpatialIndexNecessary(extent)) {
455
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
456
                                        if (ct != null) {
457
                                                Rectangle2D newExtent = ct.getInverted()
458
                                                                .convert(extent);
459
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
460
                                        } else {
461
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
462
                                        }
463
                                        sc = lstIndexes.size();
464
                                        bUseSpatialIndex = true;
465
                                }// if
466
                        }// if
467

    
468
                        int i;
469
                        for (int aux = 0; aux < sc; aux++) {
470
                                if (bUseSpatialIndex) {
471
                                        Integer idRec = (Integer) lstIndexes.get(aux);
472
                                        i = idRec.intValue();
473
                                } else {
474
                                        i = aux;
475
                                }
476

    
477
                                bounds = shapeBounds.getShapeBounds(i);
478

    
479
                                if (ct != null) {
480
                                        bounds = ct.convert(bounds);
481
                                }
482

    
483
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
484
                                        ISymbol symbol = l.getSymbol(i);
485
                                        if (symbol == null)
486
                                                continue;
487
                                        if (bitSet.get(i)) {
488
                                                symbol = symbol.getSymbolForSelection();
489
                                        }
490

    
491
                                        //boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
492

    
493
                                        geom = driver.getShape(i);
494

    
495
                                        // PRUEBA DE VELOCIDAD
496
                                        // geom = ShapeFactory.createPolygon2D(new
497
                                        // GeneralPathX(bounds));
498
                                        
499
                                        // JMVIVO: Clonamos siempre que sea necesario y no
500
                                        // solo si hay que reproyectar. Porque el FGeometry.draw
501
                                        // va a aplicar la transformacion sobre la geometria original
502
                                        if (bMustClone)
503
                                                geom = geom.cloneGeometry();
504

    
505
                                        if (ct != null) {
506
                                                geom.reProject(ct);
507
                                        }
508

    
509
                                        geom.draw(g, viewPort, symbol);
510

    
511
                                }
512
                        }
513

    
514
                        // logger.debug("getCapa().getRecordset().stop()");
515
                        //CHEMA
516
                        // Cerramos la fuente alfanumerica cuando se ha hecho
517
                        // una operacion de 'join'                        
518
                        //((FLyrVect) getCapa()).getSource().getRecordset().stop();
519
                        if (lyr.isJoined()){
520
                                lyr.getRecordset().stop();
521
                        }
522
                        //CHEMA
523

    
524
                        long t2 = System.currentTimeMillis();
525
                        // logger.debug("adapter.stop()");
526
                        adapter.stop();
527
                        lyr.afterPrinting();
528
                        // System.out.println(t2 - t1);
529
                } catch (DriverIOException e) {
530
                        throw new DriverException(e);
531
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
532
                        throw new DriverException(e);
533
                } catch (DriverException e) {
534
                        throw new DriverException(e);
535
                } catch (IOException e) {
536
                        throw new DriverException(e);
537
                }
538

    
539
        }
540

    
541
        public FBitSet queryByShape(IGeometry g, int relationship)
542
                        throws DriverException, VisitException {
543
                return queryByShape(g, relationship, null);
544
        }
545

    
546
        /*
547
         * (non-Javadoc)
548
         *
549
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByShape(com.iver.cit.gvsig.fmap.core.IGeometry,
550
         *      int)
551
         */
552
        public FBitSet queryByShape(IGeometry g, int relationship,
553
                        CancellableMonitorable cancel) throws DriverException,
554
                        VisitException {
555
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
556
                FLyrVect lyr = (FLyrVect) capa;
557
                // if (lyr.getSpatialIndex() == null) AZABALA
558
                if (lyr.getISpatialIndex() == null)
559
                        return super.queryByShape(g, relationship, null);
560

    
561
                long t1 = System.currentTimeMillis();
562
                ReadableVectorial va = lyr.getSource();
563
                ICoordTrans ct = lyr.getCoordTrans();
564
                Rectangle2D bounds = g.getBounds2D();
565
                List lstRecs = lyr.getISpatialIndex().query(bounds);
566
                Integer idRec;
567
                FBitSet bitset = new FBitSet();
568
                Geometry jtsShape = g.toJTSGeometry();
569
                IntersectionMatrix m;
570
                int index;
571
                try {
572
                        va.start();
573

    
574
                        for (int i = 0; i < lstRecs.size(); i++) {
575
                                if (cancel != null) {
576
                                        cancel.reportStep();
577
                                        if (cancel.isCanceled()) {
578
                                                break;
579
                                        }
580
                                }
581
                                idRec = (Integer) lstRecs.get(i);
582
                                index = idRec.intValue();
583
                                IGeometry geom = va.getShape(index);
584
                                if (geom == null)
585
                                        continue;
586
                                if (ct != null) {
587
                                        geom.reProject(ct);
588
                                }
589
                                Geometry jtsGeom = geom.toJTSGeometry();
590
                                switch (relationship) {
591
                                case CONTAINS:
592
                                        m = jtsShape.relate(jtsGeom);
593
                                        if (m.isContains()) {
594
                                                bitset.set(index, true);
595
                                        }
596
                                        break;
597

    
598
                                case CROSSES:
599
                                        m = jtsShape.relate(jtsGeom);
600
                                        if (m.isCrosses(jtsGeom.getDimension(), jtsShape
601
                                                        .getDimension())) {
602
                                                bitset.set(index, true);
603
                                        }
604
                                        break;
605

    
606
                                case DISJOINT:
607
                                        // TODO: CREO QUE EL DISJOINT NO SE PUEDE METER AQUI
608
                                        m = jtsShape.relate(jtsGeom);
609
                                        if (m.isDisjoint()) {
610
                                                bitset.set(index, true);
611
                                        }
612
                                        break;
613

    
614
                                case EQUALS:
615
                                        m = jtsShape.relate(jtsGeom);
616
                                        if (m.isEquals(jtsGeom.getDimension(), jtsShape
617
                                                        .getDimension())) {
618
                                                bitset.set(index, true);
619
                                        }
620
                                        break;
621

    
622
                                case INTERSECTS:
623
                                        m = jtsShape.relate(jtsGeom);
624
                                        if (m.isIntersects()) {
625
                                                bitset.set(index, true);
626
                                        }
627
                                        break;
628

    
629
                                case OVERLAPS:
630
                                        m = jtsShape.relate(jtsGeom);
631
                                        if (m.isOverlaps(jtsGeom.getDimension(), jtsShape
632
                                                        .getDimension())) {
633
                                                bitset.set(index, true);
634
                                        }
635

    
636
                                        break;
637

    
638
                                case TOUCHES:
639
                                        m = jtsShape.relate(jtsGeom);
640
                                        if (m.isTouches(jtsGeom.getDimension(), jtsShape
641
                                                        .getDimension())) {
642
                                                bitset.set(index, true);
643
                                        }
644

    
645
                                        break;
646

    
647
                                case WITHIN:
648
                                        m = jtsShape.relate(jtsGeom);
649
                                        if (m.isWithin()) {
650
                                                bitset.set(index, true);
651
                                        }
652

    
653
                                        break;
654
                                }
655
                        }
656
                        va.stop();
657
                } catch (DriverIOException e) {
658
                        // TODO Auto-generated catch block
659
                        e.printStackTrace();
660
                }
661
                long t2 = System.currentTimeMillis();
662
                // logger.info("queryByShape optimizado sobre la capa " + lyr.getName()
663
                // + ". " + (t2 - t1) + " mseg.");
664
                return bitset;
665
        }
666

    
667
        public FBitSet queryByRect(Rectangle2D rect, CancellableMonitorable cancel)
668
                        throws DriverException {
669
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
670
                FLyrVect lyr = (FLyrVect) capa;
671
                if (lyr.getISpatialIndex() == null)
672
                        return super.queryByRect(rect, cancel);
673

    
674
                ReadableVectorial va = lyr.getSource();
675
                ICoordTrans ct = lyr.getCoordTrans();
676
                Rectangle2D bounds = rect;
677
                List lstRecs = lyr.getISpatialIndex().query(bounds);
678
                Integer idRec;
679
                FBitSet bitset = new FBitSet();
680
                int index;
681
                try {
682
                        va.start();
683
                        DriverAttributes attr = va.getDriverAttributes();
684
                        boolean bMustClone = false;
685
                        if (attr != null) {
686
                                if (attr.isLoadedInMemory()) {
687
                                        bMustClone = attr.isLoadedInMemory();
688
                                }
689
                        }
690

    
691
                        for (int i = 0; i < lstRecs.size(); i++) {
692
                                if (cancel != null) {
693
                                        cancel.reportStep();
694
                                        if (cancel.isCanceled()) {
695
                                                va.stop();
696
                                                return bitset;
697
                                        }
698
                                }
699
                                idRec = (Integer) lstRecs.get(i);
700
                                index = idRec.intValue();
701
                                IGeometry geom = va.getShape(index);
702
                                if (geom == null)// azabala
703
                                        continue;
704
                                if (ct != null) {
705
                                        if (bMustClone)
706
                                                geom = geom.cloneGeometry();
707
                                        geom.reProject(ct);
708
                                }
709
                                if (geom.intersects(rect))
710
                                        bitset.set(index, true);
711
                        }
712
                        va.stop();
713
                } catch (DriverIOException e) {
714
                        // TODO Auto-generated catch block
715
                        e.printStackTrace();
716
                }
717
                return bitset;
718

    
719
        }
720

    
721
        public void process(FeatureVisitor visitor, Rectangle2D rectangle)
722
                        throws DriverException, VisitException {
723
                process(visitor, rectangle, null);
724
        }
725

    
726
        /**
727
         * Processes (by calling visitor.process() method) only those features of
728
         * the vectorial layer associated which intersects given rectangle2d.
729
         *
730
         */
731

    
732
        public void process(FeatureVisitor visitor, Rectangle2D rectangle,
733
                        CancellableMonitorable cancel) throws DriverException,
734
                        VisitException {
735
                if (visitor.start(capa)) {
736
                        FLyrVect lyr = (FLyrVect) capa;
737
                        // if we dont have spatial index or...
738
                        if (lyr.getISpatialIndex() == null) {
739
                                super.process(visitor, rectangle, cancel);
740
                                return;
741
                        }
742
                        // if spatial index is not worthy
743
                        if (!isSpatialIndexNecessary(rectangle)) {
744
                                super.process(visitor, rectangle, cancel);
745
                                return;
746
                        }
747

    
748
                        ReadableVectorial va = lyr.getSource();
749
                        ICoordTrans ct = lyr.getCoordTrans();
750
                        Rectangle2D bounds = rectangle;
751
                        List lstRecs = lyr.getISpatialIndex().query(bounds);
752
                        Integer idRec;
753
                        int index;
754
                        try {
755
                                va.start();
756
                                DriverAttributes attr = va.getDriverAttributes();
757
                                boolean bMustClone = false;
758
                                if (attr != null) {
759
                                        if (attr.isLoadedInMemory()) {
760
                                                bMustClone = attr.isLoadedInMemory();
761
                                        }
762
                                }
763

    
764
                                for (int i = 0; i < lstRecs.size(); i++) {
765
                                        if (cancel != null) {
766
                                                cancel.reportStep();
767
                                        }
768
                                        if (verifyCancelation(cancel, va, visitor))
769
                                                return;
770
                                        idRec = (Integer) lstRecs.get(i);
771
                                        index = idRec.intValue();
772
                                        IGeometry geom = va.getShape(index);
773
                                        if (geom == null)// azabala
774
                                                continue;
775
                                        if (ct != null) {
776
                                                if (bMustClone)
777
                                                        geom = geom.cloneGeometry();
778
                                                geom.reProject(ct);
779
                                        }
780
                                        if (geom.intersects(rectangle))
781
                                                visitor.visit(geom, index);
782
                                }// for
783
                                va.stop();
784
                        } catch (DriverIOException e) {
785
                                // TODO Auto-generated catch block
786
                                e.printStackTrace();
787
                        }
788
                }// if visitor.start
789
        }
790

    
791
        /*
792
         * (non-Javadoc)
793
         *
794
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByPoint(java.awt.geom.Point2D,
795
         *      double)
796
         */
797
        public FBitSet queryByPoint(Point2D p, double tolerance,
798
                        CancellableMonitorable cancel) throws DriverException {
799
                // TODO: OJO!!!!. Est? implementado como un rectangulo.
800
                // Lo correcto deber?a ser calculando las distancias reales
801
                // es decir, con un c?rculo.
802
                Rectangle2D recPoint = new Rectangle2D.Double(p.getX()
803
                                - (tolerance / 2), p.getY() - (tolerance / 2), tolerance,
804
                                tolerance);
805
                return queryByRect(recPoint, cancel);
806
        }
807
}