Statistics
| Revision:

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

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 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.operations.strategies.AnnotationStrategy;
41
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
42
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
43
import com.iver.cit.gvsig.fmap.operations.strategies.VisitException;
44
import com.iver.cit.gvsig.fmap.rendering.VectorialUniqueValueLegend;
45
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
46
import com.iver.utiles.XMLEntity;
47
import com.iver.utiles.swing.threads.Cancellable;
48

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

    
57
        private ArrayList m_labels;
58

    
59
        private int indexEditing = -1;
60

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
243
                return xml;
244
        }
245

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

    
253
                IProjection proj = null;
254

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

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

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

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

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

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

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

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

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

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

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

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

    
404

    
405

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

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

    
442
                                }
443
                        }
444

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

    
455
        }
456

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

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

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

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

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

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

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

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

    
533
        }
534

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

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

    
543

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

    
561
        }
562

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