Statistics
| Revision:

root / branches / v2_0_0_prep / extensions / org.gvsig.symbology / src / main / java / org / gvsig / symbology / fmap / mapcontext / rendering / legend / styling / LabelClass.java @ 32880

History | View | Annotate | Download (17.8 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.ToolsLocator;
131
import org.gvsig.tools.dynobject.DynStruct;
132
import org.gvsig.tools.persistence.PersistenceManager;
133
import org.gvsig.tools.persistence.PersistentState;
134
import org.gvsig.tools.persistence.exception.PersistenceException;
135
import org.slf4j.Logger;
136
import org.slf4j.LoggerFactory;
137

    
138

    
139
/**
140
 *
141
 * LabelClass is the model of the label in the new simbology of gvSIG. In this
142
 * class is contained its definition, the expresion that defines the text which
143
 * is going to be showed, if it will be visible or not, the text symbol that is
144
 * going to paint the label and the style for its background.
145
 *
146
 * @author jaume dominguez faus - jaume.dominguez@iver.es
147
 */
148
public class LabelClass implements ILabelClass {
149
        private static final String FIELD_REFERENCE_SYSTEM = "referenceSystem";
150
        private static final String FIELD_UNIT = "unit";
151
        private static final String FIELD_SQL_QUERY = "sqlQuery";
152
        private static final String FIELD_SCALE = "scale";
153
        private static final String FIELD_PRIORITY = "priority";
154
        private static final String FIELD_TEXTS = "texts";
155
        private static final String FIELD_LABEL_STYLE = "labelStyle";
156
        private static final String FIELD_VISIBLE = "visible";
157
        private static final String FIELD_LABEL_EXPRESSION = "labelExpression";
158
        private static final String FIELD_TEXT_SYMBOL = "textSymbol";
159
        private static final String FIELD_NAME = "name";
160
        private static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
161
        private static final Logger logger = LoggerFactory.getLogger(GeometryManager.class);
162
        private static final String LABEL_CLASS_DYNCLASS_NAME = "LabelClass";
163
        private String name;
164
        private ITextSymbol textSymbol;
165
        private String labelExpression;
166
        private boolean isVisible = true;
167
        private ILabelStyle labelStyle;
168
        private String[] texts;
169
        private int priority;
170
        private double scale = 1;
171
        private String sqlQuery;
172

    
173
        private int unit = CartographicSupportToolkit.DefaultMeasureUnit;
174
        private int referenceSystem =
175
                        CartographicSupportToolkit.DefaultReferenceSystem;
176
        
177
        /**
178
         * Returns true if the label will be showed in the map
179
         *
180
         * @return isVisible boolean
181
         */
182
        public boolean isVisible() {
183
                return isVisible;
184
        }
185

    
186
        /**
187
         * Sets the visibility of the label in the map.
188
         *
189
         * @param isVisible boolean
190
         */
191
        public void setVisible(boolean isVisible) {
192
                this.isVisible = isVisible;
193
        }
194

    
195
        /**
196
         * Returns the expression that defines the text which will be showed in
197
         * the label
198
         *
199
         * @return labelExpression String
200
         */
201
        public String getLabelExpression() {
202
                return labelExpression;
203
        }
204

    
205
        /**
206
         * Stablishes the expresion that, when it is evaluated, returns the text
207
         * which will be showed by the label.
208
         *
209
         * @param labelExpression String
210
         */
211
        public void setLabelExpression(String labelExpression) {
212
                this.labelExpression = labelExpression;
213
        }
214

    
215
        /**
216
         * Returns the text symbol that is being used for the text(the font,
217
         * size,style,aligment)
218
         *
219
         * @return label ITextSymbol
220
         */
221
        public ITextSymbol getTextSymbol() {
222
                if (textSymbol == null) {
223
                        textSymbol = new SimpleTextSymbol();
224
                }
225
                return textSymbol;
226
        }
227

    
228
        private Dimension getSize() {
229
                if (labelStyle == null) {
230
                        if (texts!=null && texts.length >0) {
231
                                String t = "";
232
                                for (int i = 0; i < texts.length; i++) {
233
                                        t += texts[i];
234
                                }
235
                                getTextSymbol().setText(t);
236
                        }
237

    
238
                        Rectangle bounds = getTextSymbol().getBounds();
239
                        bounds.setLocation(
240
                                        (int) Math.round(bounds.getX()),
241
                                        (int) Math.round(bounds.getY()+bounds.getHeight()));
242
                        return new Dimension(bounds.width, bounds.height);
243
                } else {
244
                        labelStyle.setTextFields(texts);
245
                        return labelStyle.getSize();
246
                }
247
        }
248
        /**
249
         * Stablishes the text symbol that is going to be used for the text(the
250
         * font,size,style,aligment)
251
         *
252
         * @param textSymbol ITextSymbol
253
         */
254
        public void setTextSymbol(ITextSymbol textSymbol) {
255
                this.textSymbol = textSymbol;
256
                if (textSymbol == null) {
257
                        this.textSymbol = new SimpleTextSymbol();
258
                }
259
                setReferenceSystem(referenceSystem);
260
                setUnit(unit);
261
        }
262

    
263
        /**
264
         * Stablishes the style for the label.
265
         *
266
         * @param labelStyle ILabelStyle
267
         */
268
        public void setLabelStyle(ILabelStyle labelStyle) {
269
                this.labelStyle = labelStyle;
270
        }
271

    
272
        /**
273
         * Returns the style of the label
274
         *
275
         */
276
        public ILabelStyle getLabelStyle() {
277
                return this.labelStyle;
278
        }
279

    
280
        /**
281
         * Returns the name of the label
282
         *
283
         */
284
        public String getName() {
285
                return name;
286
        }
287

    
288
        /**
289
         * Stablishes the name of the label
290
         * @param name
291
         */
292
        public void setName(String name) {
293
                this.name = name;
294
        }
295

    
296
        public String toString() {
297
                // for debugging
298
                //                return name+"{label expression="+labelExpression+", visible="+isVisible+", priority="+priority+"}";
299
                return getName();
300
        }
301

    
302
        /**
303
         * Sets the text for the label
304
         *
305
         * @param texts String[]
306
         */
307
        public void setTexts(String[] texts) {
308
                this.texts = texts;
309

    
310
        }
311

    
312
        /**
313
         * Return the text for the label
314
         *
315
         * @param texts String[]
316
         */
317
        public String[] getTexts() {
318
                return this.texts;
319
        }
320

    
321
        /**
322
         * <p>
323
         * LabelLocationMetrics, contains the anchor point, rotation, and some
324
         * other geometric calculations computed by the PlacementManager.
325
         * </p>
326
         *
327
         * <p>
328
         * The shp argument is passed as an accessory for subclasses of this
329
         * class in case they need futher geometric calculations
330
         * </p>
331
         * @param graphics, graphics to use to paint the label.
332
         * @param llm, concrete settings of the placement of this layer
333
         * @param shp, the Shape over whose the label is painted
334
         */
335
        public void draw(Graphics2D graphics, ILabelLocationMetrics llm, Geometry geom) {
336
                if (scale == 0)
337
                        return;
338

    
339

    
340
                Dimension size = getSize();
341
                int width = (int) Math.round(size.getWidth()*scale);
342
                if (width  < 1)
343
                        return;
344

    
345
                int height = (int) Math.round(size.getHeight()*scale);
346
                if (height < 1)
347
                        return;
348

    
349
                Rectangle r = new Rectangle(0,0, width, height);
350
                org.gvsig.fmap.geom.primitive.Point anchor;
351
                try {
352
                        anchor = geomManager.createPoint(llm.getAnchor().getX(), llm.getAnchor().getY(), SUBTYPES.GEOM2D);
353
                        double xAnchor = anchor.getX();
354
                        double yAnchor = anchor.getY();
355
                        double theta = llm.getRotation();
356

    
357
                        graphics.translate(xAnchor, yAnchor);
358
                        graphics.rotate(theta);
359
                        synchronized (this) {
360
                                float fontSizeBefore = textSymbol.getFont().getSize2D();
361
                                try {
362
                                        textSymbol.setFontSize(fontSizeBefore*scale);
363
                                        drawInsideRectangle(graphics, r);
364
                                        textSymbol.setFontSize(fontSizeBefore);
365
                                } catch (SymbolDrawingException e) {
366
                                        e.printStackTrace();
367
                                }
368
                        }
369
                        graphics.rotate(-theta);
370
                        graphics.translate(-xAnchor, -yAnchor);
371
                } catch (CreateGeometryException e1) {
372
                        logger.error("Error creating a point", e1);
373
                        e1.printStackTrace();
374
                }
375
        }
376

    
377
        private void relativeToAbsolute(double[] xy, Rectangle r, Dimension labelSz, double ratioLabel, double ratioViewPort) {
378
                int x;
379
                int y;
380
                if (ratioViewPort > ratioLabel) {
381
                        // size is defined by the viewport height
382
                        y = (int) (r.height*xy[1]);
383
                        x = (int) ((0.5*r.width) - (0.5-xy[0])*(ratioLabel*r.height));
384
                } else {
385
                        // size is defined by the viewport width
386
                        x = (int) (r.width * xy[0]);
387
                        y = (int) ((0.5 * r.height) - (0.5-xy[1])*(r.width/ratioLabel));
388
                }
389
                xy[0] = x;
390
                xy[1] = y;
391
        }
392

    
393
        /**
394
         * Useful to render a Label with size inside little rectangles.
395
         *
396
         * @param graphics Graphics2D
397
         * @param bounds Rectangle
398
         * @throws SymbolDrawingException
399
         */
400
        public void drawInsideRectangle(Graphics2D graphics, Rectangle bounds) throws SymbolDrawingException {
401
                if (labelStyle != null) {
402
                        labelStyle.drawInsideRectangle(graphics, bounds);
403
                        Rectangle2D[] textBounds = labelStyle.getTextBounds();
404
                        Dimension labelSz = getSize();
405
                        final double ratioLabel = labelSz.getWidth()/labelSz.getHeight();
406
                        final double ratioViewPort = bounds.getWidth() / bounds.getHeight();
407
                        final double[] xy = new double[2];
408

    
409

    
410
                        // draw the text fields
411
                        if (textBounds.length > 0 && texts!=null) {
412
                                for (int i = 0; i < textBounds.length && i < texts.length; i++) {
413
                                        getTextSymbol().setText(texts[i]);
414
                                        Rectangle2D textFieldArea = textBounds[i];
415
                                        xy[0] = textFieldArea.getX();
416
                                        xy[1] = textFieldArea.getY();
417
                                        relativeToAbsolute(xy, bounds, labelSz, ratioLabel, ratioViewPort);
418
                                        int x = (int) Math.round(xy[0]);
419
                                        int y = (int) Math.round(xy[1]);
420

    
421
                                        xy[0] = textFieldArea.getMaxX();
422
                                        xy[1] = textFieldArea.getMaxY();
423
                                        relativeToAbsolute(xy, bounds, labelSz, ratioLabel, ratioViewPort);
424
                                        int width = (int) Math.round(xy[0]) -x;
425
                                        int height = (int) Math.round(xy[1] - y) ;
426

    
427
                                        Rectangle textRect = new Rectangle(x, y, width, height);
428
                                        Shape oldClip = graphics.getClip();
429
                                        graphics.setClip(textRect);
430
                                        getTextSymbol().drawInsideRectangle(graphics, null, textRect, null);
431
                                        graphics.setClip(oldClip);
432
                                }
433
                        }
434
                } else {
435

    
436
                        if (texts != null && texts.length>0)
437
                                getTextSymbol().setText(texts[0]);
438
                        getTextSymbol().drawInsideRectangle(graphics, null, bounds, null);
439
                }
440
        }
441

    
442
        public int getPriority() {
443
                return priority;
444
        }
445

    
446
        public void setPriority(int priority) {
447
                this.priority = priority;
448
        }
449

    
450
        public Geometry getShape(ILabelLocationMetrics llm) throws CreateGeometryException {
451
                if (llm==null)
452
                        return null;
453
                Point2D anchor = llm.getAnchor();
454
                org.gvsig.fmap.geom.primitive.Point p = geomManager.createPoint(anchor.getX(), anchor.getY(), SUBTYPES.GEOM2D);
455
                double theta = llm.getRotation();
456

    
457
                // 2. calculate the container shape
458
                Geometry returnedValue;
459
                Rectangle bounds = getBounds();
460

    
461
                AffineTransform at = AffineTransform.getTranslateInstance(p.getX(), p.getY());
462
                at.concatenate(AffineTransform.getRotateInstance(theta));
463
                returnedValue = geomManager.createSurface(new GeneralPathX(bounds
464
                                .getPathIterator(null)), SUBTYPES.GEOM2D);
465

    
466
                returnedValue.transform(at);
467
                return returnedValue;
468
        }
469

    
470
        public String getClassName() {
471
                return getClass().getName();
472
        }
473

    
474
        public double getCartographicSize(ViewPort viewPort, double dpi, Geometry geom) {
475
                Dimension sz = getSize();
476
                double width = sz.getWidth();
477
                double height = sz.getHeight();
478
                return CartographicSupportToolkit.
479
                getCartographicLength(this,
480
                                Math.max(width, height),
481
                                viewPort,
482
                                dpi);
483
        }
484

    
485
        public int getReferenceSystem() {
486
                return referenceSystem;
487
        }
488

    
489
        public int getUnit() {
490
                return unit;
491
        }
492

    
493
        public void setCartographicSize(double cartographicSize, Geometry geom) {
494
                Dimension sz = getSize();
495
                double width = sz.getWidth();
496
                double height = sz.getHeight();
497
                if (width >= height) {
498
                        scale = cartographicSize / width;
499
                } else {
500
                        scale = cartographicSize / height;
501
                }
502
        }
503

    
504
        public void setReferenceSystem(int referenceSystem) {
505
                this.referenceSystem = referenceSystem;
506
                if (textSymbol != null && textSymbol instanceof CartographicSupport) {
507
                        ((CartographicSupport) textSymbol).setReferenceSystem(referenceSystem);
508
                }
509
        }
510

    
511
        public void setUnit(int unitIndex) {
512
                this.unit = unitIndex;
513
                if (textSymbol != null && textSymbol instanceof CartographicSupport) {
514
                        ((CartographicSupport) textSymbol).setUnit(unitIndex);
515
                }
516
        }
517

    
518
        public double toCartographicSize(ViewPort viewPort, double dpi, Geometry geom) {
519
                setCartographicSize(getCartographicSize(
520
                                viewPort,
521
                                dpi,
522
                                geom),
523
                                geom);
524
                return 0;
525
        }
526

    
527
        public Rectangle getBounds() {
528
                Dimension cBounds = getSize();
529
                return new Rectangle(
530
                                0,
531
                                0,
532
                                (int) Math.round(cBounds.width*scale),
533
                                (int) Math.round(cBounds.height*scale));
534
        }
535

    
536
        public String getSQLQuery() {
537
                if (sqlQuery == null) sqlQuery = "";
538
                return sqlQuery;
539
        }
540

    
541
        public void setSQLQuery(String sqlQuery) {
542
                this.sqlQuery = sqlQuery;
543
        }
544

    
545
        /*
546
         * (non-Javadoc)
547
         * 
548
         * @seeorg.gvsig.tools.persistence.Persistent#saveToState(org.gvsig.tools.
549
         * persistence.PersistentState)
550
         */
551
        public void saveToState(PersistentState state) throws PersistenceException {
552
                state.set(FIELD_NAME, getName());
553
                state.set(FIELD_TEXT_SYMBOL, getTextSymbol());
554
                state.set(FIELD_LABEL_EXPRESSION, getLabelExpression());
555
                state.set(FIELD_VISIBLE, isVisible());
556
                state.set(FIELD_LABEL_STYLE, getLabelStyle());
557
                state.set(FIELD_TEXTS, getTexts());
558
                state.set(FIELD_PRIORITY, getPriority());
559
                state.set(FIELD_SCALE, scale);
560
                state.set(FIELD_SQL_QUERY, getSQLQuery());
561
                state.set(FIELD_UNIT, getUnit());
562
                state.set(FIELD_REFERENCE_SYSTEM, getReferenceSystem());
563
        }
564

    
565
        /*
566
         * (non-Javadoc)
567
         * 
568
         * @see
569
         * org.gvsig.tools.persistence.Persistent#loadFromState(org.gvsig.tools.
570
         * persistence.PersistentState)
571
         */
572
        public void loadFromState(PersistentState state)
573
                        throws PersistenceException {
574
                setName(state.getString(FIELD_NAME));
575
                setTextSymbol((ITextSymbol) state.get(FIELD_TEXT_SYMBOL));
576
                setLabelExpression(state.getString(FIELD_LABEL_EXPRESSION));
577
                setVisible(state.getBoolean(FIELD_VISIBLE));
578
                setLabelStyle((ILabelStyle) state.get(FIELD_LABEL_STYLE));
579
                setTexts((String[]) state.getArray(FIELD_TEXTS, String.class));
580
                setPriority(state.getInt(FIELD_PRIORITY));
581
                scale = state.getDouble(FIELD_SCALE);
582
                setSQLQuery(state.getString(FIELD_SQL_QUERY));
583
                setUnit(state.getInt(FIELD_UNIT));
584
                setReferenceSystem(state.getInt(FIELD_REFERENCE_SYSTEM));
585
        }
586

    
587
        public static void registerPersistence() {
588
                // Add the persistence definition.
589
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
590
                DynStruct definition = manager.addDefinition(
591
                                LabelClass.class,
592
                                LABEL_CLASS_DYNCLASS_NAME,
593
                                LABEL_CLASS_DYNCLASS_NAME+" Persistence definition",
594
                                null, 
595
                                null
596
                );
597

    
598
                definition.addDynFieldString(FIELD_NAME).setMandatory(true);
599
                definition.addDynFieldObject(FIELD_TEXT_SYMBOL).setMandatory(true);
600
                definition.addDynFieldString(FIELD_LABEL_EXPRESSION).setMandatory(true);
601
                definition.addDynFieldBoolean(FIELD_VISIBLE).setMandatory(true);
602
                definition.addDynFieldObject(FIELD_LABEL_STYLE).setMandatory(true);
603
                definition.addDynFieldList(FIELD_TEXTS).setMandatory(true);
604
                definition.addDynFieldInt(FIELD_PRIORITY).setMandatory(true);
605
                definition.addDynFieldDouble(FIELD_SCALE).setMandatory(true);
606
                definition.addDynFieldString(FIELD_SQL_QUERY).setMandatory(true);
607
                definition.addDynFieldInt(FIELD_UNIT).setMandatory(true);
608
                definition.addDynFieldInt(FIELD_REFERENCE_SYSTEM).setMandatory(true);
609
        }
610

    
611
}