Statistics
| Revision:

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

History | View | Annotate | Download (17.4 KB)

1
package com.iver.cit.gvsig.fmap.layers;
2

    
3
import java.awt.Color;
4
import java.awt.Font;
5
import java.awt.Graphics2D;
6
import java.awt.geom.Point2D;
7
import java.awt.geom.Rectangle2D;
8
import java.awt.image.BufferedImage;
9
import java.util.ArrayList;
10
import java.util.Iterator;
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.gdbms.driver.exceptions.InitializeDriverException;
18
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
19
import com.hardcode.gdbms.engine.data.driver.DriverException;
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.exceptions.expansionfile.ExpansionFileReadException;
27
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
28
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
29
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
30
import com.iver.cit.gvsig.fmap.ViewPort;
31
import com.iver.cit.gvsig.fmap.core.IGeometry;
32
import com.iver.cit.gvsig.fmap.core.SymbologyFactory;
33
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
34
import com.iver.cit.gvsig.fmap.core.symbols.ITextSymbol;
35
import com.iver.cit.gvsig.fmap.core.v02.FLabel;
36
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
37
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
38
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
39
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
40
import com.iver.cit.gvsig.fmap.edition.AnnotationEditableAdapter;
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.rendering.IVectorLegend;
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 (ReadDriverException 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
         *      ISymbol)
100
         */
101
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
102
                        Cancellable cancel, double scale) throws ReadDriverException {
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 (ReadDriverException 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
         * @throws ReadDriverException
134
         * @throws ExpansionFileReadException
135
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
136
         */
137
        public Rectangle2D getFullExtent() throws ReadDriverException, ExpansionFileReadException {
138
                Rectangle2D rAux;
139
                // logger.debug("source.start()");
140
                try {
141
                        getSource().start();
142
                } catch (InitializeDriverException e) {
143
                        throw new ReadDriverException(getName(),e);
144
                }
145
                rAux = getSource().getFullExtent();
146
                        // logger.debug("source.stop()");
147
                getSource().stop();
148
                        // Si existe reproyecci?n, reproyectar el extent
149
                ICoordTrans ct = getCoordTrans();
150
                if (ct != null) {
151
                        Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
152
                        Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
153
                        pt1 = ct.convert(pt1, null);
154
                        pt2 = ct.convert(pt2, null);
155
                        rAux = new Rectangle2D.Double();
156
                        rAux.setFrameFromDiagonal(pt1, pt2);
157
                }
158
                return rAux;
159
        }
160

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

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

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

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

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

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

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

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

    
235
                return xml;
236
        }
237

    
238
        /**
239
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
240
         */
241
        public void setXMLEntity(XMLEntity xml) throws XMLException {
242
                Iterator iter=xml.findChildren("className",MappingAnnotation.class.getName());
243
                if (iter.hasNext())
244
                        mapping = MappingAnnotation.createFromXML((XMLEntity)iter.next());
245
                else{
246
                        //Este else para versiones anteriores a la 1.0.2.(908)
247
                        if (xml.getChildrenCount()==3)
248
                                mapping = MappingAnnotation.createFromXML(xml.getChild(2));
249
                        else
250
                                mapping = MappingAnnotation.createFromXML(xml.getChild(3));
251
                }
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
//                VectorialAdapter adapter=null;
261
//                if (xml.contains("file")){
262
//                        adapter = new VectorialFileAdapter(new File(xml
263
//                                        .getStringProperty("file")));
264
//                }else if (xml.contains("db")){
265
//                        adapter = new VectorialDBAdapter();
266
//                }
267
//                Driver d;
268
//
269
//                try {
270
//                        d = LayerFactory.getDM().getDriver(
271
//                                        xml.getStringProperty("driverName"));
272
//                } catch (DriverLoadException e1) {
273
//                        throw new XMLException(e1);
274
//                }
275
//
276
//                adapter.setDriver((VectorialDriver) d);
277
//                // TODO Meter esto dentro de la comprobaci?n de si hay memoria
278
//                if (false) {
279
//                } else {
280
//                        setSource(adapter);
281
//                        setProjection(proj);
282
//                }
283

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

    
294
                super.setXMLEntity(xml);
295
                try {
296
                        createLabels();
297
                } catch (ReadDriverException e) {
298
                        e.printStackTrace();
299
                }
300
        }
301

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

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

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

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

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

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

    
409

    
410

    
411
                                                if (vuvl.getSymbolByValue(total)==null){
412
                                                        Color color;
413
                                                        if (idFieldColorText != -1) {
414
                                                                NumericValue c = (NumericValue) ds.getFieldValue(
415
                                                                                i, idFieldColorText);
416
                                                                color=new Color(c.intValue());
417
                                                        } else {
418
                                                                color=defaultSym.getFontColor();
419
                                                        }
420
                                                        String typeFont;
421
                                                        if (idFieldTypeFontText != -1) {
422
                                                                StringValue tf = (StringValue) ds
423
                                                                                .getFieldValue(i, idFieldTypeFontText);
424
                                                                typeFont=tf.getValue();
425
                                                        } else {
426
                                                                typeFont=defaultSym.getFont().getFontName();
427
                                                        }
428
                                                        int style;
429
                                                        if (idFieldStyleFontText != -1) {
430
                                                                IntValue sf = (IntValue) ds
431
                                                                                .getFieldValue(i, idFieldStyleFontText);
432
                                                                style = sf.getValue();
433
                                                        } else {
434
                                                                style = defaultSym.getFont().getStyle();
435
                                                        }
436
                                                        //FSymbol symbol=new FSymbol(FConstant.SYMBOL_TYPE_TEXT);
437

    
438
                                                        ITextSymbol symbol;
439

    
440
                                                        symbol = SymbologyFactory.createDefaultTextSymbol();
441

    
442
                                                        // casca perque ara ?s un ITextSymbol
443
//                                                        symbol.setFontSizeInPixels(isInPixels());
444
                                                        symbol.setFont(new Font(typeFont, style, (int)height));
445
                                                        symbol.setDescription(lbls[j].getString());
446
                                                        //symbol.setFontColor(color);
447
                                                        symbol.setTextColor(color);
448
                                                        vuvl.addSymbol(total,symbol);
449
                                                }
450

    
451
                                        }
452
                                m_labels.add(lbls[j]);
453

    
454
                                }
455
                        }
456

    
457
                        ds.stop();
458
                        adapter.stop();
459
                } catch (ExpansionFileReadException e) {
460
                        throw new ReadDriverException(getName(),e);
461
                } catch (InitializeDriverException e) {
462
                        throw new ReadDriverException(getName(),e);
463
                }
464

    
465
        }
466

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

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

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

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

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

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

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

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

    
541
        }
542

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

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

    
551

    
552
        public void setLegend() {
553
                try {
554
                        getSource().getRecordset().start();
555
                        vuvl.setClassifyingFieldNames(
556
                                        new String[] {
557
                                                        getSource().getRecordset().getFieldName(mapping.getColumnText())
558
                                        }
559
                        );
560

    
561
//                        vuvl.setDefaultSymbol(new FSymbol(FConstant.SYMBOL_TYPE_TEXT));
562
                        vuvl.setDefaultSymbol(SymbologyFactory.createDefaultTextSymbol());
563
                        setLegend((IVectorLegend) vuvl);
564
                        getSource().getRecordset().stop();
565
                } catch (LegendLayerException e) {
566
                        e.printStackTrace();
567
                } catch (ReadDriverException e) {
568
                        e.printStackTrace();
569
                }
570

    
571
        }
572

    
573
        public Strategy getStrategy() {
574
                return strategy;
575
        }
576
        public void setEditing(boolean b) throws StartEditionLayerException {
577
                super.setEditing(b);
578
                deleteSpatialIndex();
579
        }
580

    
581
        public static FLayer createLayerFromVect(FLyrVect layer) throws ReadDriverException, LegendLayerException{
582
                FLyrAnnotation la=new FLyrAnnotation();
583
                la.setSource(layer.getSource());
584
                la.setRecordset(layer.getRecordset());
585
                la.setProjection(layer.getProjection());
586
                la.setLegend((IVectorLegend)layer.getLegend());
587
                return la;
588
        }
589
}