Statistics
| Revision:

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

History | View | Annotate | Download (16.4 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 javax.print.attribute.PrintRequestAttributeSet;
14

    
15
import org.cresques.cts.ICoordTrans;
16
import org.cresques.cts.IProjection;
17

    
18
import com.hardcode.driverManager.Driver;
19
import com.hardcode.driverManager.DriverLoadException;
20
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
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.ISymbol;
31
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
32
import com.iver.cit.gvsig.fmap.core.v02.FLabel;
33
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
34
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
35
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
36
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
37
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
38
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
39
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
40
import com.iver.cit.gvsig.fmap.edition.EditionException;
41
import com.iver.cit.gvsig.fmap.operations.strategies.AnnotationStrategy;
42
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
43
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
44
import com.iver.cit.gvsig.fmap.operations.strategies.VisitException;
45
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
46
import com.iver.cit.gvsig.fmap.rendering.VectorialUniqueValueLegend;
47
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
48
import com.iver.utiles.XMLEntity;
49
import com.iver.utiles.swing.threads.Cancellable;
50

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

    
59
        private ArrayList m_labels;
60

    
61
        private int indexEditing = -1;
62

    
63
        private boolean inPixels;
64
        private VectorialUniqueValueLegend vuvl=new VectorialUniqueValueLegend();
65
        private Strategy strategy=null;
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, ISymbol)
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
                                if (strategy == null){
111
                                        strategy = (AnnotationStrategy) StrategyManager
112
                                                        .getStrategy(this);
113
                                }
114
                                try {
115
                                        g.setColor(Color.black);
116
                                        strategy.draw(image, g, viewPort, cancel);
117
                                        if (getISpatialIndex()==null && !isEditing()) {
118
                                                createSpatialIndex();
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.utiles.swing.threads.Cancellable)
169
         */
170
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
171
                        double scale, PrintRequestAttributeSet properties) throws DriverException {
172
                if (isVisible() && isWithinScale(scale)) {
173
                        Strategy strategy = StrategyManager.getStrategy(this);
174
                        strategy.print(g, viewPort, cancel, properties);
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(3));//getIntArrayProperty("mapping");
253
                setInPixels(xml.getBooleanProperty("isInPixels"));
254

    
255
                IProjection proj = null;
256

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

    
261
//                VectorialAdapter adapter=null;
262
//                if (xml.contains("file")){
263
//                        adapter = new VectorialFileAdapter(new File(xml
264
//                                        .getStringProperty("file")));
265
//                }else if (xml.contains("db")){
266
//                        adapter = new VectorialDBAdapter();
267
//                }
268
//                Driver d;
269
//
270
//                try {
271
//                        d = LayerFactory.getDM().getDriver(
272
//                                        xml.getStringProperty("driverName"));
273
//                } catch (DriverLoadException e1) {
274
//                        throw new XMLException(e1);
275
//                }
276
//
277
//                adapter.setDriver((VectorialDriver) d);
278
//                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
279
//                if (false) {
280
//                } else {
281
//                        setSource(adapter);
282
//                        setProjection(proj);
283
//                }
284

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

    
295
                super.setXMLEntity(xml);
296
                try {
297
                        createLabels();
298
                } catch (DriverException e) {
299
                        // TODO Auto-generated catch block
300
                        e.printStackTrace();
301
                }
302
        }
303

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

    
335
                        sc = (int) ds.getRowCount();
336
                        m_labels = new ArrayList(sc);
337
                        DriverAttributes attr = adapter.getDriverAttributes();
338
                        boolean bMustClone = false;
339
                        if (attr != null) {
340
                                if (attr.isLoadedInMemory()) {
341
                                        bMustClone = attr.isLoadedInMemory();
342
                                }
343
                        }
344
                        ICoordTrans ct = getCoordTrans();
345
                        FSymbol defaultSym = (FSymbol) getLegend().getDefaultSymbol();
346
                        for (int i = 0; i < sc; i++) {
347
                                IGeometry geom = adapter.getShape(i);
348

    
349
                                if (geom == null) {
350
                                        m_labels.add(null);
351
                                        continue;
352
                                }
353
                                if (ct != null) {
354
                                        if (bMustClone)
355
                                                geom = geom.cloneGeometry();
356
                                        geom.reProject(ct);
357
                                }
358

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

    
379
                                if (idFieldStyleFontText!=-1){
380
                                        Value valStyleFont=ds.getFieldValue(i,idFieldStyleFontText);
381
                                        t=t.concat(valStyleFont.toString());
382
                                        //values.add(valStyleFont);
383
                                }
384
                                //Value total=ValueFactory.createValue((Value[])values.toArray(new Value[0]));
385
                                Value total=ValueFactory.createValue(t);
386
                                if ((val instanceof NullValue) || (val == null)) {
387
                                        m_labels.add(null);
388
                                        continue;
389
                                }
390
                                FLabel[] lbls = geom.createLabels(0, true);
391
                                for (int j = 0; j < lbls.length; j++) {
392
                                        if (lbls[j] != null) {
393
                                                lbls[j].setString(val.toString());
394
                                                if (idFieldRotationText != -1) {
395
                                                        NumericValue rotation = (NumericValue) ds
396
                                                                        .getFieldValue(i, idFieldRotationText);
397
                                                        lbls[j].setRotation(rotation.doubleValue());
398
                                                } else {
399
                                                        lbls[j].setRotation(defaultSym.getRotation());
400
                                                }
401

    
402
                                                float height;
403
                                                if (idFieldHeightText != -1) {
404
                                                        NumericValue h = (NumericValue) ds
405
                                                                        .getFieldValue(i, idFieldHeightText);
406
                                                        height=h.floatValue();
407
                                                        lbls[j].setHeight(height);
408
                                                } else {
409
                                                        height=defaultSym.getFontSize();
410
                                                        lbls[j].setHeight(height);
411
                                                }
412

    
413

    
414

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

    
448
                                        }
449
                                m_labels.add(lbls[j]);
450

    
451
                                }
452
                        }
453

    
454
                        if (this.isJoined()){
455
                                ds.stop();
456
                        }
457
                        adapter.stop();
458
                } catch (DriverIOException e) {
459
                        e.printStackTrace();
460
                        throw new DriverException(e);
461
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
462
                        e.printStackTrace();
463
                        throw new DriverException(e);
464
                }
465

    
466
        }
467

    
468
        public FLabel getLabel(int numReg) {
469
                if (m_labels == null || numReg == -1)
470
                        return null;
471
                if (getSource() instanceof AnnotationEditableAdapter){
472
                        AnnotationEditableAdapter aea=((AnnotationEditableAdapter)getSource());
473
                        return aea.getLabel(numReg,false);
474
                }
475
                return (FLabel)m_labels.get(numReg);
476
        }
477

    
478
        /*
479
         * (non-Javadoc)
480
         *
481
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#createIndex()
482
         */
483
        public void createSpatialIndex() {
484
                // FJP: ESTO HABR? QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
485
                // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
486
                // para que acepten recorrer sin geometria, solo con rectangulos.
487

    
488
                //AZABALA: Como no tengo claro de donde se crean las capas de textos
489
                //el ?ndice espacial creado seguir? siendo el Quadtree en memoria
490
                //de JTS (QuadtreeJts es un adapter a nuestra api de indices)
491
                spatialIndex = new QuadtreeJts();
492
                ReadableVectorial va = getSource();
493
                ICoordTrans ct = getCoordTrans();
494
                BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
495
                try {
496
                        va.start();
497

    
498
                        for (int i = 0; i < va.getShapeCount(); i++) {
499
                                Rectangle2D r = null;
500
                                FLabel label=getLabel(i);
501
                                if (label != null) {
502
                                        r = label.getBoundBox();
503
                                } else {
504
                                        r = shapeBounds.getShapeBounds(i);
505
                                }
506
                                // TODO: MIRAR COMO SE TRAGAR?A ESTO LO DE LAS REPROYECCIONES
507
                                if (ct != null) {
508
                                        r = ct.convert(r);
509
                                }
510
                                if (r != null) {
511
//                                        Coordinate c1 = new Coordinate(r.getMinX(), r.getMinY());
512
//                                        Coordinate c2 = new Coordinate(r.getMaxX(), r.getMaxY());
513
//                                        Envelope env = new Envelope(c1, c2);
514
//                                        spatialIndex.insert(env, new Integer(i));
515
                                        spatialIndex.insert(r, i);
516
                                }
517
                        } // for
518
                        va.stop();
519
                } catch (DriverIOException e) {
520
                        e.printStackTrace();
521
                } catch (IOException e) {
522
                        e.printStackTrace();
523
                }
524
        }
525

    
526
        public void setSelectedEditing() throws DriverException {
527
                FBitSet bitSet = getRecordset().getSelection();
528
                if (bitSet.cardinality() == 0)
529
                        return;
530
                indexEditing = bitSet.nextSetBit(0);
531
        }
532

    
533
        public void setInPixels(boolean b) {
534
                inPixels = b;
535
        }
536

    
537
        public boolean isInPixels() {
538
                return inPixels;
539
        }
540

    
541
        public void setInEdition(int i) {
542
                indexEditing = i;
543

    
544
        }
545

    
546
        public int getInEdition() {
547
                return indexEditing;
548
        }
549

    
550
        public ArrayList getLabels() {
551
                return m_labels;
552
        }
553

    
554

    
555
        public void setLegend() {
556
                try {
557
                        getSource().getRecordset().start();
558
                        vuvl.setFieldName(getSource().getRecordset().getFieldName(mapping.getColumnText()));
559
                        vuvl.setDefaultSymbol(new FSymbol(FConstant.SYMBOL_TYPE_TEXT));
560
                        setLegend(vuvl);
561
                        getSource().getRecordset().stop();
562
                } catch (FieldNotFoundException e) {
563
                        e.printStackTrace();
564
                } catch (DriverException e) {
565
                        e.printStackTrace();
566
                } catch (DriverLoadException e) {
567
                        e.printStackTrace();
568
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
569
                        e.printStackTrace();
570
                }
571

    
572
        }
573

    
574
        public Strategy getStrategy() {
575
                return strategy;
576
        }
577

    
578
        public void setEditing(boolean b) throws EditionException {
579
                super.setEditing(b);
580
                deleteSpatialIndex();
581
        }
582

    
583
        public static FLayer createLayerFromVect(FLyrVect layer) throws DriverException, FieldNotFoundException {
584
                FLyrAnnotation la=new FLyrAnnotation();
585
                la.setSource(layer.getSource());
586
                la.setRecordset(layer.getRecordset());
587
                la.setProjection(layer.getProjection());
588
                la.setLegend((VectorialLegend)layer.getLegend());
589
                return la;
590
        }
591
}