Statistics
| Revision:

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

History | View | Annotate | Download (15.5 KB)

1
package com.iver.cit.gvsig.fmap.layers;
2

    
3
import java.awt.Color;
4
import java.awt.Font;
5
import java.awt.Graphics2D;
6
import java.awt.geom.Point2D;
7
import java.awt.geom.Rectangle2D;
8
import java.awt.image.BufferedImage;
9
import java.io.File;
10
import java.io.IOException;
11
import java.util.ArrayList;
12

    
13
import org.cresques.cts.ICoordTrans;
14
import org.cresques.cts.IProjection;
15
import org.cresques.cts.ProjectionPool;
16

    
17
import com.hardcode.driverManager.Driver;
18
import com.hardcode.driverManager.DriverLoadException;
19
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
20
import com.hardcode.gdbms.engine.values.DoubleValue;
21
import com.hardcode.gdbms.engine.values.IntValue;
22
import com.hardcode.gdbms.engine.values.NullValue;
23
import com.hardcode.gdbms.engine.values.NumericValue;
24
import com.hardcode.gdbms.engine.values.StringValue;
25
import com.hardcode.gdbms.engine.values.Value;
26
import com.hardcode.gdbms.engine.values.ValueFactory;
27
import com.iver.cit.gvsig.fmap.DriverException;
28
import com.iver.cit.gvsig.fmap.ViewPort;
29
import com.iver.cit.gvsig.fmap.core.IGeometry;
30
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
31
import com.iver.cit.gvsig.fmap.core.v02.FLabel;
32
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
33
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
34
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
35
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
36
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
37
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
38
import com.iver.cit.gvsig.fmap.operations.Cancellable;
39
import com.iver.cit.gvsig.fmap.operations.strategies.AnnotationStrategy;
40
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
41
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
42
import com.iver.cit.gvsig.fmap.operations.strategies.VisitException;
43
import com.iver.cit.gvsig.fmap.rendering.VectorialUniqueValueLegend;
44
import com.iver.utiles.XMLEntity;
45
import com.vividsolutions.jts.geom.Coordinate;
46
import com.vividsolutions.jts.geom.Envelope;
47
import com.vividsolutions.jts.index.quadtree.Quadtree;
48

    
49
/**
50
 * DOCUMENT ME!
51
 *
52
 * @author Vicente Caballero Navarro
53
 */
54
public class FLyrAnnotation extends FLyrVect {
55
        private MappingAnnotation mapping = null;
56

    
57
        private ArrayList m_labels;
58

    
59
        private boolean isCreateSpatialIndex = false;
60

    
61
        private int indexEditing = -1;
62

    
63
        private boolean inPixels;
64
        private VectorialUniqueValueLegend vuvl=new VectorialUniqueValueLegend();
65

    
66
        /**
67
         * Crea un nuevo FLyrAnnotation.
68
         */
69
        public FLyrAnnotation() {
70
                super();
71
        }
72

    
73
        /**
74
         * DOCUMENT ME!
75
         *
76
         * @param mapping
77
         *            DOCUMENT ME!
78
         */
79
        public void setMapping(MappingAnnotation mapping) {
80
                this.mapping = mapping;
81
                try {
82
                        setLegend();
83
                        createLabels();
84
                } catch (DriverException e) {
85
                        e.printStackTrace();
86
                }
87
        }
88

    
89
        /**
90
         * DOCUMENT ME!
91
         *
92
         * @return DOCUMENT ME!
93
         */
94
        public MappingAnnotation getMapping() {
95
                return mapping;
96
        }
97

    
98
        /**
99
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
100
         *      java.awt.Graphics2D, com.iver.cit.gvsig.fmap.ViewPort)
101
         */
102
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
103
                        Cancellable cancel, double scale) throws DriverException {
104
                if (isWithinScale(scale)) {
105
                        // Las que solo tienen etiquetado sin pintar el shape,
106
                        // no pasamos por ellas
107
                        boolean bDrawShapes = true;
108

    
109
                        if (bDrawShapes) {
110
                                AnnotationStrategy strategy = (AnnotationStrategy) StrategyManager
111
                                                .getStrategy(this);
112

    
113
                                try {
114
                                        g.setColor(Color.black);
115
                                        strategy.draw(image, g, viewPort, cancel);
116
                                        if (!isCreateSpatialIndex) {
117
                                                createSpatialIndex();
118
                                                isCreateSpatialIndex = true;
119
                                        }
120
                                } catch (DriverException e) {
121
                                        this.setVisible(false);
122
                                        this.setActive(false);
123
                                        throw e;
124
                                }
125
                        }
126

    
127
                        if (getVirtualLayers() != null) {
128
                                getVirtualLayers().draw(image, g, viewPort, cancel, scale);
129
                        }
130
                }
131
        }
132

    
133
        /**
134
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
135
         */
136
        public Rectangle2D getFullExtent() throws DriverException {
137
                try {
138
                        Rectangle2D rAux;
139

    
140
                        // logger.debug("source.start()");
141
                        getSource().start();
142
                        rAux = getSource().getFullExtent();
143

    
144
                        // logger.debug("source.stop()");
145
                        getSource().stop();
146

    
147
                        // Si existe reproyecci?n, reproyectar el extent
148
                        ICoordTrans ct = getCoordTrans();
149

    
150
                        if (ct != null) {
151
                                Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
152
                                Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
153
                                pt1 = ct.convert(pt1, null);
154
                                pt2 = ct.convert(pt2, null);
155
                                rAux = new Rectangle2D.Double();
156
                                rAux.setFrameFromDiagonal(pt1, pt2);
157
                        }
158

    
159
                        return rAux;
160
                } catch (DriverIOException e) {
161
                        throw new DriverException(e);
162
                }
163
        }
164

    
165
        /**
166
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
167
         *      com.iver.cit.gvsig.fmap.ViewPort,
168
         *      com.iver.cit.gvsig.fmap.operations.Cancellable)
169
         */
170
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
171
                        double scale) throws DriverException {
172
                if (isVisible() && isWithinScale(scale)) {
173
                        Strategy strategy = StrategyManager.getStrategy(this);
174
                        strategy.print(g, viewPort, cancel);
175
                }
176
        }
177

    
178
        /*
179
         * (non-Javadoc)
180
         *
181
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#queryByRect(java.awt.geom.Rectangle2D)
182
         */
183
        public FBitSet queryByRect(Rectangle2D rect) throws DriverException {
184
                Strategy s = StrategyManager.getStrategy(this);
185

    
186
                return s.queryByRect(rect);
187
        }
188

    
189
        /**
190
         * DOCUMENT ME!
191
         *
192
         * @param p
193
         *            DOCUMENT ME!
194
         * @param tolerance
195
         *            DOCUMENT ME!
196
         *
197
         * @return DOCUMENT ME!
198
         *
199
         * @throws DriverException
200
         *             DOCUMENT ME!
201
         */
202
        public FBitSet queryByPoint(Point2D p, double tolerance)
203
                        throws DriverException {
204
                Strategy s = StrategyManager.getStrategy(this);
205

    
206
                return s.queryByPoint(p, tolerance);
207
        }
208

    
209
        /**
210
         * DOCUMENT ME!
211
         *
212
         * @param g
213
         *            DOCUMENT ME!
214
         * @param relationship
215
         *            DOCUMENT ME!
216
         *
217
         * @return DOCUMENT ME!
218
         *
219
         * @throws DriverException
220
         *             DOCUMENT ME!
221
         * @throws VisitException
222
         *             DOCUMENT ME!
223
         */
224
        public FBitSet queryByShape(IGeometry g, int relationship)
225
                        throws DriverException, VisitException {
226
                Strategy s = StrategyManager.getStrategy(this);
227

    
228
                return s.queryByShape(g, relationship);
229
        }
230

    
231
        /**
232
         * DOCUMENT ME!
233
         *
234
         * @return DOCUMENT ME!
235
         *
236
         * @throws XMLException
237
         *
238
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
239
         */
240
        public XMLEntity getXMLEntity() throws XMLException {
241
                XMLEntity xml = super.getXMLEntity();
242
                xml.addChild(mapping.getXMLEntity());
243
                xml.putProperty("isInPixels", isInPixels());
244

    
245
                return xml;
246
        }
247

    
248
        /**
249
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
250
         */
251
        public void setXMLEntity(XMLEntity xml) throws XMLException {
252
                mapping = MappingAnnotation.createFromXML(xml.getChild(2));//getIntArrayProperty("mapping");
253
                setInPixels(xml.getBooleanProperty("isInPixels"));
254

    
255
                IProjection proj = null;
256

    
257
                if (xml.contains("proj")) {
258
                        proj = ProjectionPool.get(xml.getStringProperty("proj"));
259
                }
260

    
261
                VectorialFileAdapter adapter = new VectorialFileAdapter(new File(xml
262
                                .getStringProperty("file")));
263
                Driver d;
264

    
265
                try {
266
                        d = LayerFactory.getDM().getDriver(
267
                                        xml.getStringProperty("driverName"));
268
                } catch (DriverLoadException e1) {
269
                        throw new XMLException(e1);
270
                }
271

    
272
                adapter.setDriver((VectorialDriver) d);
273
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
274
                if (false) {
275
                } else {
276
                        setSource(adapter);
277
                        setProjection(proj);
278
                }
279

    
280
                // Le asignamos tambi?n una legenda por defecto acorde con
281
                // el tipo de shape que tenga. Tampoco s? si es aqu? el
282
                // sitio adecuado, pero en fin....
283
                /*
284
                 * if (d instanceof WithDefaultLegend) { WithDefaultLegend aux =
285
                 * (WithDefaultLegend) d; adapter.start(); setLegend((VectorialLegend)
286
                 * aux.getDefaultLegend()); adapter.stop(); } else {
287
                 * setLegend(LegendFactory.createSingleSymbolLegend(getShapeType())); }
288
                 */
289

    
290
                super.setXMLEntity(xml);
291
                try {
292
                        createLabels();
293
                } catch (DriverException e) {
294
                        // TODO Auto-generated catch block
295
                        e.printStackTrace();
296
                }
297
        }
298

    
299
        /**
300
         * Esto tiene el fallo de que obligas a una etiqueta por entidad, para poder
301
         * evitar esto, una posible soluci?n ser?a que un FLabel pudiera ser una
302
         * colecci?n de FLabel (Patr?n Composite)
303
         *
304
         * @param lyrVect
305
         * @throws DriverException
306
         */
307
        public void createLabels() throws DriverException {
308
                SelectableDataSource ds = getRecordset();
309
                FSymbol symbol;
310
                try {
311
                        ReadableVectorial adapter = getSource();
312
                        adapter.start();
313
                        ds.start();
314
                        int sc;
315
                        // El mapping[0] es el text
316
                        int fieldId = mapping.getColumnText();
317
                        // El mapping[1] es el ?ngulo
318
                        int idFieldRotationText = mapping.getColumnRotate();
319
                        // El mapping[2] es el color
320
                        int idFieldColorText = mapping.getColumnColor();
321
                        // El mapping[3] es el alto
322
                        int idFieldHeightText = mapping.getColumnHeight();
323
                        // El mapping[4] es el tipo de fuente
324
                        int idFieldTypeFontText = mapping.getColumnTypeFont();
325
                        // El mapping[5] es el estilo de fuente
326
                        int idFieldStyleFontText = mapping.getColumnStyleFont();
327

    
328
                        sc = (int) ds.getRowCount();
329
                        m_labels = new ArrayList(sc);
330
                        DriverAttributes attr = adapter.getDriverAttributes();
331
                        boolean bMustClone = false;
332
                        if (attr != null) {
333
                                if (attr.isLoadedInMemory()) {
334
                                        bMustClone = attr.isLoadedInMemory();
335
                                }
336
                        }
337
                        ICoordTrans ct = getCoordTrans();
338
                        for (int i = 0; i < sc; i++) {
339
                                IGeometry geom = adapter.getShape(i);
340

    
341
                                if (geom == null) {
342
                                        m_labels.add(null);
343
                                        continue;
344
                                }
345
                                if (ct != null) {
346
                                        if (bMustClone)
347
                                                geom = geom.cloneGeometry();
348
                                        geom.reProject(ct);
349
                                }
350

    
351
                                // TODO: El m?todo contenedor (createLabelLayer) debe recoger
352
                                // los par?metros de posicionamiento y de allowDuplicates
353
                                // if (i >= 328)
354
                                // System.out.println("i= " + i + " " + val.toString());
355
                                //ArrayList values=new ArrayList(4);
356
                                String t=new String();
357
                                Value val = ds.getFieldValue(i, fieldId);
358
                                t=val.toString();
359
                                //values.add(val);
360
                                if (idFieldColorText!=-1){
361
                                        Value valColor=ds.getFieldValue(i,idFieldColorText);
362
                                        t=t.concat(valColor.toString());
363
                                        //values.add(valColor);
364
                                }
365
                                if (idFieldTypeFontText!=-1){
366
                                        Value valTypeFont=ds.getFieldValue(i,idFieldTypeFontText);
367
                                        t=t.concat(valTypeFont.toString());
368
                                        //values.add(valTypeFont);
369
                                }
370

    
371
                                if (idFieldStyleFontText!=-1){
372
                                        Value valStyleFont=ds.getFieldValue(i,idFieldStyleFontText);
373
                                        t=t.concat(valStyleFont.toString());
374
                                        //values.add(valStyleFont);
375
                                }
376
                                //Value total=ValueFactory.createValue((Value[])values.toArray(new Value[0]));
377
                                Value total=ValueFactory.createValue(t);
378
                                if ((val instanceof NullValue) || (val == null)) {
379
                                        continue;
380
                                }
381
                                FLabel[] lbls = geom.createLabels(0, true);
382
                                for (int j = 0; j < lbls.length; j++) {
383
                                        if (lbls[j] != null) {
384
                                                lbls[j].setString(val.toString());
385
                                                if (idFieldRotationText != -1) {
386
                                                        DoubleValue rotation = (DoubleValue) ds
387
                                                                        .getFieldValue(i, idFieldRotationText);
388
                                                        lbls[j].setRotation(rotation.getValue());
389
                                                } else {
390
                                                        lbls[j].setRotation(getLegend().getDefaultSymbol()
391
                                                                        .getRotation());
392
                                                }
393

    
394
                                                float height;
395
                                                if (idFieldHeightText != -1) {
396
                                                        NumericValue h = (NumericValue) ds
397
                                                                        .getFieldValue(i, idFieldHeightText);
398
                                                        height=h.floatValue();
399
                                                        lbls[j].setHeight(height);
400
                                                } else {
401
                                                        height=getLegend().getDefaultSymbol()
402
                                                        .getFontSize();
403
                                                        lbls[j].setHeight(height);
404
                                                }
405

    
406

    
407

    
408
                                                if (vuvl.getSymbolByValue(total)==null){
409
                                                        Color color;
410
                                                        if (idFieldColorText != -1) {
411
                                                                DoubleValue c = (DoubleValue) ds.getFieldValue(
412
                                                                                i, idFieldColorText);
413
                                                                color=new Color((int) c.getValue());
414
                                                        } else {
415
                                                                color=getLegend().getDefaultSymbol()
416
                                                                                .getFontColor();
417
                                                        }
418
                                                        String typeFont;
419
                                                        if (idFieldTypeFontText != -1) {
420
                                                                StringValue tf = (StringValue) ds
421
                                                                                .getFieldValue(i, idFieldTypeFontText);
422
                                                                typeFont=tf.getValue();
423
                                                        } else {
424
                                                                typeFont=getLegend().getDefaultSymbol()
425
                                                                        .getFont().getFontName();
426
                                                        }
427
                                                        int style;
428
                                                        if (idFieldStyleFontText != -1) {
429
                                                                IntValue sf = (IntValue) ds
430
                                                                                .getFieldValue(i, idFieldStyleFontText);
431
                                                                style=sf.getValue();
432
                                                        } else {
433
                                                                style=getLegend().getDefaultSymbol()
434
                                                                        .getFont().getStyle();
435
                                                        }
436
                                                        symbol=new FSymbol(FConstant.SYMBOL_TYPE_TEXT);
437
                                                        symbol.setFontSizeInPixels(isInPixels());
438
                                                        symbol.setFont(new Font(typeFont,style,(int)height));
439
                                                        symbol.setDescription(lbls[j].getString());
440
                                                        symbol.setFontColor(color);
441
                                                        vuvl.addSymbol(total,symbol);
442
                                                }
443

    
444
                                        }
445
                                m_labels.add(lbls[j]);
446

    
447
                                }
448
                        }
449

    
450
                        ds.stop();
451
                        adapter.stop();
452
                } catch (DriverIOException e) {
453
                        e.printStackTrace();
454
                        throw new DriverException(e);
455
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
456
                        e.printStackTrace();
457
                        throw new DriverException(e);
458
                }
459

    
460
        }
461

    
462
        public FLabel getLabel(int numReg) {
463
                if (m_labels == null || numReg == -1)
464
                        return null;
465
                return (FLabel) m_labels.get(numReg);
466
        }
467

    
468
        /*
469
         * (non-Javadoc)
470
         *
471
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#createIndex()
472
         */
473
        public void createSpatialIndex() {
474
                // FJP: ESTO HABR? QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
475
                // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
476
                // para que acepten recorrer sin geometria, solo con rectangulos.
477
                spatialIndex = new Quadtree();
478
                ReadableVectorial va = getSource();
479
                ICoordTrans ct = getCoordTrans();
480
                BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
481
                try {
482
                        va.start();
483

    
484
                        for (int i = 0; i < va.getShapeCount(); i++) {
485
                                Rectangle2D r = null;
486
                                if (getLabel(i) != null) {
487
                                        r = getLabel(i).getBoundBox();
488
                                } else {
489
                                        r = shapeBounds.getShapeBounds(i);
490
                                }
491
                                // TODO: MIRAR COMO SE TRAGAR?A ESTO LO DE LAS REPROYECCIONES
492
                                if (ct != null) {
493
                                        r = ct.convert(r);
494
                                }
495
                                if (r != null) {
496
                                        Coordinate c1 = new Coordinate(r.getMinX(), r.getMinY());
497
                                        Coordinate c2 = new Coordinate(r.getMaxX(), r.getMaxY());
498
                                        Envelope env = new Envelope(c1, c2);
499
                                        spatialIndex.insert(env, new Integer(i));
500
                                }
501
                        } // for
502
                        va.stop();
503
                } catch (DriverIOException e) {
504
                        // TODO Auto-generated catch block
505
                        e.printStackTrace();
506
                } catch (IOException e) {
507
                        // TODO Auto-generated catch block
508
                        e.printStackTrace();
509
                }
510

    
511
        }
512

    
513
        public void setSelectedEditing() throws DriverException {
514
                FBitSet bitSet = getRecordset().getSelection();
515
                if (bitSet.cardinality() == 0)
516
                        return;
517
                indexEditing = bitSet.nextSetBit(0);
518
        }
519

    
520
        public void setInPixels(boolean b) {
521
                inPixels = b;
522
        }
523

    
524
        public boolean isInPixels() {
525
                return inPixels;
526
        }
527

    
528
        public void setInEdition(int i) {
529
                indexEditing = i;
530

    
531
        }
532

    
533
        public int getInEdition() {
534
                return indexEditing;
535
        }
536

    
537
        public ArrayList getLabels() {
538
                return m_labels;
539
        }
540

    
541

    
542
        public void setLegend() {
543
                try {
544
                        getSource().getRecordset().start();
545
                        vuvl.setFieldName(getSource().getRecordset().getFieldName(mapping.getColumnText()));
546
                        vuvl.setDefaultSymbol(new FSymbol(FConstant.SYMBOL_TYPE_TEXT));
547
                        setLegend(vuvl);
548
                        getSource().getRecordset().stop();
549
                } catch (FieldNotFoundException e) {
550
                        // TODO Auto-generated catch block
551
                        e.printStackTrace();
552
                } catch (DriverException e) {
553
                        // TODO Auto-generated catch block
554
                        e.printStackTrace();
555
                } catch (DriverLoadException e) {
556
                        // TODO Auto-generated catch block
557
                        e.printStackTrace();
558
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
559
                        // TODO Auto-generated catch block
560
                        e.printStackTrace();
561
                }
562

    
563
        }
564
}