Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / edition / VectorialEditableAdapter.java @ 7461

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

    
235
import java.awt.Image;
236
import java.awt.geom.Rectangle2D;
237
import java.awt.image.BufferedImage;
238
import java.io.IOException;
239
import java.util.List;
240

    
241
import com.hardcode.driverManager.Driver;
242
import com.hardcode.driverManager.DriverLoadException;
243
import com.hardcode.gdbms.engine.data.DataSource;
244
import com.hardcode.gdbms.engine.values.Value;
245
import com.iver.cit.gvsig.fmap.DriverException;
246
import com.iver.cit.gvsig.fmap.DriverIOExceptionType;
247
import com.iver.cit.gvsig.fmap.DriverNotLoadedExceptionType;
248
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
249
import com.iver.cit.gvsig.fmap.core.FShape;
250
import com.iver.cit.gvsig.fmap.core.IFeature;
251
import com.iver.cit.gvsig.fmap.core.IGeometry;
252
import com.iver.cit.gvsig.fmap.core.IRow;
253
import com.iver.cit.gvsig.fmap.core.v02.FConverter;
254
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
255
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
256
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
257
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
258
import com.iver.cit.gvsig.fmap.layers.FBitSet;
259
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
260
import com.vividsolutions.jts.geom.Envelope;
261
import com.vividsolutions.jts.index.SpatialIndex;
262
import com.vividsolutions.jts.index.quadtree.Quadtree;
263

    
264
/**
265
 * @author fjp
266
 *
267
 */
268
public class VectorialEditableAdapter extends EditableAdapter implements
269
                ReadableVectorial, BoundedShapes {
270
        protected ReadableVectorial ova;
271

    
272
        protected Quadtree index;
273

    
274
        protected Rectangle2D fullExtent;
275

    
276
        protected Image selectionImage;
277

    
278
        protected BufferedImage handlersImage;
279

    
280
        //private double flatness=0.8;
281
        /*
282
         * private class MyFeatureIterator implements IFeatureIterator { int numReg =
283
         * 0; Rectangle2D rect; String epsg; IFeatureIterator origFeatIt; boolean
284
         * bHasNext = true;
285
         *
286
         * public MyFeatureIterator(Rectangle2D r, String strEPSG) throws
287
         * DriverException { rect = r; epsg = strEPSG; origFeatIt =
288
         * ova.getFeatureIterator(r, epsg); } public boolean hasNext() throws
289
         * DriverException { return bHasNext; }
290
         *
291
         * public IFeature next() throws DriverException { IFeature aux =
292
         * origFeatIt.next(); return null; }
293
         *
294
         * public void closeIterator() throws DriverException {
295
         *  }
296
         *  }
297
         */
298

    
299
        public VectorialEditableAdapter() {
300
                super();
301
        }
302

    
303
        public void setOriginalVectorialAdapter(ReadableVectorial rv) {
304
                ova = rv;
305
                try {
306
                        setOriginalDataSource(rv.getRecordset());
307
                } catch (DriverLoadException e) {
308
                        e.printStackTrace();
309
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
310
                        // TODO Auto-generated catch block
311
                        e.printStackTrace();
312
                }
313
        }
314

    
315
        /*
316
         * (non-Javadoc)
317
         *
318
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#start()
319
         */
320
        public void start() throws DriverIOException {
321
                ova.start();
322
        }
323

    
324
        public IWriter getWriter() {
325
                if (ova.getDriver() instanceof IWriteable)
326
                {
327
                        IWriter writer = ((IWriteable) ova.getDriver()).getWriter();
328
                        if (writer instanceof ISpatialWriter)
329
                                return writer;
330
                }
331
                return null;
332
        }
333

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

    
343
        /*
344
         * (non-Javadoc)
345
         *
346
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShape(int)
347
         */
348
        public IGeometry getShape(int rowIndex) throws DriverIOException {
349
                // Si no est? en el fichero de expansi?n
350
                int calculatedIndex = getCalculatedIndex(rowIndex);
351
                Integer integer = new Integer(calculatedIndex);
352
                if (!relations.containsKey(integer)) {
353
                        // Si ha sido eliminada
354
                        /*
355
                         * if (delRows.get(integer.intValue())) { return null; } else {
356
                         */
357
                        return ova.getShape(calculatedIndex);
358
                        // }
359
                } else {
360
                        int num = ((Integer) relations.get(integer)).intValue();
361
                        DefaultRowEdited feat;
362
                        try {
363
                                feat = (DefaultRowEdited) expansionFile.getRow(num);
364
                                return ((IFeature) feat.getLinkedRow()).getGeometry()
365
                                                .cloneGeometry();// getGeometry();
366
                        } catch (IOException e) {
367
                                e.printStackTrace();
368
                                throw new DriverIOException(e);
369
                        }
370
                }
371

    
372
        }
373

    
374
        /*
375
         * (non-Javadoc)
376
         *
377
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeType()
378
         */
379
        public int getShapeType() throws DriverIOException {
380
                return ova.getShapeType();
381
        }
382

    
383
        public ReadableVectorial getOriginalAdapter() {
384
                return ova;
385
        }
386

    
387
        public VectorialDriver getDriver() {
388
                return ova.getDriver();
389
        }
390

    
391
        public void setDriver(VectorialDriver driver) {
392
                this.ova.setDriver(driver);
393
        }
394

    
395
        public DriverAttributes getDriverAttributes() {
396
                return ova.getDriverAttributes();
397
        }
398

    
399
        /**
400
         * DOCUMENT ME!
401
         *
402
         * @throws EditionException
403
         *             DOCUMENT ME!
404
         */
405
        public void startEdition(int sourceType) throws EditionException {
406
                super.startEdition(sourceType);
407
                Driver drv = ova.getDriver();
408
                if (drv instanceof IWriteable)
409
                {
410
                        setWriter(((IWriteable) drv).getWriter());
411
                }
412

    
413

    
414
                try {
415
                        expansionFile.open();
416
                        if (index == null || fullExtent == null) {
417
                                // TODO: Si la capa dispone de un ?ndice espacial, hacer
418
                                // algo aqu? para que se use ese ?ndice espacial.
419
                                index = new Quadtree();
420

    
421
                                for (int i = 0; i < ova.getShapeCount(); i++) {
422
                                        IGeometry g = null;
423
                                        try {
424
                                                g = ((DefaultFeature) ova.getFeature(i)).getGeometry();
425
                                        } catch (DriverException e1) {
426
                                                // TODO Auto-generated catch block
427
                                                e1.printStackTrace();
428
                                        }
429

    
430
                                        if (g == null) {
431
                                                continue;
432
                                        }
433

    
434
                                        Rectangle2D r = g.getBounds2D();
435
                                        Envelope e = new Envelope(r.getX(),
436
                                                        r.getX() + r.getWidth(), r.getY(), r.getY()
437
                                                                        + r.getHeight());
438
                                        index.insert(e, new Integer(i));
439
                                        if (fullExtent == null) {
440
                                                fullExtent = r;
441
                                        } else {
442
                                                fullExtent = fullExtent.createUnion(r);
443
                                        }
444
                                }
445
                        }
446
                } catch (DriverIOException e) {
447
                        throw new EditionException(e);
448
                } catch (IOException e) {
449
                        throw new EditionException(e);
450
                }
451

    
452
                System.err.println("Se han metido en el ?ndice "
453
                                + index.queryAll().size() + " geometr?as");
454
        }
455

    
456
        /*
457
         * (non-Javadoc)
458
         *
459
         * @see com.iver.cit.gvsig.fmap.edition.IEditableSource#getRow(int)
460
         */
461
        public IRowEdited getRow(int index) throws DriverIOException, IOException {
462
                int calculatedIndex = getCalculatedIndex(index);
463
                Integer integer = new Integer(calculatedIndex);
464
                // Si no est? en el fichero de expansi?n
465
                DefaultRowEdited edRow = null;
466
                if (!relations.containsKey(integer)) {
467
                        try {
468
                                edRow = new DefaultRowEdited(ova.getFeature(calculatedIndex),
469
                                                DefaultRowEdited.STATUS_ORIGINAL, index);
470
                                return createExternalRow(edRow, 0);
471
                        } catch (DriverException e) {
472
                                // TODO Auto-generated catch block
473
                                e.printStackTrace();
474
                        }
475

    
476
                        return edRow;
477
                } else {
478
                        int num = ((Integer) relations.get(integer)).intValue();
479
                        IRowEdited aux = expansionFile.getRow(num);
480
                        edRow = new DefaultRowEdited(aux.getLinkedRow().cloneRow(), aux
481
                                        .getStatus(), index);
482

    
483
                        return edRow;
484
                }
485
        }
486

    
487
        /**
488
         * Elimina una geometria. Si es una geometr?a original de la capa en edici?n
489
         * se marca como eliminada (haya sido modificada o no). Si es una geometr?a
490
         * a?adida posteriormente se invalida en el fichero de expansi?n, para que
491
         * una futura compactaci?n termine con ella.
492
         *
493
         * @param index
494
         *            ?ndice de la geometr?a.
495
         *
496
         * @throws DriverIOException
497
         * @throws IOException
498
         */
499
        public IRow doRemoveRow(int index, int sourceType)
500
                        throws DriverIOException, IOException {
501
                boolean cancel = fireBeforeRemoveRow(index, sourceType);
502
                if (cancel)
503
                        return null;
504
                // Llega el calculatedIndex
505
                Integer integer = new Integer(index);
506

    
507
                IFeature feat = null;
508
                delRows.set(index, true);
509
                // Si la geometr?a no ha sido modificada
510
                if (!relations.containsKey(integer)) {
511

    
512
                        try {
513
                                feat = (DefaultFeature) (ova.getFeature(index));
514
                        } catch (DriverException e) {
515
                                // TODO Auto-generated catch block
516
                                e.printStackTrace();
517
                        }
518
                } else {
519
                        int num = ((Integer) relations.get(integer)).intValue();
520
                        feat = (IFeature) expansionFile.getRow(num).getLinkedRow();
521
                        // expansionFile.invalidateRow(num);
522
                }
523
                System.err.println("Elimina una Row en la posici?n: " + index);
524
                // Se actualiza el ?ndice
525
                if (feat != null) {
526
                        Rectangle2D r = feat.getGeometry().getBounds2D();
527
                        boolean borrado = this.index.remove(new Envelope(r.getX(), r.getX()
528
                                        + r.getWidth(), r.getY(), r.getY() + r.getHeight()),
529
                                        new Integer(index));
530
                        System.out.println("Est? borrado : " + borrado);
531
                        System.out.println("Index.lenght : " + this.index.size());
532
                        isFullExtentDirty = true;
533
                }
534
                setSelection(new FBitSet());
535
                fireAfterRemoveRow(index, sourceType);
536
                return feat;
537
        }
538

    
539
        /**
540
         * Si se intenta modificar una geometr?a original de la capa en edici?n se
541
         * a?ade al fichero de expansi?n y se registra la posici?n en la que se
542
         * a?adi?. Si se intenta modificar una geometria que se encuentra en el
543
         * fichero de expansi?n (por ser nueva o original pero modificada) se invoca
544
         * el m?todo modifyGeometry y se actualiza el ?ndice de la geometria en el
545
         * fichero.
546
         *
547
         * @param calculatedIndex
548
         *            DOCUMENT ME!
549
         * @param feat
550
         *            DOCUMENT ME!
551
         *
552
         * @return position inside ExpansionFile
553
         *
554
         * @throws IOException
555
         * @throws DriverIOException
556
         */
557
        public int doModifyRow(int calculatedIndex, IRow feat, int sourceType)
558
                        throws IOException, DriverIOException {
559
                boolean cancel = fireBeforeModifyRow(feat, calculatedIndex, sourceType);
560
                if (cancel)
561
                        return -1;
562
                int posAnteriorInExpansionFile = -1;
563
                Integer integer = new Integer(calculatedIndex);
564

    
565
                IFeature featAnt = null;
566
                System.err.println("Modifica una Row en la posici?n: "
567
                                + calculatedIndex);
568
                // Si la geometr?a no ha sido modificada
569
                if (!relations.containsKey(integer)) {
570
                        int newPosition = expansionFile.addRow(feat,
571
                                        IRowEdited.STATUS_MODIFIED, actualIndexFields);
572
                        relations.put(integer, new Integer(newPosition));
573

    
574
                        // Se actualiza el ?ndice espacial
575
                        try {
576
                                featAnt = (DefaultFeature) (ova.getFeature(calculatedIndex));
577
                        } catch (DriverException e) {
578
                                e.printStackTrace();
579
                        }
580
                        IGeometry g = featAnt.getGeometry();
581
                        Rectangle2D rAnt = g.getBounds2D();
582
                        Rectangle2D r = ((IFeature) feat).getGeometry().getBounds2D();
583
                        this.index.remove(new Envelope(rAnt.getX(), rAnt.getX()
584
                                        + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
585
                                        + rAnt.getHeight()), new Integer(calculatedIndex));
586
                        this.index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r
587
                                        .getY(), r.getY() + r.getHeight()), new Integer(
588
                                        calculatedIndex));
589
                } else {
590
                        // Obtenemos el ?ndice en el fichero de expansi?n
591
                        int num = ((Integer) relations.get(integer)).intValue();
592
                        posAnteriorInExpansionFile = num;
593

    
594
                        // Obtenemos la geometr?a para actualiza el ?ndice
595
                        // espacialposteriormente
596
                        featAnt = (IFeature) expansionFile.getRow(num).getLinkedRow();
597

    
598
                        /*
599
                         * Se modifica la geometr?a y nos guardamos el ?ndice dentro del
600
                         * fichero de expansi?n en el que se encuentra la geometr?a
601
                         * modificada
602
                         */
603
                        num = expansionFile.modifyRow(num, feat, actualIndexFields);
604

    
605
                        /*
606
                         * Actualiza la relaci?n del ?ndice de la geometr?a al ?ndice en el
607
                         * fichero de expansi?n.
608
                         */
609
                        relations.put(integer, new Integer(num));
610

    
611
                        // Se modifica el ?ndice espacial
612
                        Rectangle2D rAnt = featAnt.getGeometry().getBounds2D();
613
                        Rectangle2D r = ((IFeature) feat).getGeometry().getBounds2D();
614
                        this.index.remove(new Envelope(rAnt.getX(), rAnt.getX()
615
                                        + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
616
                                        + rAnt.getHeight()), new Integer(calculatedIndex));
617
                        this.index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r
618
                                        .getY(), r.getY() + r.getHeight()), new Integer(
619
                                        calculatedIndex));
620
                }
621
                isFullExtentDirty = true;
622
                fireAfterModifyRow(calculatedIndex, sourceType);
623
                return posAnteriorInExpansionFile;
624
        }
625

    
626
        /**
627
         * Actualiza en el mapa de ?ndices, la posici?n en la que estaba la
628
         * geometr?a antes de ser modificada. Se marca como v?lida, en caso de que
629
         * fuera una modificaci?n de una geometr?a que estuviese en el fichero de
630
         * expansi?n antes de ser modificada y se pone el puntero de escritura del
631
         * expansion file a justo despues de la penultima geometr?a
632
         *
633
         * @param calculatedIndex
634
         *            ?ndice de la geometr?a que se quiere deshacer su modificaci?n
635
         * @param previousExpansionFileIndex
636
         *            ?ndice que ten?a antes la geometr?a en el expansionFile. Si
637
         *            vale -1 quiere decir que es una modificaci?n de una geometr?a
638
         *            original y por tanto no hay que actualizar el mapa de indices
639
         *            sino eliminar su entrada.
640
         *
641
         * @throws IOException
642
         * @throws DriverIOException
643
         */
644
        public void undoModifyRow(int calculatedIndex,
645
                        int previousExpansionFileIndex, int sourceType) throws IOException,
646
                        DriverIOException {
647

    
648
                // Llega el CalculatedIndex
649
                /*
650
                 * Si la acci?n de modificar se realiz? sobre una geometr?a original
651
                 */
652
                if (previousExpansionFileIndex == -1) {
653

    
654
                        // Se obtiene la geometr?a para actualizar el ?ndice
655
                        // IGeometry g = ((DefaultFeature)
656
                        // getRow(calculatedIndex).getLinkedRow()).getGeometry();
657
                        int inverse = getInversedIndex(calculatedIndex);
658
                        DefaultFeature df = (DefaultFeature) getRow(inverse).getLinkedRow();
659
                        boolean cancel = fireBeforeModifyRow(df, calculatedIndex,
660
                                        sourceType);
661
                        if (cancel)
662
                                return;
663
                        IGeometry g = df.getGeometry();
664
                        // IGeometry g = ova.getShape(calculatedIndex);
665
                        Rectangle2D r = g.getBounds2D();
666

    
667
                        // Se elimina de las relaciones y del fichero de expansi?n
668
                        relations.remove(new Integer(calculatedIndex));
669
                        expansionFile.deleteLastRow();
670

    
671
                        // Se actualizan los ?ndices
672
                        IGeometry gAnt = ova.getShape(calculatedIndex);
673
                        /*
674
                         * IGeometry gAnt = ((DefaultFeature) getRow(calculatedIndex)
675
                         * .getLinkedRow()).getGeometry();
676
                         */
677
                        Rectangle2D rAnt = gAnt.getBounds2D();
678
                        this.index.remove(new Envelope(r.getX(), r.getX() + r.getWidth(), r
679
                                        .getY(), r.getY() + r.getHeight()), new Integer(
680
                                        calculatedIndex));
681
                        this.index.insert(new Envelope(rAnt.getX(), rAnt.getX()
682
                                        + rAnt.getWidth(), rAnt.getY(), rAnt.getY()
683
                                        + rAnt.getHeight()), new Integer(calculatedIndex));
684
                } else {
685
                        // Se obtiene la geometr?a para actualizar el ?ndice
686
                        IGeometry g = null;
687
                        int inverse = getInversedIndex(calculatedIndex);
688
                        DefaultFeature df = (DefaultFeature) getRow(inverse).getLinkedRow();
689
                        boolean cancel = fireBeforeModifyRow(df, calculatedIndex,
690
                                        sourceType);
691
                        if (cancel)
692
                                return;
693
                        g = df.getGeometry();
694
                        System.out.println("Actual: " + g.toString());
695

    
696
                        Rectangle2D r = g.getBounds2D();
697
                        this.index.remove(new Envelope(r.getX(), r.getX() + r.getWidth(), r
698
                                        .getY(), r.getY() + r.getHeight()), new Integer(
699
                                        calculatedIndex));
700

    
701
                        // Se actualiza la relaci?n de ?ndices
702
                        // Integer integer = new Integer(geometryIndex);
703
                        relations.put(new Integer(calculatedIndex), new Integer(
704
                                        previousExpansionFileIndex));
705

    
706
                        // Se recupera la geometr?a
707
                        // expansionFile.validateRow(previousExpansionFileIndex);
708

    
709
                        // Se actualizan los ?ndices
710
                        // g = ((IFeature)
711
                        // (expansionFile.getRow(previousExpansionFileIndex).getLinkedRow())).getGeometry();
712
                        // System.out.println("Anterior a la que volvemos : " +
713
                        // g.toString());
714
                        g = ((DefaultFeature) getRow(inverse).getLinkedRow()).getGeometry();
715
                        r = g.getBounds2D();
716
                        this.index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r
717
                                        .getY(), r.getY() + r.getHeight()), new Integer(
718
                                        calculatedIndex));
719

    
720
                }
721
                fireAfterModifyRow(calculatedIndex, sourceType);
722
        }
723

    
724
        /**
725
         * A?ade una geometria al fichero de expansi?n y guarda la correspondencia
726
         * en la tabla relations.
727
         *
728
         * @param feat
729
         *            geometr?a a guardar.
730
         *
731
         * @return calculatedIndex
732
         *
733
         * @throws DriverIOException
734
         * @throws IOException
735
         */
736
        public int doAddRow(IRow feat, int sourceType) throws DriverIOException,
737
                        IOException {
738
                int calculatedIndex = super.doAddRow(feat, sourceType);
739
                // Actualiza el ?ndice espacial
740
                IGeometry g = ((IFeature) feat).getGeometry();
741
                Rectangle2D r = g.getBounds2D();
742
                index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r.getY(),
743
                                r.getY() + r.getHeight()), new Integer(calculatedIndex));
744
                isFullExtentDirty = true;
745
                return calculatedIndex;
746
        }
747

    
748
        /**
749
         * Se desmarca como invalidada en el fichero de expansion o como eliminada
750
         * en el fichero original
751
         *
752
         * @param index
753
         *            DOCUMENT ME!
754
         *
755
         * @throws IOException
756
         * @throws DriverIOException
757
         */
758
        public void undoRemoveRow(int index, int sourceType) throws IOException,
759
                        DriverIOException {
760
                super.undoRemoveRow(index, sourceType);
761

    
762
                IGeometry g = null;
763
                g = ((IFeature) getRow(getInversedIndex(index)).getLinkedRow()).getGeometry();
764

    
765
                Rectangle2D r = g.getBounds2D();
766
                this.index.insert(new Envelope(r.getX(), r.getX() + r.getWidth(), r
767
                                .getY(), r.getY() + r.getHeight()), new Integer(index));
768
        }
769

    
770
        /**
771
         * Se elimina del final del fichero de expansi?n poniendo el puntero de
772
         * escritura apuntando al final de la pen?ltima geometr?a. Deber? quitar la
773
         * relaci?n del mapa de relaciones
774
         *
775
         * @param index
776
         *            ?ndice de la geometr?a que se a?adi?
777
         *
778
         * @throws DriverIOException
779
         * @throws IOException
780
         */
781
        public void undoAddRow(int calculatedIndex, int sourceType)
782
                        throws DriverIOException, IOException {
783
                int inverse = getInversedIndex(calculatedIndex);
784
                IGeometry g = ((IFeature) getRow(inverse).getLinkedRow()).getGeometry();
785
                Rectangle2D r = g.getBounds2D();
786
                this.index.remove(new Envelope(r.getX(), r.getX() + r.getWidth(), r
787
                                .getY(), r.getY() + r.getHeight()),
788
                                new Integer(calculatedIndex));
789

    
790
                super.undoAddRow(calculatedIndex, sourceType);
791
                setSelection(new FBitSet());
792
        }
793

    
794
        /**
795
         * Obtiene las geometr?as que se encuentran en el rect?ngulo que se pasa
796
         * como par?metro haciendo uso del ?ndice espacial
797
         *
798
         * @param r
799
         *            Rect?ngulo indicando la porci?n del espacio para el cual se
800
         *            quiere saber los ?ndices de las geometr?as que se encuentran
801
         *            dentro de ?l
802
         *
803
         * @return Array de ?ndices para su uso con getGeometry, removeGeometry, ...
804
         */
805
        /*
806
         * public int[] getRowsIndexes_OL(Rectangle2D r) { Envelope e = new
807
         * Envelope(r.getX(), r.getX() + r.getWidth(), r.getY(), r.getY() +
808
         * r.getHeight()); List l = index.query(e); int[] indexes = new
809
         * int[l.size()];
810
         *
811
         * for (int index = 0; index < l.size(); index++) { Integer i = (Integer)
812
         * l.get(index); indexes[index] = getInversedIndex(i.intValue()); }
813
         *
814
         * return indexes; }
815
         */
816
        /**
817
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getShapeCount()
818
         */
819
        public int getShapeCount() throws DriverIOException {
820
                try {
821
                        return getRowCount();
822
                } catch (IOException e) {
823
                        throw new DriverIOException(e);
824
                }
825
        }
826

    
827
        /**
828
         * @see com.iver.cit.gvsig.fmap.layers.ReadableVectorial#getFullExtent()
829
         */
830
        public Rectangle2D getFullExtent() throws DriverIOException {
831
                if (fullExtent == null) {
832
                        fullExtent = ova.getFullExtent();
833
                }
834

    
835
                if (isFullExtentDirty) {
836
                        fullExtent = reCalculateFullExtent();
837
                        isFullExtentDirty = false;
838
                }
839
                return fullExtent;
840
        }
841

    
842
        /**
843
         * Use it BEFORE writing to a file.
844
         *
845
         * @return real full extent.
846
         * @throws DriverIOException
847
         */
848
        public Rectangle2D reCalculateFullExtent() throws DriverIOException {
849
                if (getShapeCount() > 0) {
850
                        fullExtent = getShape(0).getBounds2D();
851
                        for (int i = 1; i < getShapeCount(); i++) {
852
                                fullExtent.add(getShape(i).getBounds2D());
853
                        }
854
                } else {
855
                        fullExtent = ova.getFullExtent();
856
                }
857
                return fullExtent;
858
        }
859

    
860
        /**
861
         * En la implementaci?n por defecto podemos hacer que cada feature tenga ID =
862
         * numero de registro. En el DBAdapter podr?amos "overrride" este m?todo y
863
         * poner como ID de la Feature el campo ?nico escogido en la base de datos.
864
         *
865
         * @param numReg
866
         * @return
867
         * @throws DriverException
868
         */
869
        public IFeature getFeature(int numReg) throws DriverException {
870
                IGeometry geom;
871
                IFeature feat = null;
872
                try {
873
                        geom = getShape(numReg);
874
                        DataSource rs = getRecordset();
875
                        Value[] regAtt = new Value[rs.getFieldCount()];
876
                        for (int fieldId = 0; fieldId < rs.getFieldCount(); fieldId++) {
877
                                regAtt[fieldId] = rs.getFieldValue(numReg, fieldId);
878
                        }
879
                        feat = new DefaultFeature(geom, regAtt, numReg + "");
880
                } catch (DriverIOException e) {
881
                        DriverIOExceptionType type =
882
                                new DriverIOExceptionType();
883
                        type.setDriverName(this.getDriver().getName());
884
                        throw new DriverException(e, type);
885
                        
886
                } catch (DriverLoadException e) {
887
                        DriverNotLoadedExceptionType type =
888
                                new DriverNotLoadedExceptionType();
889
                        type.setDriverName(getDriver().getName());
890
                        throw new DriverException(e, type);
891
                        
892
                        
893
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
894
                        
895
                        throw new DriverException(e);
896
                }
897
                return feat;
898
        }
899

    
900
        public void stopEdition(IWriter writer, int sourceType)
901
                        throws EditionException {
902
                ISpatialWriter spatialWriter = (ISpatialWriter) writer;
903
//                spatialWriter.setFlatness(FConverter.flatness);
904
                super.stopEdition(writer, sourceType);
905
                try {
906
                        ova.getDriver().reload();
907
                } catch (IOException e) {
908
                        e.printStackTrace();
909
                        throw new EditionException(e);
910
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
911
                        e.printStackTrace();
912
                        throw new EditionException(e);
913
                }
914
        }
915

    
916
        public Rectangle2D getShapeBounds(int index) throws IOException {
917
                // Solo se utiliza cuando el driver es BoundedShapes
918
                // Si no est? en el fichero de expansi?n
919
                Integer integer = new Integer((int) index);
920
                if (!relations.containsKey(integer)) {
921
                        if (ova.getDriver() instanceof BoundedShapes) {
922
                                BoundedShapes bs = (BoundedShapes) ova.getDriver();
923
                                return bs.getShapeBounds(index);
924
                        } else {
925
                                return ova.getDriver().getShape(index).getBounds2D();
926
                        }
927

    
928
                } else {
929
                        int num = ((Integer) relations.get(integer)).intValue();
930
                        DefaultRowEdited feat;
931
                        feat = (DefaultRowEdited) expansionFile.getRow(num);
932
                        if (feat.getStatus() == IRowEdited.STATUS_DELETED)
933
                                return null;
934
                        IGeometry geom = ((IFeature) feat.getLinkedRow()).getGeometry();
935
                        return geom.getBounds2D();// getGeometry();
936
                }
937

    
938
        }
939

    
940
        public int getShapeType(int index) {
941
                try {
942
                        return ova.getShapeType();
943
                } catch (DriverIOException e) {
944
                        // TODO Auto-generated catch block
945
                        e.printStackTrace();
946
                }
947
                return FShape.MULTI;
948
        }
949

    
950
        /**
951
         * Usar solo cuando est?s seguro de que puedes gastar memoria. Nosotros lo
952
         * usamos para las b?squedas por ?ndice espacial con el handle. La idea es
953
         * usarlo una vez, guardar las geometr?as que necesitas en ese extent y
954
         * trabajar con ellas hasta el siguiente cambio de extent.
955
         *
956
         * @param r
957
         * @param strEPSG
958
         * @return
959
         * @throws DriverException
960
         */
961
        public IRowEdited[] getFeatures(Rectangle2D r, String strEPSG)
962
                        throws DriverException {
963
                // En esta clase suponemos random access.
964
                // Luego tendremos otra clase que sea VectorialEditableDBAdapter
965
                // que reescribir? este m?todo.
966
                Envelope e = FConverter.convertRectangle2DtoEnvelope(r);
967
                List l = index.query(e);
968
                IRowEdited[] feats = new IRowEdited[l.size()];
969
                try {
970
                        for (int index = 0; index < l.size(); index++) {
971
                                Integer i = (Integer) l.get(index);
972
                                int inverse = getInversedIndex(i.intValue());
973
                                feats[index] = (IRowEdited) getRow(inverse);
974
                        }
975
                } catch (IOException ex) {
976
                        DriverIOExceptionType type =
977
                                new DriverIOExceptionType();
978
                        type.setDriverName(this.getDriver().getName());
979
                        throw new DriverException(ex, type);
980
                        
981
                } catch (DriverLoadException ex) {
982
                        DriverNotLoadedExceptionType type =
983
                                new DriverNotLoadedExceptionType();
984
                        type.setDriverName(getDriver().getName());
985
                        throw new DriverException(ex, type);
986
                } catch (DriverIOException ex) {
987
                        DriverIOExceptionType type =
988
                                new DriverIOExceptionType();
989
                        type.setDriverName(this.getDriver().getName());
990
                        throw new DriverException(ex, type);
991
                } 
992
                return feats;
993
        }
994

    
995
        public void setSpatialIndex(SpatialIndex spatialIndex) {
996
                index = (Quadtree) spatialIndex;
997
        }
998

    
999
        public void setFullExtent(Rectangle2D fullExtent2) {
1000
                fullExtent = fullExtent2;
1001
        }
1002

    
1003
        /**
1004
         * DOCUMENT ME!
1005
         *
1006
         * @return DOCUMENT ME!
1007
         */
1008
        public Image getSelectionImage() {
1009
                return selectionImage;
1010
        }
1011

    
1012
        public Image getHandlersImage() {
1013
                return handlersImage;
1014
        }
1015

    
1016
        /**
1017
         * DOCUMENT ME!
1018
         *
1019
         * @param i
1020
         *            DOCUMENT ME!
1021
         */
1022
        public void setSelectionImage(Image i) {
1023
                selectionImage = i;
1024
        }
1025

    
1026
        public void setHandlersImage(BufferedImage handlersImage) {
1027
                this.handlersImage = handlersImage;
1028
        }
1029

    
1030
//        public double getFlatness() {
1031
//                return flatness;
1032
//        }
1033
//
1034
//        public void setFlatness(double d) {
1035
//                flatness=d;
1036
//        }
1037

    
1038
}