Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / extensions / org.gvsig.symbology / src / main / java / org / gvsig / symbology / fmap / mapcontext / rendering / legend / styling / LabelClass.java @ 31457

History | View | Annotate | Download (16.9 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41

    
42
/* CVS MESSAGES:
43
 *
44
 * $Id: LabelClass.java 13953 2007-09-21 12:26:04Z jaume $
45
 * $Log$
46
 * Revision 1.14  2007-09-21 12:26:04  jaume
47
 * cancellation support extended down to the IGeometry and ISymbol level
48
 *
49
 * Revision 1.13  2007/09/17 14:16:11  jaume
50
 * multilayer symbols sizing bug fixed
51
 *
52
 * Revision 1.12  2007/08/22 09:48:13  jvidal
53
 * javadoc
54
 *
55
 * Revision 1.11  2007/05/09 11:04:58  jaume
56
 * refactored legend hierarchy
57
 *
58
 * Revision 1.10  2007/05/08 08:47:40  jaume
59
 * *** empty log message ***
60
 *
61
 * Revision 1.9  2007/04/26 11:41:00  jaume
62
 * attempting to let defining size in world units
63
 *
64
 * Revision 1.8  2007/04/18 15:35:11  jaume
65
 * *** empty log message ***
66
 *
67
 * Revision 1.7  2007/04/12 14:28:43  jaume
68
 * basic labeling support for lines
69
 *
70
 * Revision 1.6  2007/04/11 16:01:08  jaume
71
 * maybe a label placer refactor
72
 *
73
 * Revision 1.5  2007/04/10 16:34:01  jaume
74
 * towards a styled labeling
75
 *
76
 * Revision 1.4  2007/04/05 16:07:14  jaume
77
 * Styled labeling stuff
78
 *
79
 * Revision 1.3  2007/04/02 16:34:56  jaume
80
 * Styled labeling (start commiting)
81
 *
82
 * Revision 1.2  2007/03/09 08:33:43  jaume
83
 * *** empty log message ***
84
 *
85
 * Revision 1.1.2.6  2007/02/15 16:23:44  jaume
86
 * *** empty log message ***
87
 *
88
 * Revision 1.1.2.5  2007/02/09 07:47:05  jaume
89
 * Isymbol moved
90
 *
91
 * Revision 1.1.2.4  2007/02/02 16:21:24  jaume
92
 * start commiting labeling stuff
93
 *
94
 * Revision 1.1.2.3  2007/02/01 17:46:49  jaume
95
 * *** empty log message ***
96
 *
97
 * Revision 1.1.2.2  2007/02/01 11:42:47  jaume
98
 * *** empty log message ***
99
 *
100
 * Revision 1.1.2.1  2007/01/30 18:10:45  jaume
101
 * start commiting labeling stuff
102
 *
103
 *
104
 */
105
package org.gvsig.symbology.fmap.mapcontext.rendering.legend.styling;
106

    
107
import java.awt.Dimension;
108
import java.awt.Graphics2D;
109
import java.awt.Rectangle;
110
import java.awt.Shape;
111
import java.awt.geom.AffineTransform;
112
import java.awt.geom.Point2D;
113
import java.awt.geom.Rectangle2D;
114

    
115
import org.gvsig.fmap.geom.Geometry;
116
import org.gvsig.fmap.geom.GeometryLocator;
117
import org.gvsig.fmap.geom.GeometryManager;
118
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
119
import org.gvsig.fmap.geom.exception.CreateGeometryException;
120
import org.gvsig.fmap.geom.primitive.GeneralPathX;
121
import org.gvsig.fmap.mapcontext.ViewPort;
122
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelClass;
123
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelLocationMetrics;
124
import org.gvsig.fmap.mapcontext.rendering.symbols.CartographicSupport;
125
import org.gvsig.fmap.mapcontext.rendering.symbols.ITextSymbol;
126
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolDrawingException;
127
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.ILabelStyle;
128
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.impl.CartographicSupportToolkit;
129
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.text.impl.SimpleTextSymbol;
130
import org.gvsig.tools.persistence.PersistenceException;
131
import org.gvsig.tools.persistence.PersistentState;
132
import org.gvsig.utils.XMLEntity;
133
import org.gvsig.utils.XMLException;
134
import org.slf4j.Logger;
135
import org.slf4j.LoggerFactory;
136

    
137

    
138
/**
139
 *
140
 * LabelClass is the model of the label in the new simbology of gvSIG. In this
141
 * class is contained its definition, the expresion that defines the text which
142
 * is going to be showed, if it will be visible or not, the text symbol that is
143
 * going to paint the label and the style for its background.
144
 *
145
 * @author jaume dominguez faus - jaume.dominguez@iver.es
146
 */
147
public class LabelClass implements ILabelClass {
148
        private static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
149
        private static final Logger logger = LoggerFactory.getLogger(GeometryManager.class);
150
        private String name;
151
        private ITextSymbol textSymbol;
152
        private String labelExpression;
153
        private boolean isVisible = true;
154
        private ILabelStyle labelStyle;
155
        private String[] texts;
156
        private int priority;
157
        private double scale = 1;
158
        private String sqlQuery;
159
        private boolean changing = false;
160

    
161

    
162
        /**
163
         * Returns true if the label will be showed in the map
164
         *
165
         * @return isVisible boolean
166
         */
167
        public boolean isVisible() {
168
                return isVisible;
169
        }
170

    
171
        /**
172
         * Sets the visibility of the label in the map.
173
         *
174
         * @param isVisible boolean
175
         */
176
        public void setVisible(boolean isVisible) {
177
                this.isVisible = isVisible;
178
        }
179

    
180
        /**
181
         * Returns the expression that defines the text which will be showed in
182
         * the label
183
         *
184
         * @return labelExpression String
185
         */
186
        public String getLabelExpression() {
187
                return labelExpression;
188
        }
189

    
190
        /**
191
         * Stablishes the expresion that, when it is evaluated, returns the text
192
         * which will be showed by the label.
193
         *
194
         * @param labelExpression String
195
         */
196
        public void setLabelExpression(String labelExpression) {
197
                this.labelExpression = labelExpression;
198
        }
199

    
200
        /**
201
         * Returns the text symbol that is being used for the text(the font,
202
         * size,style,aligment)
203
         *
204
         * @return label ITextSymbol
205
         */
206
        public ITextSymbol getTextSymbol() {
207
                if (textSymbol == null) {
208
                        textSymbol = new SimpleTextSymbol();
209
                }
210
                return textSymbol;
211
        }
212

    
213
        private Dimension getSize() {
214
                if (labelStyle == null) {
215
                        if (texts!=null && texts.length >0) {
216
                                String t = "";
217
                                for (int i = 0; i < texts.length; i++) {
218
                                        t += texts[i];
219
                                }
220
                                getTextSymbol().setText(t);
221
                        }
222

    
223
                        Rectangle bounds = getTextSymbol().getBounds();
224
                        bounds.setLocation(
225
                                        (int) Math.round(bounds.getX()),
226
                                        (int) Math.round(bounds.getY()+bounds.getHeight()));
227
                        return new Dimension(bounds.width, bounds.height);
228
                } else {
229
                        labelStyle.setTextFields(texts);
230
                        return labelStyle.getSize();
231
                }
232
        }
233
        /**
234
         * Stablishes the text symbol that is going to be used for the text(the
235
         * font,size,style,aligment)
236
         *
237
         * @param textSymbol ITextSymbol
238
         */
239
        public void setTextSymbol(ITextSymbol textSymbol) {
240
                this.textSymbol = textSymbol;
241
                if (textSymbol == null) {
242
                        this.textSymbol = new SimpleTextSymbol();
243
                }
244
                setReferenceSystem(referenceSystem);
245
                setUnit(unit);
246
        }
247

    
248
        /**
249
         * Stablishes the style for the label.
250
         *
251
         * @param labelStyle ILabelStyle
252
         */
253
        public void setLabelStyle(ILabelStyle labelStyle) {
254
                this.labelStyle = labelStyle;
255
        }
256

    
257
        /**
258
         * Returns the style of the label
259
         *
260
         */
261
        public ILabelStyle getLabelStyle() {
262
                return this.labelStyle;
263
        }
264

    
265
        /**
266
         * Returns the name of the label
267
         *
268
         */
269
        public String getName() {
270
                return name;
271
        }
272

    
273
        /**
274
         * Stablishes the name of the label
275
         * @param name
276
         */
277
        public void setName(String name) {
278
                this.name = name;
279
        }
280

    
281
        public String toString() {
282
                // for debugging
283
                //                return name+"{label expression="+labelExpression+", visible="+isVisible+", priority="+priority+"}";
284
                return getName();
285
        }
286

    
287
        /**
288
         * Sets the text for the label
289
         *
290
         * @param texts String[]
291
         */
292
        public void setTexts(String[] texts) {
293
                this.texts = texts;
294

    
295
        }
296

    
297
        /**
298
         * Return the text for the label
299
         *
300
         * @param texts String[]
301
         */
302
        public String[] getTexts() {
303
                return this.texts;
304
        }
305

    
306
        /**
307
         * <p>
308
         * LabelLocationMetrics, contains the anchor point, rotation, and some
309
         * other geometric calculations computed by the PlacementManager.
310
         * </p>
311
         *
312
         * <p>
313
         * The shp argument is passed as an accessory for subclasses of this
314
         * class in case they need futher geometric calculations
315
         * </p>
316
         * @param graphics, graphics to use to paint the label.
317
         * @param llm, concrete settings of the placement of this layer
318
         * @param shp, the Shape over whose the label is painted
319
         */
320
        public void draw(Graphics2D graphics, ILabelLocationMetrics llm, Geometry geom) {
321
                if (scale == 0)
322
                        return;
323

    
324

    
325
                Dimension size = getSize();
326
                int width = (int) Math.round(size.getWidth()*scale);
327
                if (width  < 1)
328
                        return;
329

    
330
                int height = (int) Math.round(size.getHeight()*scale);
331
                if (height < 1)
332
                        return;
333

    
334
                Rectangle r = new Rectangle(0,0, width, height);
335
                org.gvsig.fmap.geom.primitive.Point anchor;
336
                try {
337
                        anchor = geomManager.createPoint(llm.getAnchor().getX(), llm.getAnchor().getY(), SUBTYPES.GEOM2D);
338
                        double xAnchor = anchor.getX();
339
                        double yAnchor = anchor.getY();
340
                        double theta = llm.getRotation();
341

    
342
                        graphics.translate(xAnchor, yAnchor);
343
                        graphics.rotate(theta);
344
                        while (changing){}
345
                                changing=true;
346
                                float fontSizeBefore = textSymbol.getFont().getSize2D();
347
                                try {
348
                                        textSymbol.setFontSize(fontSizeBefore*scale);
349
                                        drawInsideRectangle(graphics, r);
350
                                        textSymbol.setFontSize(fontSizeBefore);
351
                                } catch (SymbolDrawingException e) {
352
                                        e.printStackTrace();
353
                                }finally{
354
                                        changing=false;
355
                                }
356

    
357
                        graphics.rotate(-theta);
358
                        graphics.translate(-xAnchor, -yAnchor);
359
                } catch (CreateGeometryException e1) {
360
                        logger.error("Error creating a point", e1);
361
                        e1.printStackTrace();
362
                }
363
        }
364

    
365
        private void relativeToAbsolute(double[] xy, Rectangle r, Dimension labelSz, double ratioLabel, double ratioViewPort) {
366
                int x;
367
                int y;
368
                if (ratioViewPort > ratioLabel) {
369
                        // size is defined by the viewport height
370
                        y = (int) (r.height*xy[1]);
371
                        x = (int) ((0.5*r.width) - (0.5-xy[0])*(ratioLabel*r.height));
372
                } else {
373
                        // size is defined by the viewport width
374
                        x = (int) (r.width * xy[0]);
375
                        y = (int) ((0.5 * r.height) - (0.5-xy[1])*(r.width/ratioLabel));
376
                }
377
                xy[0] = x;
378
                xy[1] = y;
379
        }
380

    
381
        /**
382
         * Useful to render a Label with size inside little rectangles.
383
         *
384
         * @param graphics Graphics2D
385
         * @param bounds Rectangle
386
         * @throws SymbolDrawingException
387
         */
388
        public void drawInsideRectangle(Graphics2D graphics, Rectangle bounds) throws SymbolDrawingException {
389
                if (labelStyle != null) {
390
                        labelStyle.drawInsideRectangle(graphics, bounds);
391
                        Rectangle2D[] textBounds = labelStyle.getTextBounds();
392
                        Dimension labelSz = getSize();
393
                        final double ratioLabel = labelSz.getWidth()/labelSz.getHeight();
394
                        final double ratioViewPort = bounds.getWidth() / bounds.getHeight();
395
                        final double[] xy = new double[2];
396

    
397

    
398
                        // draw the text fields
399
                        if (textBounds.length > 0 && texts!=null) {
400
                                for (int i = 0; i < textBounds.length && i < texts.length; i++) {
401
                                        getTextSymbol().setText(texts[i]);
402
                                        Rectangle2D textFieldArea = textBounds[i];
403
                                        xy[0] = textFieldArea.getX();
404
                                        xy[1] = textFieldArea.getY();
405
                                        relativeToAbsolute(xy, bounds, labelSz, ratioLabel, ratioViewPort);
406
                                        int x = (int) Math.round(xy[0]);
407
                                        int y = (int) Math.round(xy[1]);
408

    
409
                                        xy[0] = textFieldArea.getMaxX();
410
                                        xy[1] = textFieldArea.getMaxY();
411
                                        relativeToAbsolute(xy, bounds, labelSz, ratioLabel, ratioViewPort);
412
                                        int width = (int) Math.round(xy[0]) -x;
413
                                        int height = (int) Math.round(xy[1] - y) ;
414

    
415
                                        Rectangle textRect = new Rectangle(x, y, width, height);
416
                                        Shape oldClip = graphics.getClip();
417
                                        graphics.setClip(textRect);
418
                                        getTextSymbol().drawInsideRectangle(graphics, null, textRect, null);
419
                                        graphics.setClip(oldClip);
420
                                }
421
                        }
422
                } else {
423

    
424
                        if (texts != null && texts.length>0)
425
                                getTextSymbol().setText(texts[0]);
426
                        getTextSymbol().drawInsideRectangle(graphics, null, bounds, null);
427
                }
428
        }
429

    
430
        public int getPriority() {
431
                return priority;
432
        }
433

    
434
        public void setPriority(int priority) {
435
                this.priority = priority;
436
        }
437

    
438
        public Geometry getShape(ILabelLocationMetrics llm) throws CreateGeometryException {
439
                if (llm==null)
440
                        return null;
441
                Point2D anchor = llm.getAnchor();
442
                org.gvsig.fmap.geom.primitive.Point p = geomManager.createPoint(anchor.getX(), anchor.getY(), SUBTYPES.GEOM2D);
443
                double theta = llm.getRotation();
444

    
445
                // 2. calculate the container shape
446
                Geometry returnedValue;
447
                Rectangle bounds = getBounds();
448

    
449
                AffineTransform at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
450
                at.concatenate(AffineTransform.getRotateInstance(theta));
451
                returnedValue = geomManager.createSurface(new GeneralPathX(bounds
452
                                .getPathIterator(null)), SUBTYPES.GEOM2D);
453

    
454
                returnedValue.transform(at);
455
                return returnedValue;
456
        }
457

    
458
        public String getClassName() {
459
                return getClass().getName();
460
        }
461

    
462
        public XMLEntity getXMLEntity() throws XMLException {
463
                XMLEntity xml = new XMLEntity();
464
//                xml.putProperty("className", getClassName());
465
//                xml.putProperty("isVisible", isVisible);
466
//                xml.putProperty("name", name);
467
//                xml.putProperty("labelExpression", labelExpression);
468
//                xml.putProperty("unit", getUnit());
469
//                xml.putProperty("referenceSystem", getReferenceSystem());
470
//                xml.putProperty("priority", getPriority());
471
//                if (texts != null) {
472
//                        xml.putProperty("texts", texts);
473
//                }
474
//                if (sqlQuery != null) {
475
//                        xml.putProperty("sqlQuery", getSQLQuery());
476
//                }
477
//
478
//                if (labelStyle!=null) {
479
//                        XMLEntity labelStyleXML = labelStyle.getXMLEntity();
480
//                        labelStyleXML.putProperty("id", "labelStyle");
481
//                        xml.addChild(labelStyleXML);
482
//                }
483
//
484
//                XMLEntity textSymXML = getTextSymbol().getXMLEntity();
485
//                textSymXML.putProperty("id", "TextSymbol");
486
//                xml.addChild(textSymXML);
487

    
488
                return xml;
489
        }
490

    
491
        /**
492
         * TODO: replace with the new persistence API
493
         */
494
        public void setXMLEntity(XMLEntity xml) {
495
//                isVisible = xml.getBooleanProperty("isVisible");
496
//                name = xml.getStringProperty("name");
497
//                labelExpression = xml.getStringProperty("labelExpression");
498
//                setUnit(xml.getIntProperty("unit"));
499
//                setReferenceSystem(xml.getIntProperty("referenceSystem"));
500
//                setTextSymbol(
501
//                                (ITextSymbol) SymbologyFactory.
502
//                                createSymbolFromXML(xml.firstChild("id", "TextSymbol"), null));
503
//                if (xml.contains("texts")) {
504
//                        setTexts(xml.getStringArrayProperty("texts"));
505
//                }
506
//                if (xml.contains("sqlQuery")) {
507
//                        setSQLQuery(xml.getStringProperty("sqlQuery"));
508
//                }
509
//
510
//                if (xml.contains("priority")) {
511
//                        setPriority(xml.getIntProperty("priority"));
512
//                }
513
//                // labelStyle
514
//                XMLEntity aux = xml.firstChild("id", "labelStyle");
515
//                if (aux!= null) {
516
//                        setLabelStyle((ILabelStyle) SymbologyFactory.
517
//                                        createStyleFromXML(aux, "labelStyle"));
518
//                }
519
        }
520

    
521
        private int unit = CartographicSupportToolkit.DefaultMeasureUnit;
522
        private int referenceSystem = CartographicSupportToolkit.DefaultReferenceSystem;
523

    
524
        public double getCartographicSize(ViewPort viewPort, double dpi, Geometry geom) {
525
                Dimension sz = getSize();
526
                double width = sz.getWidth();
527
                double height = sz.getHeight();
528
                return CartographicSupportToolkit.
529
                getCartographicLength(this,
530
                                Math.max(width, height),
531
                                viewPort,
532
                                dpi);
533
        }
534

    
535
        public int getReferenceSystem() {
536
                return referenceSystem;
537
        }
538

    
539
        public int getUnit() {
540
                return unit;
541
        }
542

    
543
        public void setCartographicSize(double cartographicSize, Geometry geom) {
544
                Dimension sz = getSize();
545
                double width = sz.getWidth();
546
                double height = sz.getHeight();
547
                if (width >= height) {
548
                        scale = cartographicSize / width;
549
                } else {
550
                        scale = cartographicSize / height;
551
                }
552
        }
553

    
554
        public void setReferenceSystem(int referenceSystem) {
555
                this.referenceSystem = referenceSystem;
556
                if (textSymbol != null && textSymbol instanceof CartographicSupport) {
557
                        ((CartographicSupport) textSymbol).setReferenceSystem(referenceSystem);
558
                }
559
        }
560

    
561
        public void setUnit(int unitIndex) {
562
                this.unit = unitIndex;
563
                if (textSymbol != null && textSymbol instanceof CartographicSupport) {
564
                        ((CartographicSupport) textSymbol).setUnit(unitIndex);
565
                }
566
        }
567

    
568
        public double toCartographicSize(ViewPort viewPort, double dpi, Geometry geom) {
569
                setCartographicSize(getCartographicSize(
570
                                viewPort,
571
                                dpi,
572
                                geom),
573
                                geom);
574
                return 0;
575
        }
576

    
577
        public Rectangle getBounds() {
578
                Dimension cBounds = getSize();
579
                return new Rectangle(
580
                                0,
581
                                0,
582
                                (int) Math.round(cBounds.width*scale),
583
                                (int) Math.round(cBounds.height*scale));
584
        }
585

    
586
        public String getSQLQuery() {
587
                if (sqlQuery == null) sqlQuery = "";
588
                return sqlQuery;
589
        }
590

    
591
        public void setSQLQuery(String sqlQuery) {
592
                this.sqlQuery = sqlQuery;
593
        }
594

    
595
        /* (non-Javadoc)
596
         * @see org.gvsig.tools.persistence.Persistent#loadFromState(org.gvsig.tools.persistence.PersistentState)
597
         */
598
        public void loadFromState(PersistentState state)
599
                        throws PersistenceException {
600
                // TODO Auto-generated method stub
601
                
602
        }
603

    
604
        /* (non-Javadoc)
605
         * @see org.gvsig.tools.persistence.Persistent#saveToState(org.gvsig.tools.persistence.PersistentState)
606
         */
607
        public void saveToState(PersistentState state) throws PersistenceException {
608
                // TODO Auto-generated method stub
609
                
610
        }
611
}