Statistics
| Revision:

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

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
                        ds.start();
319
                        int sc;
320
                        // El mapping[0] es el text
321
                        int fieldId = mapping.getColumnText();
322
                        // El mapping[1] es el ?ngulo
323
                        int idFieldRotationText = mapping.getColumnRotate();
324
                        // El mapping[2] es el color
325
                        int idFieldColorText = mapping.getColumnColor();
326
                        // El mapping[3] es el alto
327
                        int idFieldHeightText = mapping.getColumnHeight();
328
                        // El mapping[4] es el tipo de fuente
329
                        int idFieldTypeFontText = mapping.getColumnTypeFont();
330
                        // El mapping[5] es el estilo de fuente
331
                        int idFieldStyleFontText = mapping.getColumnStyleFont();
332

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

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

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

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

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

    
411

    
412

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

    
446
                                        }
447
                                m_labels.add(lbls[j]);
448

    
449
                                }
450
                        }
451

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

    
462
        }
463

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

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

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

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

    
522
        public void setSelectedEditing() throws DriverException {
523
                FBitSet bitSet = getRecordset().getSelection();
524
                if (bitSet.cardinality() == 0)
525
                        return;
526
                indexEditing = bitSet.nextSetBit(0);
527
        }
528

    
529
        public void setInPixels(boolean b) {
530
                inPixels = b;
531
        }
532

    
533
        public boolean isInPixels() {
534
                return inPixels;
535
        }
536

    
537
        public void setInEdition(int i) {
538
                indexEditing = i;
539

    
540
        }
541

    
542
        public int getInEdition() {
543
                return indexEditing;
544
        }
545

    
546
        public ArrayList getLabels() {
547
                return m_labels;
548
        }
549

    
550

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

    
568
        }
569

    
570
        public Strategy getStrategy() {
571
                return strategy;
572
        }
573

    
574
        public void setEditing(boolean b) throws EditionException {
575
                super.setEditing(b);
576
                deleteSpatialIndex();
577
        }
578

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