Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / VectorialEditableAdapter.java @ 13882

History | View | Annotate | Download (34.6 KB)

1
/*
2
 * Created on 12-ene-2006 by fjp
3
 *
4
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
5
 *
6
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21
 *
22
 * For more information, contact:
23
 *
24
 *  Generalitat Valenciana
25
 *   Conselleria d'Infraestructures i Transport
26
 *   Av. Blasco Ib??ez, 50
27
 *   46010 VALENCIA
28
 *   SPAIN
29
 *
30
 *      +34 963862235
31
 *   gvsig@gva.es
32
 *      www.gvsig.gva.es
33
 *
34
 *    or
35
 *
36
 *   IVER T.I. S.A
37
 *   Salamanca 50
38
 *   46005 Valencia
39
 *   Spain
40
 *
41
 *   +34 963163400
42
 *   dac@iver.es
43
 */
44
/* CVS MESSAGES:
45
 *
46
 * $Id: VectorialEditableAdapter.java 13882 2007-09-19 16:25:05Z jaume $
47
 * $Log$
48
 * Revision 1.76  2007-09-19 16:25:04  jaume
49
 * ReadExpansionFileException removed from this context
50
 *
51
 * Revision 1.75  2007/07/25 06:52:08  caballero
52
 * reproject
53
 *
54
 * Revision 1.74  2007/06/22 10:52:30  caballero
55
 * start y stop
56
 *
57
 * Revision 1.73  2007/05/29 19:09:07  azabala
58
 * using of spatial index in spatial iteration now depends of the query area (to avoid using index in full scan queries)
59
 *
60
 * Revision 1.72  2007/05/07 09:02:47  caballero
61
 * editing memory
62
 *
63
 * Revision 1.71  2007/04/25 14:42:24  caballero
64
 * BoundShape
65
 *
66
 * Revision 1.70  2007/04/19 17:28:24  azabala
67
 * changes in ReadableVectorial interface (new iteration modes)
68
 *
69
 * Revision 1.69  2007/03/06 17:08:55  caballero
70
 * Exceptions
71
 *
72
 * Revision 1.68  2007/02/19 12:36:22  caballero
73
 * *** empty log message ***
74
 *
75
 * Revision 1.67  2007/02/13 11:31:08  caballero
76
 * optimizo cuando el cambio es alfanum?rico
77
 *
78
 * Revision 1.66  2007/02/12 08:53:37  caballero
79
 * FieldExpresion
80
 *
81
 * Revision 1.65  2007/02/08 12:03:07  caballero
82
 * comentar println
83
 *
84
 * Revision 1.64  2006/09/21 17:32:11  azabala
85
 * *** empty log message ***
86
 *
87
 * Revision 1.62  2006/08/10 08:20:31  caballero
88
 * flatness
89
 *
90
 * Revision 1.61  2006/07/20 13:03:07  fjp
91
 * nuevos campos
92
 *
93
 * Revision 1.60  2006/07/12 11:48:41  fjp
94
 * Draft to add, remove and delete fields
95
 *
96
 * Revision 1.59  2006/07/12 10:34:52  fjp
97
 * Draft to add, remove and delete fields
98
 *
99
 * Revision 1.58  2006/07/06 08:31:29  fjp
100
 * Draft to add, remove and delete fields
101
 *
102
 * Revision 1.57  2006/06/22 11:38:12  caballero
103
 * soluci?n error al borrar geometr?as
104
 *
105
 * Revision 1.56  2006/06/16 10:44:01  fjp
106
 * Por mandato de Vicente
107
 *
108
 * Revision 1.54  2006/06/01 16:15:16  fjp
109
 * Escritura que permite crear drivers de manera m?s sencilla.
110
 *
111
 * Revision 1.53  2006/05/30 13:03:41  fjp
112
 * setFlatness solo se debe aplicar a bases de datos espaciales.
113
 *
114
 * Revision 1.52  2006/05/24 09:29:30  caballero
115
 * a?adir flatness
116
 *
117
 * Revision 1.51  2006/05/16 16:07:19  fjp
118
 * snapping. Revisar
119
 *
120
 * Revision 1.50  2006/05/16 07:07:46  caballero
121
 * Modificar la geometr?a desde fuera
122
 *
123
 * Revision 1.49  2006/05/15 10:52:23  caballero
124
 * Saber si se realiza una operaci?n desde la vista o desde la tabla.
125
 *
126
 * Revision 1.48  2006/05/09 15:58:37  caballero
127
 * Para el IGN
128
 *
129
 * Revision 1.47  2006/05/09 10:28:28  caballero
130
 * faltaba controlar undo y redo
131
 *
132
 * Revision 1.46  2006/04/27 06:44:56  caballero
133
 * Soluci?n undo y redo de anotaciones
134
 *
135
 * Revision 1.45  2006/04/18 06:56:55  caballero
136
 * Cambiar VectorialAdapter por ReadableVectorial
137
 *
138
 * Revision 1.44  2006/04/12 17:13:39  fjp
139
 * *** empty log message ***
140
 *
141
 * Revision 1.43  2006/04/11 12:12:29  fjp
142
 * Con edici?n en PostGIS y guardando pseudo-arcos en los shapes.
143
 *
144
 * Revision 1.42  2006/04/11 06:53:20  fjp
145
 * Preparando el driver de escritura PostGIS
146
 *
147
 * Revision 1.41  2006/04/04 11:27:16  fjp
148
 * Consola escuchando bien y selecci?n en tabla sincronizada cuando hay edici?n
149
 *
150
 * Revision 1.40  2006/04/03 11:04:48  caballero
151
 * Posibilidad de a?adir una anotaci?n
152
 *
153
 * Revision 1.39  2006/03/29 06:26:37  caballero
154
 * acelerar con una imagen las herramientas
155
 *
156
 * Revision 1.38  2006/03/23 16:20:52  fjp
157
 * Un fallo un tanto inverosimil con el mapOverview
158
 *
159
 * Revision 1.37  2006/03/23 10:08:11  caballero
160
 * calculo del fullExtent recorriendo todas las geometr?as
161
 *
162
 * Revision 1.36  2006/03/22 11:46:29  caballero
163
 * Editar capa de anotaciones
164
 *
165
 * Revision 1.35  2006/02/28 18:15:22  fjp
166
 * Consola de CAD
167
 *
168
 * Revision 1.34  2006/02/24 11:30:32  fjp
169
 * FUNCIONA!!! (Creo)
170
 *
171
 * Revision 1.33  2006/02/24 07:57:58  fjp
172
 * FUNCIONA!!! (Creo)
173
 *
174
 * Revision 1.32  2006/02/23 17:55:45  fjp
175
 * Preparando para poder editar con el EditionManager
176
 *
177
 * Revision 1.31  2006/02/21 16:44:08  fjp
178
 * Preparando para poder editar con el EditionManager
179
 *
180
 * Revision 1.30  2006/02/20 18:14:59  fjp
181
 * Preparando para poder editar con el EditionManager
182
 *
183
 * Revision 1.29  2006/02/20 10:32:54  fjp
184
 * Preparando para poder editar con el EditionManager
185
 *
186
 * Revision 1.28  2006/02/17 13:40:03  fjp
187
 * Preparando para poder editar con el EditionManager
188
 *
189
 * Revision 1.27  2006/02/17 10:41:14  fjp
190
 * Evento de edici?n lanzado cuando una capa se pone en edici?n
191
 *
192
 * Revision 1.26  2006/02/17 08:21:19  fjp
193
 * *** empty log message ***
194
 *
195
 * Revision 1.25  2006/02/16 09:38:10  fjp
196
 * Preparando compatibilidad para bases de datos (y de paso, acelerando :-)
197
 *
198
 * Revision 1.24  2006/02/16 09:06:28  caballero
199
 * commandStack
200
 *
201
 * Revision 1.23  2006/02/15 18:16:02  fjp
202
 * POR TERMINAR
203
 *
204
 * Revision 1.22  2006/02/13 18:18:31  fjp
205
 * POR TERMINAR
206
 *
207
 * Revision 1.21  2006/02/10 13:28:23  caballero
208
 * poder cambiar la selecci?n
209
 *
210
 * Revision 1.20  2006/02/09 13:11:54  caballero
211
 * *** empty log message ***
212
 *
213
 * Revision 1.19  2006/02/08 16:45:29  caballero
214
 * elimnar c?dio no usado
215
 *
216
 * Revision 1.18  2006/02/08 15:18:45  caballero
217
 * control de las rows eliminadas
218
 *
219
 * Revision 1.17  2006/02/07 10:18:44  caballero
220
 * Con BoundedShape
221
 *
222
 * Revision 1.16  2006/02/06 12:01:41  caballero
223
 * driver del ova
224
 *
225
 * Revision 1.15  2006/02/03 14:09:32  fjp
226
 * Preparando edici?n
227
 *
228
 * Revision 1.14  2006/02/03 12:16:33  fjp
229
 * Preparando edici?n
230
 *
231
 * Revision 1.13  2006/02/03 11:54:12  caballero
232
 * tablas con vectorialEditableAdapter en edici?n
233
 *
234
 * Revision 1.11  2006/01/31 08:10:05  caballero
235
 * cambio de feature a row
236
 *
237
 * Revision 1.10  2006/01/30 08:18:14  caballero
238
 * m?todos para deshacer y rehacer
239
 *
240
 * Revision 1.9  2006/01/23 17:30:28  caballero
241
 * coger los datos del ova
242
 *
243
 * Revision 1.8  2006/01/23 16:16:16  caballero
244
 * getRowIndex
245
 *
246
 * Revision 1.7  2006/01/20 08:37:10  fjp
247
 * Preparando la edici?n
248
 *
249
 * Revision 1.6  2006/01/19 12:48:20  caballero
250
 * poder modificar su vectorial Adapter
251
 *
252
 * Revision 1.5  2006/01/19 09:28:11  fjp
253
 * Preparando la edici?n
254
 *
255
 * Revision 1.4  2006/01/17 10:24:02  fjp
256
 * Preparando edici?n
257
 *
258
 * Revision 1.3  2006/01/16 12:47:38  fjp
259
 * Preparando edici?n
260
 *
261
 * Revision 1.2  2006/01/16 11:23:00  fjp
262
 * Preparando edici?n
263
 *
264
 * Revision 1.1  2006/01/12 13:39:14  fjp
265
 * preaparar edicion
266
 *
267
 *
268
 */
269
package com.iver.cit.gvsig.fmap.edition;
270

    
271
import java.awt.Image;
272
import java.awt.geom.Rectangle2D;
273
import java.awt.image.BufferedImage;
274
import java.io.IOException;
275
import java.util.List;
276

    
277
import org.cresques.cts.ICoordTrans;
278
import org.cresques.cts.IProjection;
279

    
280
import com.hardcode.driverManager.Driver;
281
import com.hardcode.gdbms.driver.exceptions.InitializeDriverException;
282
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
283
import com.hardcode.gdbms.engine.data.DataSource;
284
import com.hardcode.gdbms.engine.data.driver.DriverException;
285
import com.hardcode.gdbms.engine.values.Value;
286
import com.iver.cit.gvsig.exceptions.commands.EditionCommandException;
287
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
288
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileWriteException;
289
import com.iver.cit.gvsig.exceptions.expansionfile.OpenExpansionFileException;
290
import com.iver.cit.gvsig.exceptions.layers.CancelEditingLayerException;
291
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
292
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException;
293
import com.iver.cit.gvsig.exceptions.visitors.StopWriterVisitorException;
294
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
295
import com.iver.cit.gvsig.fmap.core.FNullGeometry;
296
import com.iver.cit.gvsig.fmap.core.IFeature;
297
import com.iver.cit.gvsig.fmap.core.IGeometry;
298
import com.iver.cit.gvsig.fmap.core.IRow;
299
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
300
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
301
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
302
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
303
import com.iver.cit.gvsig.fmap.drivers.IFeatureIterator;
304
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
305
import com.iver.cit.gvsig.fmap.drivers.featureiterators.AttrQueryFeatureIterator;
306
import com.iver.cit.gvsig.fmap.drivers.featureiterators.DefaultFeatureIterator;
307
import com.iver.cit.gvsig.fmap.drivers.featureiterators.IndexedSptQueryFeatureIterator;
308
import com.iver.cit.gvsig.fmap.drivers.featureiterators.SpatialQueryFeatureIterator;
309
import com.iver.cit.gvsig.fmap.layers.FBitSet;
310
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
311
import com.iver.cit.gvsig.fmap.spatialindex.ISpatialIndex;
312
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
313
import com.vividsolutions.jts.geom.Envelope;
314
import com.vividsolutions.jts.index.SpatialIndex;
315
import com.vividsolutions.jts.index.quadtree.Quadtree;
316

    
317
/**
318
 * @author fjp
319
 *
320
 */
321
public class VectorialEditableAdapter extends EditableAdapter implements
322
                ReadableVectorial, BoundedShapes {
323
        protected ReadableVectorial ova;
324

    
325
        protected Quadtree index;
326

    
327
        protected Rectangle2D fullExtent;
328

    
329
        protected Image selectionImage;
330

    
331
        protected BufferedImage handlersImage;
332

    
333

    
334
        /*
335
         * azo; ReadableVectorial implementations need a reference to
336
         * IProjection (of the layer) and to ISpatialIndex (of the layer)
337
         * to allow iteration with different criteria
338
         * */
339
        protected IProjection projection;
340
        protected ISpatialIndex fmapSpatialIndex;
341
        private ICoordTrans ct;
342

    
343
        //private double flatness=0.8;
344
        /*
345
         * private class MyFeatureIterator implements IFeatureIterator { int numReg =
346
         * 0; Rectangle2D rect; String epsg; IFeatureIterator origFeatIt; boolean
347
         * bHasNext = true;
348
         *
349
         * public MyFeatureIterator(Rectangle2D r, String strEPSG) throws
350
         * DriverException { rect = r; epsg = strEPSG; origFeatIt =
351
         * ova.getFeatureIterator(r, epsg); } public boolean hasNext() throws
352
         * DriverException { return bHasNext; }
353
         *
354
         * public IFeature next() throws DriverException { IFeature aux =
355
         * origFeatIt.next(); return null; }
356
         *
357
         * public void closeIterator() throws DriverException {
358
         *  }
359
         *  }
360
         */
361

    
362

    
363

    
364
        public VectorialEditableAdapter() {
365
                super();
366
        }
367

    
368
        public void setOriginalVectorialAdapter(ReadableVectorial rv) throws ReadDriverException {
369
                ova = rv;
370
                setOriginalDataSource(rv.getRecordset());
371
        }
372

    
373
        /*
374
         * (non-Javadoc)
375
         *
376
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#start()
377
         */
378
        public void start() throws ReadDriverException, InitializeDriverException {
379
                ova.start();
380
        }
381

    
382
        public IWriter getWriter() {
383
                if (ova.getDriver() instanceof IWriteable)
384
                {
385
                        IWriter writer = ((IWriteable) ova.getDriver()).getWriter();
386
                        if (writer instanceof ISpatialWriter)
387
                                return writer;
388
                }
389
                return null;
390
        }
391

    
392
        /*
393
         * (non-Javadoc)
394
         *
395
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#stop()
396
         */
397
        public void stop() throws ReadDriverException {
398
                ova.stop();
399
        }
400

    
401
        /*
402
         * (non-Javadoc)
403
         *
404
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShape(int)
405
         */
406
        public IGeometry getShape(int rowIndex) throws ReadDriverException, ExpansionFileReadException {
407
                // Si no est? en el fichero de expansi?n
408
                int calculatedIndex = getCalculatedIndex(rowIndex);
409
                Integer integer = new Integer(calculatedIndex);
410
                if (!relations.containsKey(integer)) {
411
                        // Si ha sido eliminada
412
                        /*
413
                         * if (delRows.get(integer.intValue())) { return null; } else {
414
                         */
415
                        return ova.getShape(calculatedIndex);
416
                        // }
417
                }
418
                int num = ((Integer) relations.get(integer)).intValue();
419
                DefaultRowEdited feat;
420
                feat = (DefaultRowEdited) expansionFile.getRow(num);
421
                return ((IFeature) feat.getLinkedRow()).getGeometry()
422
                                        .cloneGeometry();// getGeometry();
423
        }
424

    
425
        /*
426
         * (non-Javadoc)
427
         *
428
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeType()
429
         */
430
        public int getShapeType() throws ReadDriverException {
431
                return ova.getShapeType();
432
        }
433

    
434
        public ReadableVectorial getOriginalAdapter() {
435
                return ova;
436
        }
437

    
438
        public VectorialDriver getDriver() {
439
                return ova.getDriver();
440
        }
441

    
442
        public void setDriver(VectorialDriver driver) {
443
                this.ova.setDriver(driver);
444
        }
445

    
446
        public DriverAttributes getDriverAttributes() {
447
                return ova.getDriverAttributes();
448
        }
449

    
450
        /**
451
         * DOCUMENT ME!
452
         * @throws StartEditionLayerException
453
         * @throws StartWriterVisitorException
454
         *
455
         * @throws EditionException
456
         *             DOCUMENT ME!
457
         */
458
        public void startEdition(int sourceType) throws StartWriterVisitorException {
459
                super.startEdition(sourceType);
460
                Driver drv = ova.getDriver();
461
                if (drv instanceof IWriteable)
462
                {
463
                        setWriter(((IWriteable) drv).getWriter());
464
                }
465

    
466

    
467
                try {
468
                        expansionFile.open();
469
                        if (index == null || fullExtent == null) {
470
                                // TODO: Si la capa dispone de un ?ndice espacial, hacer
471
                                // algo aqu? para que se use ese ?ndice espacial.
472
                                index = new Quadtree();
473

    
474
                                for (int i = 0; i < ova.getShapeCount(); i++) {
475
                                        Rectangle2D r=null;
476
                                        if (ova.getDriver() instanceof BoundedShapes) {
477
                                                r = ((BoundedShapes) ova.getDriver()).getShapeBounds(i);
478
                                        } else {
479
                                                IGeometry g = null;
480
                                                g = ((DefaultFeature) ova.getFeature(i))
481
                                                                        .getGeometry();
482
                                                if (g == null) {
483
                                                        continue;
484
                                                }
485

    
486
                                                r = g.getBounds2D();
487
                                        }
488
                                        if (ct != null) {
489
                                                r = ct.convert(r);
490
                                        }
491
                                        Envelope e = new Envelope(r.getX(),
492
                                                        r.getX() + r.getWidth(), r.getY(), r.getY()
493
                                                                        + r.getHeight());
494
                                        index.insert(e, new Integer(i));
495
                                        if (fullExtent == null) {
496
                                                fullExtent = r;
497
                                        } else {
498
                                                fullExtent = fullExtent.createUnion(r);
499
                                        }
500
                                }
501
                        }
502
                } catch (ReadDriverException e) {
503
                        throw new StartWriterVisitorException(writer.getName(),e);
504
                } 
505

    
506
                System.err.println("Se han metido en el ?ndice "
507
                                + index.queryAll().size() + " geometr?as");
508
        }
509

    
510
        /*
511
         * (non-Javadoc)
512
         *
513
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getRow(int)
514
         */
515
        public IRowEdited getRow(int index) throws ReadDriverException, ExpansionFileReadException {
516
                start();
517
                int calculatedIndex = getCalculatedIndex(index);
518
                Integer integer = new Integer(calculatedIndex);
519
                // Si no est? en el fichero de expansi?n
520
                DefaultRowEdited edRow = null;
521
                if (!relations.containsKey(integer)) {
522
                        edRow = new DefaultRowEdited(ova.getFeature(calculatedIndex),
523
                                        IRowEdited.STATUS_ORIGINAL, index);
524
                        stop();
525
                        return createExternalRow(edRow, 0);
526
                }
527
                int num = ((Integer) relations.get(integer)).intValue();
528
                IRowEdited aux = expansionFile.getRow(num);
529
                edRow = new DefaultRowEdited(aux.getLinkedRow().cloneRow(), aux
530
                                .getStatus(), index);
531
                stop();
532
                return edRow;
533
        }
534

    
535
        /**
536
         * Elimina una geometria. Si es una geometr?a original de la capa en edici?n
537
         * se marca como eliminada (haya sido modificada o no). Si es una geometr?a
538
         * a?adida posteriormente se invalida en el fichero de expansi?n, para que
539
         * una futura compactaci?n termine con ella.
540
         *
541
         * @param index
542
         *            ?ndice de la geometr?a.
543
         * @throws ReadDriverException
544
         * @throws ExpansionFileReadException
545
         *
546
         * @throws DriverIOException
547
         * @throws IOException
548
         */
549
        public IRow doRemoveRow(int index, int sourceType) throws ReadDriverException, ExpansionFileReadException{
550
                boolean cancel = fireBeforeRemoveRow(index, sourceType);
551
                if (cancel)
552
                        return null;
553
                // Llega el calculatedIndex
554
                Integer integer = new Integer(index);
555

    
556
                IFeature feat = null;
557
                delRows.set(index, true);
558
                // Si la geometr?a no ha sido modificada
559
                if (!relations.containsKey(integer)) {
560
                        feat = (DefaultFeature) (ova.getFeature(index));
561
                } else {
562
                        int num = ((Integer) relations.get(integer)).intValue();
563
                        feat = (IFeature) expansionFile.getRow(num).getLinkedRow();
564
                        // expansionFile.invalidateRow(num);
565
                }
566
                System.err.println("Elimina una Row en la posici?n: " + index);
567
                // Se actualiza el ?ndice
568
                if (feat != null) {
569
                        Rectangle2D r = feat.getGeometry().getBounds2D();
570
                        boolean borrado = this.index.remove(new Envelope(r.getX(), r.getX()
571
                                        + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
572
                                        new Integer(index));
573
                        System.out.println("Est? borrado : " + borrado);
574
                        System.out.println("Index.lenght : " + this.index.size());
575
                        isFullExtentDirty = true;
576
                }
577
                setSelection(new FBitSet());
578
                fireAfterRemoveRow(index, sourceType);
579
                return feat;
580
        }
581

    
582
        /**
583
         * Si se intenta modificar una geometr?a original de la capa en edici?n se
584
         * a?ade al fichero de expansi?n y se registra la posici?n en la que se
585
         * a?adi?. Si se intenta modificar una geometria que se encuentra en el
586
         * fichero de expansi?n (por ser nueva o original pero modificada) se invoca
587
         * el m?todo modifyGeometry y se actualiza el ?ndice de la geometria en el
588
         * fichero.
589
         *
590
         * @param calculatedIndex
591
         *            DOCUMENT ME!
592
         * @param feat
593
         *            DOCUMENT ME!
594
         *
595
         * @return position inside ExpansionFile
596
         * @throws ReadDriverException
597
         * @throws ExpansionFileWriteException
598
         * @throws ExpansionFileReadException
599
         *
600
         * @throws IOException
601
         * @throws DriverIOException
602
         */
603
        public int doModifyRow(int calculatedIndex, IRow feat, int sourceType) throws ReadDriverException, ExpansionFileWriteException, ExpansionFileReadException {
604
                boolean cancel = fireBeforeModifyRow(feat, calculatedIndex, sourceType);
605
                if (cancel)
606
                        return -1;
607
                int posAnteriorInExpansionFile = -1;
608
                Integer integer = new Integer(calculatedIndex);
609

    
610
                IFeature featAnt = null;
611
//                System.err.println("Modifica una Row en la posici?n: "
612
//                                + calculatedIndex);
613
                // Si la geometr?a no ha sido modificada
614
                if (!relations.containsKey(integer)) {
615
                        int newPosition = expansionFile.addRow(feat,
616
                                        IRowEdited.STATUS_MODIFIED, actualIndexFields);
617
                        relations.put(integer, new Integer(newPosition));
618

    
619
                        if (sourceType == EditionEvent.GRAPHIC) {
620
                                // Se actualiza el ?ndice espacial
621
                                featAnt = (DefaultFeature) (ova.getFeature(calculatedIndex));
622
                                IGeometry g = featAnt.getGeometry();
623
                                Rectangle2D rAnt = g.getBounds2D();
624
                                Rectangle2D r = ((IFeature) feat).getGeometry().getBounds2D();
625
                                this.index.remove(new Envelope(rAnt.getX(), rAnt.getX()
626
                                                + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
627
                                                + rAnt.getHeight()), new Integer(calculatedIndex));
628
                                this.index.insert(new Envelope(r.getX(), r.getX()
629
                                                + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
630
                                                new Integer(calculatedIndex));
631
                        }
632
                } else {
633
                        // Obtenemos el ?ndice en el fichero de expansi?n
634
                        int num = ((Integer) relations.get(integer)).intValue();
635
                        posAnteriorInExpansionFile = num;
636

    
637
                        // Obtenemos la geometr?a para actualiza el ?ndice
638
                        // espacialposteriormente
639
                        featAnt = (IFeature) expansionFile.getRow(num).getLinkedRow();
640

    
641
                        /*
642
                         * Se modifica la geometr?a y nos guardamos el ?ndice dentro del
643
                         * fichero de expansi?n en el que se encuentra la geometr?a
644
                         * modificada
645
                         */
646
                        num = expansionFile.modifyRow(num, feat, actualIndexFields);
647

    
648
                        /*
649
                         * Actualiza la relaci?n del ?ndice de la geometr?a al ?ndice en el
650
                         * fichero de expansi?n.
651
                         */
652
                        relations.put(integer, new Integer(num));
653
                        if (sourceType == EditionEvent.GRAPHIC) {
654
                                // Se modifica el ?ndice espacial
655
                                Rectangle2D rAnt = featAnt.getGeometry().getBounds2D();
656
                                Rectangle2D r = ((IFeature) feat).getGeometry().getBounds2D();
657
                                this.index.remove(new Envelope(rAnt.getX(), rAnt.getX()
658
                                                + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
659
                                                + rAnt.getHeight()), new Integer(calculatedIndex));
660
                                this.index.insert(new Envelope(r.getX(), r.getX()
661
                                                + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
662
                                                new Integer(calculatedIndex));
663
                        }
664
                }
665
                isFullExtentDirty = true;
666
                fireAfterModifyRow(calculatedIndex, sourceType);
667
                return posAnteriorInExpansionFile;
668
        }
669

    
670
        /**
671
         * Actualiza en el mapa de ?ndices, la posici?n en la que estaba la
672
         * geometr?a antes de ser modificada. Se marca como v?lida, en caso de que
673
         * fuera una modificaci?n de una geometr?a que estuviese en el fichero de
674
         * expansi?n antes de ser modificada y se pone el puntero de escritura del
675
         * expansion file a justo despues de la penultima geometr?a
676
         *
677
         * @param calculatedIndex
678
         *            ?ndice de la geometr?a que se quiere deshacer su modificaci?n
679
         * @param previousExpansionFileIndex
680
         *            ?ndice que ten?a antes la geometr?a en el expansionFile. Si
681
         *            vale -1 quiere decir que es una modificaci?n de una geometr?a
682
         *            original y por tanto no hay que actualizar el mapa de indices
683
         *            sino eliminar su entrada.
684
         * @throws IOException
685
         * @throws DriverIOException
686
         */
687
        public void undoModifyRow(int calculatedIndex,
688
                        int previousExpansionFileIndex, int sourceType) throws EditionCommandException{
689
                try {
690
                        // Llega el CalculatedIndex
691
                        /*
692
                         * Si la acci?n de modificar se realiz? sobre una geometr?a original
693
                         */
694
                        if (previousExpansionFileIndex == -1) {
695

    
696
                                // Se obtiene la geometr?a para actualizar el ?ndice
697
                                // IGeometry g = ((DefaultFeature)
698
                                // getRow(calculatedIndex).getLinkedRow()).getGeometry();
699
                                int inverse = getInversedIndex(calculatedIndex);
700
                                DefaultFeature df;
701

    
702
                                df = (DefaultFeature) getRow(inverse).getLinkedRow();
703

    
704
                                boolean cancel = fireBeforeModifyRow(df, calculatedIndex,
705
                                                sourceType);
706
                                if (cancel)
707
                                        return;
708
                                IGeometry g = df.getGeometry();
709
                                // IGeometry g = ova.getShape(calculatedIndex);
710
                                Rectangle2D r = g.getBounds2D();
711

    
712
                                // Se elimina de las relaciones y del fichero de expansi?n
713
                                relations.remove(new Integer(calculatedIndex));
714
                                expansionFile.deleteLastRow();
715
                                if (sourceType == EditionEvent.GRAPHIC) {
716
                                        // Se actualizan los ?ndices
717
                                        IGeometry gAnt = ova.getShape(calculatedIndex);
718
                                        /*
719
                                         * IGeometry gAnt = ((DefaultFeature) getRow(calculatedIndex)
720
                                         * .getLinkedRow()).getGeometry();
721
                                         */
722
                                        Rectangle2D rAnt = gAnt.getBounds2D();
723
                                        this.index.remove(new Envelope(r.getX(), r.getX()
724
                                                        + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
725
                                                        new Integer(calculatedIndex));
726
                                        this.index.insert(new Envelope(rAnt.getX(), rAnt.getX()
727
                                                        + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
728
                                                        + rAnt.getHeight()), new Integer(calculatedIndex));
729
                                }
730
                        } else {
731
                                // Se obtiene la geometr?a para actualizar el ?ndice
732
                                IGeometry g = null;
733
                                int inverse = getInversedIndex(calculatedIndex);
734
                                DefaultFeature df = (DefaultFeature) getRow(inverse).getLinkedRow();
735
                                boolean cancel = fireBeforeModifyRow(df, calculatedIndex,
736
                                                sourceType);
737
                                if (cancel)
738
                                        return;
739
                                if (sourceType == EditionEvent.GRAPHIC) {
740
                                        g = df.getGeometry();
741
                                        System.out.println("Actual: " + g.toString());
742

    
743
                                        Rectangle2D r = g.getBounds2D();
744
                                        this.index.remove(new Envelope(r.getX(), r.getX()
745
                                                        + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
746
                                                        new Integer(calculatedIndex));
747

    
748
                                        // Se recupera la geometr?a
749
                                        // expansionFile.validateRow(previousExpansionFileIndex);
750

    
751
                                        // Se actualizan los ?ndices
752
                                        // g = ((IFeature)
753
                                        // (expansionFile.getRow(previousExpansionFileIndex).getLinkedRow())).getGeometry();
754
                                        // System.out.println("Anterior a la que volvemos : " +
755
                                        // g.toString());
756
                                        g = ((DefaultFeature) getRow(inverse).getLinkedRow())
757
                                        .getGeometry();
758
                                        r = g.getBounds2D();
759
                                        this.index.insert(new Envelope(r.getX(), r.getX()
760
                                                        + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
761
                                                        new Integer(calculatedIndex));
762
                                }
763
                                // Se actualiza la relaci?n de ?ndices
764
                                // Integer integer = new Integer(geometryIndex);
765
                                relations.put(new Integer(calculatedIndex), new Integer(
766
                                                previousExpansionFileIndex));
767

    
768
                        }
769
                } catch (ReadDriverException e) {
770
                        throw new EditionCommandException(writer.getName(),e);
771
                }
772
                //fireAfterModifyRow(calculatedIndex, sourceType);
773
        }
774

    
775
        /**
776
         * A?ade una geometria al fichero de expansi?n y guarda la correspondencia
777
         * en la tabla relations.
778
         *
779
         * @param feat
780
         *            geometr?a a guardar.
781
         *
782
         * @return calculatedIndex
783
         * @throws ExpansionFileWriteException
784
         * @throws DriverIOException
785
         * @throws IOException
786
         */
787
        public int doAddRow(IRow feat, int sourceType) throws ReadDriverException, ExpansionFileWriteException{
788
                int calculatedIndex = super.doAddRow(feat, sourceType);
789
                // Actualiza el ?ndice espacial
790
                IGeometry g = ((IFeature) feat).getGeometry();
791
                Rectangle2D r = g.getBounds2D();
792
                index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r.getY(),
793
                                r.getY() + r.getHeight()), new Integer(calculatedIndex));
794
                isFullExtentDirty = true;
795
                return calculatedIndex;
796
        }
797

    
798
        /**
799
         * Se desmarca como invalidada en el fichero de expansion o como eliminada
800
         * en el fichero original
801
         *
802
         * @param index
803
         *            DOCUMENT ME!
804
         * @throws IOException
805
         * @throws DriverIOException
806
         */
807
        public void undoRemoveRow(int index, int sourceType) throws EditionCommandException  {
808
                super.undoRemoveRow(index, sourceType);
809

    
810
                IGeometry g = null;
811
                try {
812
                        g = ((IFeature) getRow(getInversedIndex(index)).getLinkedRow()).getGeometry();
813
                } catch (ReadDriverException e) {
814
                        throw new EditionCommandException(writer.getName(),e);
815
                } 
816

    
817
                Rectangle2D r = g.getBounds2D();
818
                this.index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r
819
                                .getY(), r.getY() + r.getHeight()), new Integer(index));
820
        }
821

    
822
        /**
823
         * Se elimina del final del fichero de expansi?n poniendo el puntero de
824
         * escritura apuntando al final de la pen?ltima geometr?a. Deber? quitar la
825
         * relaci?n del mapa de relaciones
826
         *
827
         * @param index
828
         *            ?ndice de la geometr?a que se a?adi?
829
         * @throws EditionCommandException
830
         * @throws DriverIOException
831
         * @throws IOException
832
         */
833
        public void undoAddRow(int calculatedIndex, int sourceType) throws EditionCommandException{
834
                int inverse = getInversedIndex(calculatedIndex);
835
                IGeometry g;
836
                try {
837
                        g = ((IFeature) getRow(inverse).getLinkedRow()).getGeometry();
838
                        Rectangle2D r = g.getBounds2D();
839
                        this.index.remove(new Envelope(r.getX(), r.getX() + r.getWidth(), r
840
                                .getY(), r.getY() + r.getHeight()),
841
                                new Integer(calculatedIndex));
842

    
843
                        super.undoAddRow(calculatedIndex, sourceType);
844
                        setSelection(new FBitSet());
845
                } catch (ReadDriverException e) {
846
                        throw new EditionCommandException(writer.getName(),e);
847
                } 
848
        }
849

    
850
        /**
851
         * Obtiene las geometr?as que se encuentran en el rect?ngulo que se pasa
852
         * como par?metro haciendo uso del ?ndice espacial
853
         *
854
         * @param r
855
         *            Rect?ngulo indicando la porci?n del espacio para el cual se
856
         *            quiere saber los ?ndices de las geometr?as que se encuentran
857
         *            dentro de ?l
858
         *
859
         * @return Array de ?ndices para su uso con getGeometry, removeGeometry, ...
860
         */
861
        /*
862
         * public int[] getRowsIndexes_OL(Rectangle2D r) { Envelope e = new
863
         * Envelope(r.getX(), r.getX() + r.getWidth(), r.getY(), r.getY() +
864
         * r.getHeight()); List l = index.query(e); int[] indexes = new
865
         * int[l.size()];
866
         *
867
         * for (int index = 0; index < l.size(); index++) { Integer i = (Integer)
868
         * l.get(index); indexes[index] = getInversedIndex(i.intValue()); }
869
         *
870
         * return indexes; }
871
         */
872
        /**
873
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeCount()
874
         */
875
        public int getShapeCount() throws ReadDriverException {
876
                return getRowCount();
877
        }
878

    
879
        /**
880
         * @throws ExpansionFileReadException
881
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getFullExtent()
882
         */
883
        public Rectangle2D getFullExtent() throws ReadDriverException, ExpansionFileReadException {
884
                if (fullExtent == null) {
885
                        fullExtent = ova.getFullExtent();
886
                }
887

    
888
                if (isFullExtentDirty) {
889
                        fullExtent = reCalculateFullExtent();
890
                        isFullExtentDirty = false;
891
                }
892
                return fullExtent;
893
        }
894

    
895
        /**
896
         * Use it BEFORE writing to a file.
897
         *
898
         * @return real full extent.
899
         * @throws ExpansionFileReadException
900
         * @throws ReadDriverException
901
         * @throws DriverIOException
902
         */
903
        public Rectangle2D reCalculateFullExtent() throws ReadDriverException, ExpansionFileReadException  {
904
                if (getShapeCount() > 0) {
905
                        fullExtent = getShape(0).getBounds2D();
906
                        for (int i = 1; i < getShapeCount(); i++) {
907
                                IGeometry geom=getShape(i);
908
                                if (fullExtent==null) {
909
                                        fullExtent=geom.getBounds2D();
910
                                        continue;
911
                                }
912
                                if (!(geom instanceof FNullGeometry)) {
913
                                        fullExtent.add(geom.getBounds2D());
914
                                }
915
                        }
916
                } else {
917
                        fullExtent = ova.getFullExtent();
918
                }
919
                return fullExtent;
920
        }
921

    
922
        /**
923
         * En la implementaci?n por defecto podemos hacer que cada feature tenga ID =
924
         * numero de registro. En el DBAdapter podr?amos "overrride" este m?todo y
925
         * poner como ID de la Feature el campo ?nico escogido en la base de datos.
926
         *
927
         * @param numReg
928
         * @return
929
         * @throws ExpansionFileReadException
930
         */
931
        public IFeature getFeature(int numReg) throws ReadDriverException, ExpansionFileReadException {
932
                IGeometry geom;
933
                IFeature feat = null;
934
                        geom = getShape(numReg);
935
                        DataSource rs = getRecordset();
936
                        Value[] regAtt = new Value[rs.getFieldCount()];
937
                        for (int fieldId = 0; fieldId < rs.getFieldCount(); fieldId++) {
938
                                regAtt[fieldId] = rs.getFieldValue(numReg, fieldId);
939
                        }
940
                        feat = new DefaultFeature(geom, regAtt, numReg + "");
941
                return feat;
942
        }
943

    
944
        public void stopEdition(IWriter writer, int sourceType) throws StopWriterVisitorException {
945
//                ISpatialWriter spatialWriter = (ISpatialWriter) writer;
946
//                spatialWriter.setFlatness(FConverter.flatness);
947
                super.stopEdition(writer, sourceType);
948
//                try {
949
//                        ova.getDriver().reload();
950
//                } catch (ReloadDriverException e) {
951
//                        throw new StopWriterVisitorException(writer.getName(),e);
952
//                }
953
                index=null;
954
                writer=null;
955
        }
956

    
957
        public Rectangle2D getShapeBounds(int index) throws ReadDriverException, ExpansionFileReadException {
958
                // Solo se utiliza cuando el driver es BoundedShapes
959
                // Si no est? en el fichero de expansi?n
960
                Integer integer = new Integer(index);
961
                if (!relations.containsKey(integer)) {
962
                        if (ova.getDriver() instanceof BoundedShapes) {
963
                                BoundedShapes bs = (BoundedShapes) ova.getDriver();
964
                                return bs.getShapeBounds(index);
965
                        }
966
                        return ova.getDriver().getShape(index).getBounds2D();
967

    
968
                }
969
                int num = ((Integer) relations.get(integer)).intValue();
970
                DefaultRowEdited feat;
971
                feat = (DefaultRowEdited) expansionFile.getRow(num);
972
                if (feat.getStatus() == IRowEdited.STATUS_DELETED)
973
                        return null;
974
                IGeometry geom = ((IFeature) feat.getLinkedRow()).getGeometry();
975
                return geom.getBounds2D();// getGeometry();
976

    
977
        }
978

    
979
        public int getShapeType(int index) throws ReadDriverException {
980
                return ova.getShapeType();
981
        }
982

    
983
        /**
984
         * Usar solo cuando est?s seguro de que puedes gastar memoria. Nosotros lo
985
         * usamos para las b?squedas por ?ndice espacial con el handle. La idea es
986
         * usarlo una vez, guardar las geometr?as que necesitas en ese extent y
987
         * trabajar con ellas hasta el siguiente cambio de extent.
988
         *
989
         * @param r
990
         * @param strEPSG
991
         * @return
992
         * @throws ExpansionFileReadException
993
         * @throws ReadDriverException
994
         * @throws DriverException
995
         */
996
        public IRowEdited[] getFeatures(Rectangle2D r, String strEPSG) throws ReadDriverException, ExpansionFileReadException{
997
                // En esta clase suponemos random access.
998
                // Luego tendremos otra clase que sea VectorialEditableDBAdapter
999
                // que reescribir? este m?todo.
1000
                Envelope e = FConverter.convertRectangle2DtoEnvelope(r);
1001
                List l = index.query(e);
1002
                IRowEdited[] feats = new IRowEdited[l.size()];
1003
                for (int index = 0; index < l.size(); index++) {
1004
                        Integer i = (Integer) l.get(index);
1005
                        int inverse = getInversedIndex(i.intValue());
1006
                        feats[index] = getRow(inverse);
1007
                }
1008
                return feats;
1009
        }
1010

    
1011
        public void setSpatialIndex(SpatialIndex spatialIndex) {
1012
                index = (Quadtree) spatialIndex;
1013
                QuadtreeJts fmapidx = new QuadtreeJts(index);
1014
                setSpatialIndex(fmapidx);
1015

    
1016
        }
1017

    
1018
        public void setFullExtent(Rectangle2D fullExtent2) {
1019
                fullExtent = fullExtent2;
1020
        }
1021

    
1022
        /**
1023
         * DOCUMENT ME!
1024
         *
1025
         * @return DOCUMENT ME!
1026
         */
1027
        public Image getSelectionImage() {
1028
                return selectionImage;
1029
        }
1030

    
1031
        public Image getHandlersImage() {
1032
                return handlersImage;
1033
        }
1034

    
1035
        /**
1036
         * DOCUMENT ME!
1037
         *
1038
         * @param i
1039
         *            DOCUMENT ME!
1040
         */
1041
        public void setSelectionImage(Image i) {
1042
                selectionImage = i;
1043
        }
1044

    
1045
        public void setHandlersImage(BufferedImage handlersImage) {
1046
                this.handlersImage = handlersImage;
1047
        }
1048

    
1049
        public IFeatureIterator getFeatureIterator() throws ReadDriverException {
1050
                return new DefaultFeatureIterator(this, projection, null, null);
1051
        }
1052

    
1053

    
1054
        public IFeatureIterator getFeatureIterator(String[] fields, IProjection newProjection)
1055
        throws ReadDriverException{
1056
                return new DefaultFeatureIterator(this, projection, newProjection, fields);
1057
        }
1058

    
1059
        /**
1060
        * Return a feature iterator from a given sql statement.
1061
        * <br>
1062
        * In this case, the statement will have the "projection" operator
1063
        * (select campo1, campo2, ...etc) and the "selection" operator (where ....)
1064
        * @param sql statement which define a filter
1065
        * @return feature iterator
1066
        * */
1067
        public IFeatureIterator getFeatureIterator(String sql,
1068
                                                                IProjection newProjection) throws ReadDriverException{
1069

    
1070
                return new AttrQueryFeatureIterator(this, projection, newProjection, sql);
1071
        }
1072

    
1073

    
1074
        /**
1075
        * Makes an spatial query returning a feature iterator over the features which intersects
1076
        * or are contained in the rectangle query. Applies a restriction to the alphanumeric fields
1077
        * returned by the iterator.
1078
        * @param rect
1079
        * @param fields
1080
        * @return
1081
         * @throws ReadDriverException
1082
        */
1083
        public IFeatureIterator getFeatureIterator(Rectangle2D rect, String[] fields,
1084
                                                                        IProjection newProjection, boolean fastIteration) throws ReadDriverException{
1085
                if(fmapSpatialIndex == null){
1086
                        return new SpatialQueryFeatureIterator(this, projection, newProjection, fields, rect, fastIteration);
1087
                }else{
1088
                        return new IndexedSptQueryFeatureIterator(this, projection, newProjection, fields, rect, fmapSpatialIndex, fastIteration);
1089
                }
1090
        }
1091

    
1092
        public ISpatialIndex getSpatialIndex() {
1093
                return fmapSpatialIndex;
1094
        }
1095

    
1096
        public void setSpatialIndex(ISpatialIndex spatialIndex) {
1097
                this.fmapSpatialIndex = spatialIndex;
1098
        }
1099

    
1100
        public void setProjection(IProjection projection) {
1101
                this.projection = projection;
1102
        }
1103

    
1104
        public IProjection getProjection() {
1105
                return projection;
1106
        }
1107

    
1108
        public void cancelEdition(int sourceType) throws CancelEditingLayerException {
1109
                super.cancelEdition(sourceType);
1110
                index=null;
1111
                setWriter(null);
1112
                System.gc();
1113
        }
1114

    
1115
        /**
1116
         * Inserta las coordenadas de transformaci?n.
1117
         *
1118
         * @param ct Coordenadas de transformaci?n.
1119
         */
1120
        public void setCoordTrans(ICoordTrans ct) {
1121
                this.ct=ct;
1122
        }
1123

    
1124
}