Statistics
| Revision:

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

History | View | Annotate | Download (15.7 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.util.ArrayList;
11

    
12
import javax.print.attribute.PrintRequestAttributeSet;
13

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

    
17
import com.hardcode.driverManager.Driver;
18
import com.hardcode.driverManager.DriverLoadException;
19
import com.hardcode.gdbms.driver.exceptions.InitializeDriverException;
20
import com.hardcode.gdbms.driver.exceptions.OpenDriverException;
21
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
22
import com.hardcode.gdbms.engine.data.driver.DriverException;
23
import com.hardcode.gdbms.engine.values.IntValue;
24
import com.hardcode.gdbms.engine.values.NullValue;
25
import com.hardcode.gdbms.engine.values.NumericValue;
26
import com.hardcode.gdbms.engine.values.StringValue;
27
import com.hardcode.gdbms.engine.values.Value;
28
import com.hardcode.gdbms.engine.values.ValueFactory;
29
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
30
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
31
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
32
import com.iver.cit.gvsig.fmap.ViewPort;
33
import com.iver.cit.gvsig.fmap.core.IGeometry;
34
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
35
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
36
import com.iver.cit.gvsig.fmap.core.v02.FLabel;
37
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
38
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
39
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
40
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
41
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
42
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
43
import com.iver.cit.gvsig.fmap.operations.strategies.AnnotationStrategy;
44
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
45
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
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 (ReadDriverException 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 ReadDriverException {
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) {
118
                                                createSpatialIndex();
119
                                        }
120
                                } catch (ReadDriverException 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
         * @throws ReadDriverException
135
         * @throws ExpansionFileReadException
136
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
137
         */
138
        public Rectangle2D getFullExtent() throws ReadDriverException, ExpansionFileReadException {
139
                Rectangle2D rAux;
140
                // logger.debug("source.start()");
141
                try {
142
                        getSource().start();
143
                } catch (InitializeDriverException e) {
144
                        throw new ReadDriverException(getName(),e);
145
                }
146
                rAux = getSource().getFullExtent();
147
                        // logger.debug("source.stop()");
148
                getSource().stop();
149
                        // Si existe reproyecci?n, reproyectar el extent
150
                ICoordTrans ct = getCoordTrans();
151
                if (ct != null) {
152
                        Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
153
                        Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
154
                        pt1 = ct.convert(pt1, null);
155
                        pt2 = ct.convert(pt2, null);
156
                        rAux = new Rectangle2D.Double();
157
                        rAux.setFrameFromDiagonal(pt1, pt2);
158
                }
159
                return rAux;
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, PrintRequestAttributeSet properties) throws ReadDriverException {
169
                if (isVisible() && isWithinScale(scale)) {
170
                        Strategy strategy = StrategyManager.getStrategy(this);
171
                        strategy.print(g, viewPort, cancel, properties);
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 ReadDriverException, VisitorException {
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
         * @throws DriverException
196
         *             DOCUMENT ME!
197
         */
198
        public FBitSet queryByPoint(Point2D p, double tolerance)
199
                        throws ReadDriverException, VisitorException {
200
                Strategy s = StrategyManager.getStrategy(this);
201

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

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

    
219
                return s.queryByShape(g, relationship);
220
        }
221

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

    
236
                return xml;
237
        }
238

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

    
246
                IProjection proj = null;
247

    
248
                if (xml.contains("proj")) {
249
                        proj = CRSFactory.getCRS(xml.getStringProperty("proj"));
250
                }
251

    
252
                VectorialFileAdapter adapter = new VectorialFileAdapter(new File(xml
253
                                .getStringProperty("file")));
254
                Driver d;
255

    
256
                try {
257
                        d = LayerFactory.getDM().getDriver(
258
                                        xml.getStringProperty("driverName"));
259
                } catch (DriverLoadException e1) {
260
                        throw new XMLException(e1);
261
                }
262

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

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

    
281
                super.setXMLEntity(xml);
282
                try {
283
                        createLabels();
284
                } catch (ReadDriverException e) {
285
                        e.printStackTrace();
286
                }
287
        }
288

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

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

    
333
                                if (geom == null) {
334
                                        m_labels.add(null);
335
                                        continue;
336
                                }
337
                                if (ct != null) {
338
                                        if (bMustClone)
339
                                                geom = geom.cloneGeometry();
340
                                        geom.reProject(ct);
341
                                }
342

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

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

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

    
397

    
398

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

    
432
                                        }
433
                                m_labels.add(lbls[j]);
434

    
435
                                }
436
                        }
437

    
438
                        ds.stop();
439
                        adapter.stop();
440
                } catch (ExpansionFileReadException e) {
441
                        throw new ReadDriverException(getName(),e);
442
                } catch (InitializeDriverException e) {
443
                        throw new ReadDriverException(getName(),e);
444
                }
445

    
446
        }
447

    
448
        public FLabel getLabel(int numReg) {
449
                if (m_labels == null || numReg == -1)
450
                        return null;
451
                if (getSource() instanceof AnnotationEditableAdapter){
452
                        AnnotationEditableAdapter aea=((AnnotationEditableAdapter)getSource());
453
                        return aea.getLabel(numReg,false);
454
                }
455
                return (FLabel)m_labels.get(numReg);
456
        }
457

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

    
468
                //AZABALA: Como no tengo claro de donde se crean las capas de textos
469
                //el ?ndice espacial creado seguir? siendo el Quadtree en memoria
470
                //de JTS (QuadtreeJts es un adapter a nuestra api de indices)
471
                spatialIndex = new QuadtreeJts();
472
                ReadableVectorial va = getSource();
473
                ICoordTrans ct = getCoordTrans();
474
                BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
475
                try {
476
                        va.start();
477

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

    
506
        public void setSelectedEditing() throws ReadDriverException {
507
                FBitSet bitSet = getRecordset().getSelection();
508
                if (bitSet.cardinality() == 0)
509
                        return;
510
                indexEditing = bitSet.nextSetBit(0);
511
        }
512

    
513
        public void setInPixels(boolean b) {
514
                inPixels = b;
515
        }
516

    
517
        public boolean isInPixels() {
518
                return inPixels;
519
        }
520

    
521
        public void setInEdition(int i) {
522
                indexEditing = i;
523

    
524
        }
525

    
526
        public int getInEdition() {
527
                return indexEditing;
528
        }
529

    
530
        public ArrayList getLabels() {
531
                return m_labels;
532
        }
533

    
534

    
535
        public void setLegend() {
536
                try {
537
                        getSource().getRecordset().start();
538
                        vuvl.setFieldName(getSource().getRecordset().getFieldName(mapping.getColumnText()));
539
                        vuvl.setDefaultSymbol(new FSymbol(FConstant.SYMBOL_TYPE_TEXT));
540
                        setLegend(vuvl);
541
                        getSource().getRecordset().stop();
542
                } catch (LegendLayerException e) {
543
                        e.printStackTrace();
544
                } catch (ReadDriverException e) {
545
                        e.printStackTrace();
546
                }
547

    
548
        }
549

    
550
        public Strategy getStrategy() {
551
                return strategy;
552
        }
553
}