Statistics
| Revision:

svn-gvsig-desktop / tags / v10_RC2c / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / FLyrAnnotation.java @ 8745

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

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

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

    
54
        private ArrayList m_labels;
55

    
56
        private int indexEditing = -1;
57

    
58
        private boolean inPixels;
59
        private VectorialUniqueValueLegend vuvl=new VectorialUniqueValueLegend();
60
        private Strategy strategy=null;
61
        /**
62
         * Crea un nuevo FLyrAnnotation.
63
         */
64
        public FLyrAnnotation() {
65
                super();
66
        }
67

    
68
        /**
69
         * DOCUMENT ME!
70
         *
71
         * @param mapping
72
         *            DOCUMENT ME!
73
         */
74
        public void setMapping(MappingAnnotation mapping) {
75
                this.mapping = mapping;
76
                try {
77
                        setLegend();
78
                        createLabels();
79
                } catch (DriverException e) {
80
                        e.printStackTrace();
81
                }
82
        }
83

    
84
        /**
85
         * DOCUMENT ME!
86
         *
87
         * @return DOCUMENT ME!
88
         */
89
        public MappingAnnotation getMapping() {
90
                return mapping;
91
        }
92

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

    
104
                        if (bDrawShapes) {
105
                                if (strategy == null){
106
                                        strategy = (AnnotationStrategy) StrategyManager
107
                                                        .getStrategy(this);
108
                                }
109
                                try {
110
                                        g.setColor(Color.black);
111
                                        strategy.draw(image, g, viewPort, cancel);
112
                                        if (getISpatialIndex()==null) {
113
                                                createSpatialIndex();
114
                                        }
115
                                } catch (DriverException e) {
116
                                        this.setVisible(false);
117
                                        this.setActive(false);
118
                                        throw e;
119
                                }
120
                        }
121

    
122
                        if (getVirtualLayers() != null) {
123
                                getVirtualLayers().draw(image, g, viewPort, cancel, scale);
124
                        }
125
                }
126
        }
127

    
128
        /**
129
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
130
         */
131
        public Rectangle2D getFullExtent() throws DriverException {
132
                try {
133
                        Rectangle2D rAux;
134

    
135
                        // logger.debug("source.start()");
136
                        getSource().start();
137
                        rAux = getSource().getFullExtent();
138

    
139
                        // logger.debug("source.stop()");
140
                        getSource().stop();
141

    
142
                        // Si existe reproyecci?n, reproyectar el extent
143
                        ICoordTrans ct = getCoordTrans();
144

    
145
                        if (ct != null) {
146
                                Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
147
                                Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
148
                                pt1 = ct.convert(pt1, null);
149
                                pt2 = ct.convert(pt2, null);
150
                                rAux = new Rectangle2D.Double();
151
                                rAux.setFrameFromDiagonal(pt1, pt2);
152
                        }
153

    
154
                        return rAux;
155
                } catch (DriverIOException e) {
156
                        throw new DriverException(e);
157
                }
158
        }
159

    
160
        /**
161
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
162
         *      com.iver.cit.gvsig.fmap.ViewPort,
163
         *      com.iver.utiles.swing.threads.Cancellable)
164
         */
165
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
166
                        double scale) throws DriverException {
167
                if (isVisible() && isWithinScale(scale)) {
168
                        Strategy strategy = StrategyManager.getStrategy(this);
169
                        strategy.print(g, viewPort, cancel);
170
                }
171
        }
172

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

    
181
                return s.queryByRect(rect);
182
        }
183

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

    
201
                return s.queryByPoint(p, tolerance);
202
        }
203

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

    
223
                return s.queryByShape(g, relationship);
224
        }
225

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

    
240
                return xml;
241
        }
242

    
243
        /**
244
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
245
         */
246
        public void setXMLEntity(XMLEntity xml) throws XMLException {
247
                mapping = MappingAnnotation.createFromXML(xml.getChild(2));//getIntArrayProperty("mapping");
248
                setInPixels(xml.getBooleanProperty("isInPixels"));
249

    
250
                IProjection proj = null;
251

    
252
                if (xml.contains("proj")) {
253
                        proj = CRSFactory.getCRS(xml.getStringProperty("proj"));
254
                }
255

    
256
                VectorialFileAdapter adapter = new VectorialFileAdapter(new File(xml
257
                                .getStringProperty("file")));
258
                Driver d;
259

    
260
                try {
261
                        d = LayerFactory.getDM().getDriver(
262
                                        xml.getStringProperty("driverName"));
263
                } catch (DriverLoadException e1) {
264
                        throw new XMLException(e1);
265
                }
266

    
267
                adapter.setDriver((VectorialDriver) d);
268
                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
269
                if (false) {
270
                } else {
271
                        setSource(adapter);
272
                        setProjection(proj);
273
                }
274

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

    
285
                super.setXMLEntity(xml);
286
                try {
287
                        createLabels();
288
                } catch (DriverException e) {
289
                        // TODO Auto-generated catch block
290
                        e.printStackTrace();
291
                }
292
        }
293

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

    
323
                        sc = (int) ds.getRowCount();
324
                        m_labels = new ArrayList(sc);
325
                        DriverAttributes attr = adapter.getDriverAttributes();
326
                        boolean bMustClone = false;
327
                        if (attr != null) {
328
                                if (attr.isLoadedInMemory()) {
329
                                        bMustClone = attr.isLoadedInMemory();
330
                                }
331
                        }
332
                        ICoordTrans ct = getCoordTrans();
333
                        FSymbol defaultSym = (FSymbol) getLegend().getDefaultSymbol();
334
                        for (int i = 0; i < sc; i++) {
335
                                IGeometry geom = adapter.getShape(i);
336

    
337
                                if (geom == null) {
338
                                        m_labels.add(null);
339
                                        continue;
340
                                }
341
                                if (ct != null) {
342
                                        if (bMustClone)
343
                                                geom = geom.cloneGeometry();
344
                                        geom.reProject(ct);
345
                                }
346

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

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

    
390
                                                float height;
391
                                                if (idFieldHeightText != -1) {
392
                                                        NumericValue h = (NumericValue) ds
393
                                                                        .getFieldValue(i, idFieldHeightText);
394
                                                        height=h.floatValue();
395
                                                        lbls[j].setHeight(height);
396
                                                } else {
397
                                                        height=defaultSym.getFontSize();
398
                                                        lbls[j].setHeight(height);
399
                                                }
400

    
401

    
402

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

    
436
                                        }
437
                                m_labels.add(lbls[j]);
438

    
439
                                }
440
                        }
441

    
442
                        ds.stop();
443
                        adapter.stop();
444
                } catch (DriverIOException e) {
445
                        e.printStackTrace();
446
                        throw new DriverException(e);
447
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
448
                        e.printStackTrace();
449
                        throw new DriverException(e);
450
                }
451

    
452
        }
453

    
454
        public FLabel getLabel(int numReg) {
455
                if (m_labels == null || numReg == -1)
456
                        return null;
457
                if (getSource() instanceof AnnotationEditableAdapter){
458
                        AnnotationEditableAdapter aea=((AnnotationEditableAdapter)getSource());
459
                        return aea.getLabel(numReg,false);
460
                }
461
                return (FLabel)m_labels.get(numReg);
462
        }
463

    
464
        /*
465
         * (non-Javadoc)
466
         *
467
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#createIndex()
468
         */
469
        public void createSpatialIndex() {
470
                // FJP: ESTO HABR? QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
471
                // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
472
                // para que acepten recorrer sin geometria, solo con rectangulos.
473

    
474
                //AZABALA: Como no tengo claro de donde se crean las capas de textos
475
                //el ?ndice espacial creado seguir? siendo el Quadtree en memoria
476
                //de JTS (QuadtreeJts es un adapter a nuestra api de indices)
477
                spatialIndex = new QuadtreeJts();
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
                                FLabel label=getLabel(i);
487
                                if (label != null) {
488
                                        r = label.getBoundBox();
489
                                } else {
490
                                        r = shapeBounds.getShapeBounds(i);
491
                                }
492
                                // TODO: MIRAR COMO SE TRAGAR?A ESTO LO DE LAS REPROYECCIONES
493
                                if (ct != null) {
494
                                        r = ct.convert(r);
495
                                }
496
                                if (r != null) {
497
//                                        Coordinate c1 = new Coordinate(r.getMinX(), r.getMinY());
498
//                                        Coordinate c2 = new Coordinate(r.getMaxX(), r.getMaxY());
499
//                                        Envelope env = new Envelope(c1, c2);
500
//                                        spatialIndex.insert(env, new Integer(i));
501
                                        spatialIndex.insert(r, i);
502
                                }
503
                        } // for
504
                        va.stop();
505
                } catch (DriverIOException e) {
506
                        e.printStackTrace();
507
                } catch (IOException e) {
508
                        e.printStackTrace();
509
                }
510
        }
511

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

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

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

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

    
530
        }
531

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

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

    
540

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

    
558
        }
559

    
560
        public Strategy getStrategy() {
561
                return strategy;
562
        }
563
}