Statistics
| Revision:

root / branches / v10 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / layers / FLyrAnnotation.java @ 10925

History | View | Annotate | Download (15.8 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.VectorialUniqueValueLegend;
46
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
47
import com.iver.utiles.XMLEntity;
48
import com.iver.utiles.swing.threads.Cancellable;
49

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

    
58
        private ArrayList m_labels;
59

    
60
        private int indexEditing = -1;
61

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

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

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

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

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

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

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

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

    
143
                        // logger.debug("source.stop()");
144
                        getSource().stop();
145

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

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

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

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

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

    
185
                return s.queryByRect(rect);
186
        }
187

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

    
205
                return s.queryByPoint(p, tolerance);
206
        }
207

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

    
227
                return s.queryByShape(g, relationship);
228
        }
229

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

    
244
                return xml;
245
        }
246

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

    
254
                IProjection proj = null;
255

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

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

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

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

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

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

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

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

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

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

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

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

    
405

    
406

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

    
440
                                        }
441
                                m_labels.add(lbls[j]);
442

    
443
                                }
444
                        }
445

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

    
456
        }
457

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

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

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

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

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

    
523
        public void setInPixels(boolean b) {
524
                inPixels = b;
525
        }
526

    
527
        public boolean isInPixels() {
528
                return inPixels;
529
        }
530

    
531
        public void setInEdition(int i) {
532
                indexEditing = i;
533

    
534
        }
535

    
536
        public int getInEdition() {
537
                return indexEditing;
538
        }
539

    
540
        public ArrayList getLabels() {
541
                return m_labels;
542
        }
543

    
544

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

    
562
        }
563

    
564
        public Strategy getStrategy() {
565
                return strategy;
566
        }
567

    
568
        public void setEditing(boolean b) throws EditionException {
569
                super.setEditing(b);
570
                deleteSpatialIndex();
571
        }
572
}