Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1003 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / VectorialEditableAdapter.java @ 12271

History | View | Annotate | Download (31.4 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 12271 2007-06-21 10:50:33Z  $
47
 * $Log$
48
 * Revision 1.62.4.7  2007-06-21 10:19:37  caballero
49
 * bug acceso a la tabla simultaneamente en edici?n
50
 *
51
 * Revision 1.62.4.6  2007/05/07 09:01:50  caballero
52
 * editing memory
53
 *
54
 * Revision 1.62.4.5  2007/04/04 14:25:22  caballero
55
 * indice espacial diferente si es BoundShapes
56
 *
57
 * Revision 1.62.4.4  2007/02/09 11:25:44  caballero
58
 * gr?fico o alfanum?rico
59
 *
60
 * Revision 1.62.4.3  2006/11/22 09:23:09  fjp
61
 * Fallo al editar una capa de postgis 8.0 o superior. Y de paso, para que al guardar los cambios no haga falta leer todos los registros.
62
 *
63
 * Revision 1.62.4.2  2006/11/15 00:08:24  jjdelcerro
64
 * *** empty log message ***
65
 *
66
 * Revision 1.64  2006/09/21 17:32:11  azabala
67
 * *** empty log message ***
68
 *
69
 * Revision 1.62  2006/08/10 08:20:31  caballero
70
 * flatness
71
 *
72
 * Revision 1.61  2006/07/20 13:03:07  fjp
73
 * nuevos campos
74
 *
75
 * Revision 1.60  2006/07/12 11:48:41  fjp
76
 * Draft to add, remove and delete fields
77
 *
78
 * Revision 1.59  2006/07/12 10:34:52  fjp
79
 * Draft to add, remove and delete fields
80
 *
81
 * Revision 1.58  2006/07/06 08:31:29  fjp
82
 * Draft to add, remove and delete fields
83
 *
84
 * Revision 1.57  2006/06/22 11:38:12  caballero
85
 * soluci?n error al borrar geometr?as
86
 *
87
 * Revision 1.56  2006/06/16 10:44:01  fjp
88
 * Por mandato de Vicente
89
 *
90
 * Revision 1.54  2006/06/01 16:15:16  fjp
91
 * Escritura que permite crear drivers de manera m?s sencilla.
92
 *
93
 * Revision 1.53  2006/05/30 13:03:41  fjp
94
 * setFlatness solo se debe aplicar a bases de datos espaciales.
95
 *
96
 * Revision 1.52  2006/05/24 09:29:30  caballero
97
 * a?adir flatness
98
 *
99
 * Revision 1.51  2006/05/16 16:07:19  fjp
100
 * snapping. Revisar
101
 *
102
 * Revision 1.50  2006/05/16 07:07:46  caballero
103
 * Modificar la geometr?a desde fuera
104
 *
105
 * Revision 1.49  2006/05/15 10:52:23  caballero
106
 * Saber si se realiza una operaci?n desde la vista o desde la tabla.
107
 *
108
 * Revision 1.48  2006/05/09 15:58:37  caballero
109
 * Para el IGN
110
 *
111
 * Revision 1.47  2006/05/09 10:28:28  caballero
112
 * faltaba controlar undo y redo
113
 *
114
 * Revision 1.46  2006/04/27 06:44:56  caballero
115
 * Soluci?n undo y redo de anotaciones
116
 *
117
 * Revision 1.45  2006/04/18 06:56:55  caballero
118
 * Cambiar VectorialAdapter por ReadableVectorial
119
 *
120
 * Revision 1.44  2006/04/12 17:13:39  fjp
121
 * *** empty log message ***
122
 *
123
 * Revision 1.43  2006/04/11 12:12:29  fjp
124
 * Con edici?n en PostGIS y guardando pseudo-arcos en los shapes.
125
 *
126
 * Revision 1.42  2006/04/11 06:53:20  fjp
127
 * Preparando el driver de escritura PostGIS
128
 *
129
 * Revision 1.41  2006/04/04 11:27:16  fjp
130
 * Consola escuchando bien y selecci?n en tabla sincronizada cuando hay edici?n
131
 *
132
 * Revision 1.40  2006/04/03 11:04:48  caballero
133
 * Posibilidad de a?adir una anotaci?n
134
 *
135
 * Revision 1.39  2006/03/29 06:26:37  caballero
136
 * acelerar con una imagen las herramientas
137
 *
138
 * Revision 1.38  2006/03/23 16:20:52  fjp
139
 * Un fallo un tanto inverosimil con el mapOverview
140
 *
141
 * Revision 1.37  2006/03/23 10:08:11  caballero
142
 * calculo del fullExtent recorriendo todas las geometr?as
143
 *
144
 * Revision 1.36  2006/03/22 11:46:29  caballero
145
 * Editar capa de anotaciones
146
 *
147
 * Revision 1.35  2006/02/28 18:15:22  fjp
148
 * Consola de CAD
149
 *
150
 * Revision 1.34  2006/02/24 11:30:32  fjp
151
 * FUNCIONA!!! (Creo)
152
 *
153
 * Revision 1.33  2006/02/24 07:57:58  fjp
154
 * FUNCIONA!!! (Creo)
155
 *
156
 * Revision 1.32  2006/02/23 17:55:45  fjp
157
 * Preparando para poder editar con el EditionManager
158
 *
159
 * Revision 1.31  2006/02/21 16:44:08  fjp
160
 * Preparando para poder editar con el EditionManager
161
 *
162
 * Revision 1.30  2006/02/20 18:14:59  fjp
163
 * Preparando para poder editar con el EditionManager
164
 *
165
 * Revision 1.29  2006/02/20 10:32:54  fjp
166
 * Preparando para poder editar con el EditionManager
167
 *
168
 * Revision 1.28  2006/02/17 13:40:03  fjp
169
 * Preparando para poder editar con el EditionManager
170
 *
171
 * Revision 1.27  2006/02/17 10:41:14  fjp
172
 * Evento de edici?n lanzado cuando una capa se pone en edici?n
173
 *
174
 * Revision 1.26  2006/02/17 08:21:19  fjp
175
 * *** empty log message ***
176
 *
177
 * Revision 1.25  2006/02/16 09:38:10  fjp
178
 * Preparando compatibilidad para bases de datos (y de paso, acelerando :-)
179
 *
180
 * Revision 1.24  2006/02/16 09:06:28  caballero
181
 * commandStack
182
 *
183
 * Revision 1.23  2006/02/15 18:16:02  fjp
184
 * POR TERMINAR
185
 *
186
 * Revision 1.22  2006/02/13 18:18:31  fjp
187
 * POR TERMINAR
188
 *
189
 * Revision 1.21  2006/02/10 13:28:23  caballero
190
 * poder cambiar la selecci?n
191
 *
192
 * Revision 1.20  2006/02/09 13:11:54  caballero
193
 * *** empty log message ***
194
 *
195
 * Revision 1.19  2006/02/08 16:45:29  caballero
196
 * elimnar c?dio no usado
197
 *
198
 * Revision 1.18  2006/02/08 15:18:45  caballero
199
 * control de las rows eliminadas
200
 *
201
 * Revision 1.17  2006/02/07 10:18:44  caballero
202
 * Con BoundedShape
203
 *
204
 * Revision 1.16  2006/02/06 12:01:41  caballero
205
 * driver del ova
206
 *
207
 * Revision 1.15  2006/02/03 14:09:32  fjp
208
 * Preparando edici?n
209
 *
210
 * Revision 1.14  2006/02/03 12:16:33  fjp
211
 * Preparando edici?n
212
 *
213
 * Revision 1.13  2006/02/03 11:54:12  caballero
214
 * tablas con vectorialEditableAdapter en edici?n
215
 *
216
 * Revision 1.11  2006/01/31 08:10:05  caballero
217
 * cambio de feature a row
218
 *
219
 * Revision 1.10  2006/01/30 08:18:14  caballero
220
 * m?todos para deshacer y rehacer
221
 *
222
 * Revision 1.9  2006/01/23 17:30:28  caballero
223
 * coger los datos del ova
224
 *
225
 * Revision 1.8  2006/01/23 16:16:16  caballero
226
 * getRowIndex
227
 *
228
 * Revision 1.7  2006/01/20 08:37:10  fjp
229
 * Preparando la edici?n
230
 *
231
 * Revision 1.6  2006/01/19 12:48:20  caballero
232
 * poder modificar su vectorial Adapter
233
 *
234
 * Revision 1.5  2006/01/19 09:28:11  fjp
235
 * Preparando la edici?n
236
 *
237
 * Revision 1.4  2006/01/17 10:24:02  fjp
238
 * Preparando edici?n
239
 *
240
 * Revision 1.3  2006/01/16 12:47:38  fjp
241
 * Preparando edici?n
242
 *
243
 * Revision 1.2  2006/01/16 11:23:00  fjp
244
 * Preparando edici?n
245
 *
246
 * Revision 1.1  2006/01/12 13:39:14  fjp
247
 * preaparar edicion
248
 *
249
 *
250
 */
251
package com.iver.cit.gvsig.fmap.edition;
252

    
253
import java.awt.Image;
254
import java.awt.geom.Rectangle2D;
255
import java.awt.image.BufferedImage;
256
import java.io.IOException;
257
import java.util.List;
258

    
259
import com.hardcode.driverManager.Driver;
260
import com.hardcode.driverManager.DriverLoadException;
261
import com.hardcode.gdbms.engine.data.DataSource;
262
import com.hardcode.gdbms.engine.values.Value;
263
import com.iver.cit.gvsig.fmap.DriverException;
264
import com.iver.cit.gvsig.fmap.DriverIOExceptionType;
265
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
266
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
267
import com.iver.cit.gvsig.fmap.core.FShape;
268
import com.iver.cit.gvsig.fmap.core.IFeature;
269
import com.iver.cit.gvsig.fmap.core.IGeometry;
270
import com.iver.cit.gvsig.fmap.core.IRow;
271
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
272
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
273
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
274
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
275
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
276
import com.iver.cit.gvsig.fmap.layers.FBitSet;
277
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
278
import com.vividsolutions.jts.geom.Envelope;
279
import com.vividsolutions.jts.index.SpatialIndex;
280
import com.vividsolutions.jts.index.quadtree.Quadtree;
281

    
282
/**
283
 * @author fjp
284
 *
285
 */
286
public class VectorialEditableAdapter extends EditableAdapter implements
287
                ReadableVectorial, BoundedShapes {
288
        protected ReadableVectorial ova;
289

    
290
        protected Quadtree index;
291

    
292
        protected Rectangle2D fullExtent;
293

    
294
        protected Image selectionImage;
295

    
296
        protected BufferedImage handlersImage;
297

    
298
        //private double flatness=0.8;
299
        /*
300
         * private class MyFeatureIterator implements IFeatureIterator { int numReg =
301
         * 0; Rectangle2D rect; String epsg; IFeatureIterator origFeatIt; boolean
302
         * bHasNext = true;
303
         *
304
         * public MyFeatureIterator(Rectangle2D r, String strEPSG) throws
305
         * DriverException { rect = r; epsg = strEPSG; origFeatIt =
306
         * ova.getFeatureIterator(r, epsg); } public boolean hasNext() throws
307
         * DriverException { return bHasNext; }
308
         *
309
         * public IFeature next() throws DriverException { IFeature aux =
310
         * origFeatIt.next(); return null; }
311
         *
312
         * public void closeIterator() throws DriverException {
313
         *  }
314
         *  }
315
         */
316

    
317
        public VectorialEditableAdapter() {
318
                super();
319
        }
320

    
321
        public void setOriginalVectorialAdapter(ReadableVectorial rv) {
322
                ova = rv;
323
                try {
324
                        setOriginalDataSource(rv.getRecordset());
325
                } catch (DriverLoadException e) {
326
                        e.printStackTrace();
327
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
328
                        // TODO Auto-generated catch block
329
                        e.printStackTrace();
330
                }
331
        }
332

    
333
        /*
334
         * (non-Javadoc)
335
         *
336
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#start()
337
         */
338
        public void start() throws DriverIOException {
339
                ova.start();
340
        }
341

    
342
        public IWriter getWriter() {
343
                if (ova.getDriver() instanceof IWriteable)
344
                {
345
                        IWriter writer = ((IWriteable) ova.getDriver()).getWriter();
346
                        if (writer instanceof ISpatialWriter)
347
                                return writer;
348
                }
349
                return null;
350
        }
351

    
352
        /*
353
         * (non-Javadoc)
354
         *
355
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#stop()
356
         */
357
        public void stop() throws DriverIOException {
358
                ova.stop();
359
        }
360

    
361
        /*
362
         * (non-Javadoc)
363
         *
364
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShape(int)
365
         */
366
        public IGeometry getShape(int rowIndex) throws DriverIOException {
367
                // Si no est? en el fichero de expansi?n
368
                int calculatedIndex = getCalculatedIndex(rowIndex);
369
                Integer integer = new Integer(calculatedIndex);
370
                if (!relations.containsKey(integer)) {
371
                        // Si ha sido eliminada
372
                        /*
373
                         * if (delRows.get(integer.intValue())) { return null; } else {
374
                         */
375
                        return ova.getShape(calculatedIndex);
376
                        // }
377
                } else {
378
                        int num = ((Integer) relations.get(integer)).intValue();
379
                        DefaultRowEdited feat;
380
                        try {
381
                                feat = (DefaultRowEdited) expansionFile.getRow(num);
382
                                return ((IFeature) feat.getLinkedRow()).getGeometry()
383
                                                .cloneGeometry();// getGeometry();
384
                        } catch (IOException e) {
385
                                e.printStackTrace();
386
                                throw new DriverIOException(e);
387
                        }
388
                }
389

    
390
        }
391

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

    
401
        public ReadableVectorial getOriginalAdapter() {
402
                return ova;
403
        }
404

    
405
        public VectorialDriver getDriver() {
406
                return ova.getDriver();
407
        }
408

    
409
        public void setDriver(VectorialDriver driver) {
410
                this.ova.setDriver(driver);
411
        }
412

    
413
        public DriverAttributes getDriverAttributes() {
414
                return ova.getDriverAttributes();
415
        }
416
        /**
417
         * DOCUMENT ME!
418
         *
419
         * @throws EditionException
420
         *             DOCUMENT ME!
421
         */
422
        public void startEdition(int sourceType) throws EditionException {
423
                super.startEdition(sourceType);
424
                Driver drv = ova.getDriver();
425
                if (drv instanceof IWriteable)
426
                {
427
                        setWriter(((IWriteable) drv).getWriter());
428
                }
429

    
430

    
431
                try {
432
                        expansionFile.open();
433
                        if (index == null || fullExtent == null) {
434
                                // TODO: Si la capa dispone de un ?ndice espacial, hacer
435
                                // algo aqu? para que se use ese ?ndice espacial.
436
                                index = new Quadtree();
437
                                for (int i = 0; i < ova.getShapeCount(); i++) {
438
                                        Rectangle2D r=null;
439
                                        if (ova.getDriver() instanceof BoundedShapes) {
440
                                                r = ((BoundedShapes) ova.getDriver()).getShapeBounds(i);
441
                                        } else {
442
                                                IGeometry g = null;
443
                                                try {
444
                                                        g = ((DefaultFeature) ova.getFeature(i))
445
                                                                        .getGeometry();
446
                                                } catch (DriverException e1) {
447
                                                        e1.printStackTrace();
448
                                                }
449

    
450
                                                if (g == null) {
451
                                                        continue;
452
                                                }
453

    
454
                                                r = g.getBounds2D();
455
                                        }
456
                                        Envelope e = new Envelope(r.getX(),
457
                                                        r.getX() + r.getWidth(), r.getY(), r.getY()
458
                                                                        + r.getHeight());
459
                                        index.insert(e, new Integer(i));
460
                                        if (fullExtent == null) {
461
                                                fullExtent = r;
462
                                        } else {
463
                                                fullExtent = fullExtent.createUnion(r);
464
                                        }
465
                                }
466
                        }
467
                } catch (DriverIOException e) {
468
                        throw new EditionException(e);
469
                } catch (IOException e) {
470
                        throw new EditionException(e);
471
                }
472

    
473
                System.err.println("Se han metido en el ?ndice "
474
                                + index.queryAll().size() + " geometr?as");
475
        }
476

    
477
        /*
478
         * (non-Javadoc)
479
         *
480
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getRow(int)
481
         */
482
        public IRowEdited getRow(int index) throws DriverIOException, IOException {
483
                start();
484
                int calculatedIndex = getCalculatedIndex(index);
485
                Integer integer = new Integer(calculatedIndex);
486
                // Si no est? en el fichero de expansi?n
487
                DefaultRowEdited edRow = null;
488
                if (!relations.containsKey(integer)) {
489
                        try {
490
                                edRow = new DefaultRowEdited(ova.getFeature(calculatedIndex),
491
                                                DefaultRowEdited.STATUS_ORIGINAL, index);
492
                                stop();
493
                                return createExternalRow(edRow, 0);
494
                        } catch (DriverException e) {
495
                                e.printStackTrace();
496
                                throw new DriverIOException(e);
497
                        }
498

    
499
//                        return edRow;
500
                } else {
501
                        int num = ((Integer) relations.get(integer)).intValue();
502
                        IRowEdited aux = expansionFile.getRow(num);
503
                        edRow = new DefaultRowEdited(aux.getLinkedRow().cloneRow(), aux
504
                                        .getStatus(), index);
505
                        stop();
506
                        return edRow;
507
                }
508
        }
509

    
510
        /**
511
         * Elimina una geometria. Si es una geometr?a original de la capa en edici?n
512
         * se marca como eliminada (haya sido modificada o no). Si es una geometr?a
513
         * a?adida posteriormente se invalida en el fichero de expansi?n, para que
514
         * una futura compactaci?n termine con ella.
515
         *
516
         * @param index
517
         *            ?ndice de la geometr?a.
518
         *
519
         * @throws DriverIOException
520
         * @throws IOException
521
         */
522
        public IRow doRemoveRow(int index, int sourceType)
523
                        throws DriverIOException, IOException {
524
                boolean cancel = fireBeforeRemoveRow(index, sourceType);
525
                if (cancel)
526
                        return null;
527
                // Llega el calculatedIndex
528
                Integer integer = new Integer(index);
529

    
530
                IFeature feat = null;
531
                delRows.set(index, true);
532
                // Si la geometr?a no ha sido modificada
533
                if (!relations.containsKey(integer)) {
534

    
535
                        try {
536
                                feat = (DefaultFeature) (ova.getFeature(index));
537
                        } catch (DriverException e) {
538
                                // TODO Auto-generated catch block
539
                                e.printStackTrace();
540
                        }
541
                } else {
542
                        int num = ((Integer) relations.get(integer)).intValue();
543
                        feat = (IFeature) expansionFile.getRow(num).getLinkedRow();
544
                        // expansionFile.invalidateRow(num);
545
                }
546
                System.err.println("Elimina una Row en la posici?n: " + index);
547
                // Se actualiza el ?ndice
548
                if (feat != null) {
549
                        Rectangle2D r = feat.getGeometry().getBounds2D();
550
                        boolean borrado = this.index.remove(new Envelope(r.getX(), r.getX()
551
                                        + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
552
                                        new Integer(index));
553
                        System.out.println("Est? borrado : " + borrado);
554
                        System.out.println("Index.lenght : " + this.index.size());
555
                        isFullExtentDirty = true;
556
                }
557
                setSelection(new FBitSet());
558
                fireAfterRemoveRow(index, sourceType);
559
                return feat;
560
        }
561

    
562
        /**
563
         * Si se intenta modificar una geometr?a original de la capa en edici?n se
564
         * a?ade al fichero de expansi?n y se registra la posici?n en la que se
565
         * a?adi?. Si se intenta modificar una geometria que se encuentra en el
566
         * fichero de expansi?n (por ser nueva o original pero modificada) se invoca
567
         * el m?todo modifyGeometry y se actualiza el ?ndice de la geometria en el
568
         * fichero.
569
         *
570
         * @param calculatedIndex
571
         *            DOCUMENT ME!
572
         * @param feat
573
         *            DOCUMENT ME!
574
         *
575
         * @return position inside ExpansionFile
576
         *
577
         * @throws IOException
578
         * @throws DriverIOException
579
         */
580
        public int doModifyRow(int calculatedIndex, IRow feat, int sourceType)
581
                        throws IOException, DriverIOException {
582
                boolean cancel = fireBeforeModifyRow(feat, calculatedIndex, sourceType);
583
                if (cancel)
584
                        return -1;
585
                int posAnteriorInExpansionFile = -1;
586
                Integer integer = new Integer(calculatedIndex);
587

    
588
                IFeature featAnt = null;
589
//                System.err.println("Modifica una Row en la posici?n: "
590
//                                + calculatedIndex);
591
                // Si la geometr?a no ha sido modificada
592
                if (!relations.containsKey(integer)) {
593
                        int newPosition = expansionFile.addRow(feat,
594
                                        IRowEdited.STATUS_MODIFIED, actualIndexFields);
595
                        relations.put(integer, new Integer(newPosition));
596

    
597
                        if (sourceType == EditionEvent.GRAPHIC) {
598
                                // Se actualiza el ?ndice espacial
599
                                try {
600
                                        featAnt = (DefaultFeature) (ova.getFeature(calculatedIndex));
601
                                } catch (DriverException e) {
602
                                        e.printStackTrace();
603
                                }
604
                                IGeometry g = featAnt.getGeometry();
605
                                Rectangle2D rAnt = g.getBounds2D();
606
                                Rectangle2D r = ((IFeature) feat).getGeometry().getBounds2D();
607
                                this.index.remove(new Envelope(rAnt.getX(), rAnt.getX()
608
                                                + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
609
                                                + rAnt.getHeight()), new Integer(calculatedIndex));
610
                                this.index.insert(new Envelope(r.getX(), r.getX()
611
                                                + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
612
                                                new Integer(calculatedIndex));
613
                        }
614
                } else {
615
                        // Obtenemos el ?ndice en el fichero de expansi?n
616
                        int num = ((Integer) relations.get(integer)).intValue();
617
                        posAnteriorInExpansionFile = num;
618

    
619
                        // Obtenemos la geometr?a para actualiza el ?ndice
620
                        // espacialposteriormente
621
                        featAnt = (IFeature) expansionFile.getRow(num).getLinkedRow();
622

    
623
                        /*
624
                         * Se modifica la geometr?a y nos guardamos el ?ndice dentro del
625
                         * fichero de expansi?n en el que se encuentra la geometr?a
626
                         * modificada
627
                         */
628
                        num = expansionFile.modifyRow(num, feat, actualIndexFields);
629

    
630
                        /*
631
                         * Actualiza la relaci?n del ?ndice de la geometr?a al ?ndice en el
632
                         * fichero de expansi?n.
633
                         */
634
                        relations.put(integer, new Integer(num));
635
                        if (sourceType == EditionEvent.GRAPHIC) {
636
                                // Se modifica el ?ndice espacial
637
                                Rectangle2D rAnt = featAnt.getGeometry().getBounds2D();
638
                                Rectangle2D r = ((IFeature) feat).getGeometry().getBounds2D();
639
                                this.index.remove(new Envelope(rAnt.getX(), rAnt.getX()
640
                                                + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
641
                                                + rAnt.getHeight()), new Integer(calculatedIndex));
642
                                this.index.insert(new Envelope(r.getX(), r.getX()
643
                                                + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
644
                                                new Integer(calculatedIndex));
645
                        }
646
                }
647
                isFullExtentDirty = true;
648
                fireAfterModifyRow(calculatedIndex, sourceType);
649
                return posAnteriorInExpansionFile;
650
        }
651

    
652
        /**
653
         * Actualiza en el mapa de ?ndices, la posici?n en la que estaba la
654
         * geometr?a antes de ser modificada. Se marca como v?lida, en caso de que
655
         * fuera una modificaci?n de una geometr?a que estuviese en el fichero de
656
         * expansi?n antes de ser modificada y se pone el puntero de escritura del
657
         * expansion file a justo despues de la penultima geometr?a
658
         *
659
         * @param calculatedIndex
660
         *            ?ndice de la geometr?a que se quiere deshacer su modificaci?n
661
         * @param previousExpansionFileIndex
662
         *            ?ndice que ten?a antes la geometr?a en el expansionFile. Si
663
         *            vale -1 quiere decir que es una modificaci?n de una geometr?a
664
         *            original y por tanto no hay que actualizar el mapa de indices
665
         *            sino eliminar su entrada.
666
         *
667
         * @throws IOException
668
         * @throws DriverIOException
669
         */
670
        public void undoModifyRow(int calculatedIndex,
671
                        int previousExpansionFileIndex, int sourceType) throws IOException,
672
                        DriverIOException {
673

    
674
                // Llega el CalculatedIndex
675
                /*
676
                 * Si la acci?n de modificar se realiz? sobre una geometr?a original
677
                 */
678
                if (previousExpansionFileIndex == -1) {
679

    
680
                        // Se obtiene la geometr?a para actualizar el ?ndice
681
                        // IGeometry g = ((DefaultFeature)
682
                        // getRow(calculatedIndex).getLinkedRow()).getGeometry();
683
                        int inverse = getInversedIndex(calculatedIndex);
684
                        DefaultFeature df = (DefaultFeature) getRow(inverse).getLinkedRow();
685
                        boolean cancel = fireBeforeModifyRow(df, calculatedIndex,
686
                                        sourceType);
687
                        if (cancel)
688
                                return;
689
                        IGeometry g = df.getGeometry();
690
                        // IGeometry g = ova.getShape(calculatedIndex);
691
                        Rectangle2D r = g.getBounds2D();
692

    
693
                        // Se elimina de las relaciones y del fichero de expansi?n
694
                        relations.remove(new Integer(calculatedIndex));
695
                        expansionFile.deleteLastRow();
696

    
697
                        // Se actualizan los ?ndices
698
                        IGeometry gAnt = ova.getShape(calculatedIndex);
699
                        /*
700
                         * IGeometry gAnt = ((DefaultFeature) getRow(calculatedIndex)
701
                         * .getLinkedRow()).getGeometry();
702
                         */
703
                        Rectangle2D rAnt = gAnt.getBounds2D();
704
                        this.index.remove(new Envelope(r.getX(), r.getX() + r.getWidth(), r
705
                                        .getY(), r.getY() + r.getHeight()), new Integer(
706
                                        calculatedIndex));
707
                        this.index.insert(new Envelope(rAnt.getX(), rAnt.getX()
708
                                        + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
709
                                        + rAnt.getHeight()), new Integer(calculatedIndex));
710
                } else {
711
                        // Se obtiene la geometr?a para actualizar el ?ndice
712
                        IGeometry g = null;
713
                        int inverse = getInversedIndex(calculatedIndex);
714
                        DefaultFeature df = (DefaultFeature) getRow(inverse).getLinkedRow();
715
                        boolean cancel = fireBeforeModifyRow(df, calculatedIndex,
716
                                        sourceType);
717
                        if (cancel)
718
                                return;
719
                        g = df.getGeometry();
720
                        System.out.println("Actual: " + g.toString());
721

    
722
                        Rectangle2D r = g.getBounds2D();
723
                        this.index.remove(new Envelope(r.getX(), r.getX() + r.getWidth(), r
724
                                        .getY(), r.getY() + r.getHeight()), new Integer(
725
                                        calculatedIndex));
726

    
727
                        // Se actualiza la relaci?n de ?ndices
728
                        // Integer integer = new Integer(geometryIndex);
729
                        relations.put(new Integer(calculatedIndex), new Integer(
730
                                        previousExpansionFileIndex));
731

    
732
                        // Se recupera la geometr?a
733
                        // expansionFile.validateRow(previousExpansionFileIndex);
734

    
735
                        // Se actualizan los ?ndices
736
                        // g = ((IFeature)
737
                        // (expansionFile.getRow(previousExpansionFileIndex).getLinkedRow())).getGeometry();
738
                        // System.out.println("Anterior a la que volvemos : " +
739
                        // g.toString());
740
                        g = ((DefaultFeature) getRow(inverse).getLinkedRow()).getGeometry();
741
                        r = g.getBounds2D();
742
                        this.index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r
743
                                        .getY(), r.getY() + r.getHeight()), new Integer(
744
                                        calculatedIndex));
745

    
746
                }
747
                fireAfterModifyRow(calculatedIndex, sourceType);
748
        }
749

    
750
        /**
751
         * A?ade una geometria al fichero de expansi?n y guarda la correspondencia
752
         * en la tabla relations.
753
         *
754
         * @param feat
755
         *            geometr?a a guardar.
756
         *
757
         * @return calculatedIndex
758
         *
759
         * @throws DriverIOException
760
         * @throws IOException
761
         */
762
        public int doAddRow(IRow feat, int sourceType) throws DriverIOException,
763
                        IOException {
764
                int calculatedIndex = super.doAddRow(feat, sourceType);
765
                // Actualiza el ?ndice espacial
766
                IGeometry g = ((IFeature) feat).getGeometry();
767
                Rectangle2D r = g.getBounds2D();
768
                index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r.getY(),
769
                                r.getY() + r.getHeight()), new Integer(calculatedIndex));
770
                isFullExtentDirty = true;
771
                return calculatedIndex;
772
        }
773

    
774
        /**
775
         * Se desmarca como invalidada en el fichero de expansion o como eliminada
776
         * en el fichero original
777
         *
778
         * @param index
779
         *            DOCUMENT ME!
780
         *
781
         * @throws IOException
782
         * @throws DriverIOException
783
         */
784
        public void undoRemoveRow(int index, int sourceType) throws IOException,
785
                        DriverIOException {
786
                super.undoRemoveRow(index, sourceType);
787

    
788
                IGeometry g = null;
789
                g = ((IFeature) getRow(getInversedIndex(index)).getLinkedRow()).getGeometry();
790

    
791
                Rectangle2D r = g.getBounds2D();
792
                this.index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r
793
                                .getY(), r.getY() + r.getHeight()), new Integer(index));
794
        }
795

    
796
        /**
797
         * Se elimina del final del fichero de expansi?n poniendo el puntero de
798
         * escritura apuntando al final de la pen?ltima geometr?a. Deber? quitar la
799
         * relaci?n del mapa de relaciones
800
         *
801
         * @param index
802
         *            ?ndice de la geometr?a que se a?adi?
803
         *
804
         * @throws DriverIOException
805
         * @throws IOException
806
         */
807
        public void undoAddRow(int calculatedIndex, int sourceType)
808
                        throws DriverIOException, IOException {
809
                int inverse = getInversedIndex(calculatedIndex);
810
                IGeometry g = ((IFeature) getRow(inverse).getLinkedRow()).getGeometry();
811
                Rectangle2D r = g.getBounds2D();
812
                this.index.remove(new Envelope(r.getX(), r.getX() + r.getWidth(), r
813
                                .getY(), r.getY() + r.getHeight()),
814
                                new Integer(calculatedIndex));
815

    
816
                super.undoAddRow(calculatedIndex, sourceType);
817
                setSelection(new FBitSet());
818
        }
819

    
820
        /**
821
         * Obtiene las geometr?as que se encuentran en el rect?ngulo que se pasa
822
         * como par?metro haciendo uso del ?ndice espacial
823
         *
824
         * @param r
825
         *            Rect?ngulo indicando la porci?n del espacio para el cual se
826
         *            quiere saber los ?ndices de las geometr?as que se encuentran
827
         *            dentro de ?l
828
         *
829
         * @return Array de ?ndices para su uso con getGeometry, removeGeometry, ...
830
         */
831
        /*
832
         * public int[] getRowsIndexes_OL(Rectangle2D r) { Envelope e = new
833
         * Envelope(r.getX(), r.getX() + r.getWidth(), r.getY(), r.getY() +
834
         * r.getHeight()); List l = index.query(e); int[] indexes = new
835
         * int[l.size()];
836
         *
837
         * for (int index = 0; index < l.size(); index++) { Integer i = (Integer)
838
         * l.get(index); indexes[index] = getInversedIndex(i.intValue()); }
839
         *
840
         * return indexes; }
841
         */
842
        /**
843
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeCount()
844
         */
845
        public int getShapeCount() throws DriverIOException {
846
                try {
847
                        return getRowCount();
848
                } catch (IOException e) {
849
                        throw new DriverIOException(e);
850
                }
851
        }
852

    
853
        /**
854
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getFullExtent()
855
         */
856
        public Rectangle2D getFullExtent() throws DriverIOException {
857
                if (fullExtent == null) {
858
                        fullExtent = ova.getFullExtent();
859
                }
860

    
861
                if (isFullExtentDirty) {
862
                        fullExtent = reCalculateFullExtent();
863
                        isFullExtentDirty = false;
864
                }
865
                return fullExtent;
866
        }
867

    
868
        /**
869
         * Use it BEFORE writing to a file.
870
         *
871
         * @return real full extent.
872
         * @throws DriverIOException
873
         */
874
        public Rectangle2D reCalculateFullExtent() throws DriverIOException {
875
                if (getShapeCount() > 0) {
876
                        fullExtent = getShape(0).getBounds2D();
877
                        for (int i = 1; i < getShapeCount(); i++) {
878
                                fullExtent.add(getShape(i).getBounds2D());
879
                        }
880
                } else {
881
                        fullExtent = ova.getFullExtent();
882
                }
883
                return fullExtent;
884
        }
885

    
886
        /**
887
         * En la implementaci?n por defecto podemos hacer que cada feature tenga ID =
888
         * numero de registro. En el DBAdapter podr?amos "overrride" este m?todo y
889
         * poner como ID de la Feature el campo ?nico escogido en la base de datos.
890
         *
891
         * @param numReg
892
         * @return
893
         * @throws DriverException
894
         */
895
        public IFeature getFeature(int numReg) throws DriverException {
896
                IGeometry geom;
897
                IFeature feat = null;
898
                try {
899
                        geom = getShape(numReg);
900
                        DataSource rs = getRecordset();
901
                        Value[] regAtt = new Value[rs.getFieldCount()];
902
                        for (int fieldId = 0; fieldId < rs.getFieldCount(); fieldId++) {
903
                                regAtt[fieldId] = rs.getFieldValue(numReg, fieldId);
904
                        }
905
                        feat = new DefaultFeature(geom, regAtt, numReg + "");
906
                } catch (DriverIOException e) {
907
                        DriverIOExceptionType type =
908
                                new DriverIOExceptionType();
909
                        type.setDriverName(this.getDriver().getName());
910
                        throw new DriverException(e, type);
911

    
912
                } catch (DriverLoadException e) {
913
                        DriverNotLoadedExceptionType type =
914
                                new DriverNotLoadedExceptionType();
915
                        type.setDriverName(getDriver().getName());
916
                        throw new DriverException(e, type);
917

    
918

    
919
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
920

    
921
                        throw new DriverException(e);
922
                }
923
                return feat;
924
        }
925

    
926
        public void stopEdition(IWriter writer, int sourceType)
927
                        throws EditionException {
928
//                ISpatialWriter spatialWriter = (ISpatialWriter) writer;
929
//                spatialWriter.setFlatness(FConverter.flatness);
930
                super.stopEdition(writer, sourceType);
931
                try {
932
                        ova.getDriver().reload();
933
                } catch (IOException e) {
934
                        e.printStackTrace();
935
                        throw new EditionException(e);
936
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
937
                        e.printStackTrace();
938
                        throw new EditionException(e);
939
                }
940
                index=null;
941
                writer=null;
942
        }
943

    
944
        public Rectangle2D getShapeBounds(int index) throws IOException {
945
                // Solo se utiliza cuando el driver es BoundedShapes
946
                // Si no est? en el fichero de expansi?n
947
                Integer integer = new Integer((int) index);
948
                if (!relations.containsKey(integer)) {
949
                        if (ova.getDriver() instanceof BoundedShapes) {
950
                                BoundedShapes bs = (BoundedShapes) ova.getDriver();
951
                                return bs.getShapeBounds(index);
952
                        } else {
953
                                return ova.getDriver().getShape(index).getBounds2D();
954
                        }
955

    
956
                } else {
957
                        int num = ((Integer) relations.get(integer)).intValue();
958
                        DefaultRowEdited feat;
959
                        feat = (DefaultRowEdited) expansionFile.getRow(num);
960
                        if (feat.getStatus() == IRowEdited.STATUS_DELETED)
961
                                return null;
962
                        IGeometry geom = ((IFeature) feat.getLinkedRow()).getGeometry();
963
                        return geom.getBounds2D();// getGeometry();
964
                }
965

    
966
        }
967

    
968
        public int getShapeType(int index) {
969
                try {
970
                        return ova.getShapeType();
971
                } catch (DriverIOException e) {
972
                        // TODO Auto-generated catch block
973
                        e.printStackTrace();
974
                }
975
                return FShape.MULTI;
976
        }
977

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

    
1009
                } catch (DriverLoadException ex) {
1010
                        DriverNotLoadedExceptionType type =
1011
                                new DriverNotLoadedExceptionType();
1012
                        type.setDriverName(getDriver().getName());
1013
                        throw new DriverException(ex, type);
1014
                } catch (DriverIOException ex) {
1015
                        DriverIOExceptionType type =
1016
                                new DriverIOExceptionType();
1017
                        type.setDriverName(this.getDriver().getName());
1018
                        throw new DriverException(ex, type);
1019
                }
1020
                return feats;
1021
        }
1022

    
1023
        public void setSpatialIndex(SpatialIndex spatialIndex) {
1024
                index = (Quadtree) spatialIndex;
1025
        }
1026

    
1027
        public void setFullExtent(Rectangle2D fullExtent2) {
1028
                fullExtent = fullExtent2;
1029
        }
1030

    
1031
        /**
1032
         * DOCUMENT ME!
1033
         *
1034
         * @return DOCUMENT ME!
1035
         */
1036
        public Image getSelectionImage() {
1037
                return selectionImage;
1038
        }
1039

    
1040
        public Image getHandlersImage() {
1041
                return handlersImage;
1042
        }
1043

    
1044
        /**
1045
         * DOCUMENT ME!
1046
         *
1047
         * @param i
1048
         *            DOCUMENT ME!
1049
         */
1050
        public void setSelectionImage(Image i) {
1051
                selectionImage = i;
1052
        }
1053

    
1054
        public void setHandlersImage(BufferedImage handlersImage) {
1055
                this.handlersImage = handlersImage;
1056
        }
1057

    
1058
        public void cancelEdition(int sourceType) throws IOException {
1059
                super.cancelEdition(sourceType);
1060
                index=null;
1061
                setWriter(null);
1062
                System.gc();
1063
        }
1064

    
1065
//        public double getFlatness() {
1066
//                return flatness;
1067
//        }
1068
//
1069
//        public void setFlatness(double d) {
1070
//                flatness=d;
1071
//        }
1072

    
1073
}