Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / FLyrAnnotation.java @ 7659

History | View | Annotate | Download (15.6 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.DoubleValue;
20
import com.hardcode.gdbms.engine.values.IntValue;
21
import com.hardcode.gdbms.engine.values.NullValue;
22
import com.hardcode.gdbms.engine.values.NumericValue;
23
import com.hardcode.gdbms.engine.values.StringValue;
24
import com.hardcode.gdbms.engine.values.Value;
25
import com.hardcode.gdbms.engine.values.ValueFactory;
26
import com.iver.cit.gvsig.fmap.DriverException;
27
import com.iver.cit.gvsig.fmap.ViewPort;
28
import com.iver.cit.gvsig.fmap.core.IGeometry;
29
import com.iver.cit.gvsig.fmap.core.ISymbol;
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.crs.CRSFactory;
34
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
35
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
36
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
37
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
38
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
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.cit.gvsig.fmap.spatialindex.QuadtreeJts;
45
import com.iver.utiles.XMLEntity;
46
import com.iver.utiles.swing.threads.Cancellable;
47

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

    
56
        private ArrayList m_labels;
57

    
58
        private int indexEditing = -1;
59

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

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

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

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

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

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

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

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

    
141
                        // logger.debug("source.stop()");
142
                        getSource().stop();
143

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

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

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

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

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

    
183
                return s.queryByRect(rect);
184
        }
185

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

    
203
                return s.queryByPoint(p, tolerance);
204
        }
205

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

    
225
                return s.queryByShape(g, relationship);
226
        }
227

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

    
242
                return xml;
243
        }
244

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

    
252
                IProjection proj = null;
253

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

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

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

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

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

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

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

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

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

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

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

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

    
403

    
404

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

    
438
                                        }
439
                                m_labels.add(lbls[j]);
440

    
441
                                }
442
                        }
443

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

    
454
        }
455

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

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

    
476
                //AZABALA: Como no tengo claro de donde se crean las capas de textos
477
                //el ?ndice espacial creado seguir? siendo el Quadtree en memoria
478
                //de JTS (QuadtreeJts es un adapter a nuestra api de indices)
479
                spatialIndex = new QuadtreeJts();
480
                ReadableVectorial va = getSource();
481
                ICoordTrans ct = getCoordTrans();
482
                BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
483
                try {
484
                        va.start();
485

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

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

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

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

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

    
532
        }
533

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

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

    
542

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

    
560
        }
561

    
562
        public Strategy getStrategy() {
563
                return strategy;
564
        }
565
}