Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.symbology / org.gvsig.symbology.lib / org.gvsig.symbology.lib.impl / src / main / java / org / gvsig / symbology / fmap / mapcontext / rendering / legend / styling / AttrInTableLabelingStrategy.java @ 42775

History | View | Annotate | Download (30.7 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 3 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.symbology.fmap.mapcontext.rendering.legend.styling;
24

    
25
import java.awt.Color;
26
import java.awt.Font;
27
import java.awt.Graphics2D;
28
import java.awt.geom.NoninvertibleTransformException;
29
import java.awt.geom.Point2D;
30
import java.awt.image.BufferedImage;
31
import java.util.ArrayList;
32
import java.util.List;
33
import java.util.logging.Level;
34

    
35
import org.apache.batik.ext.awt.geom.PathLength;
36
import org.cresques.cts.ICoordTrans;
37
import org.cresques.cts.IProjection;
38
import org.slf4j.LoggerFactory;
39

    
40
import org.gvsig.compat.print.PrintAttributes;
41
import org.gvsig.fmap.dal.exception.DataException;
42
import org.gvsig.fmap.dal.exception.ReadException;
43
import org.gvsig.fmap.dal.feature.Feature;
44
import org.gvsig.fmap.dal.feature.FeatureQuery;
45
import org.gvsig.fmap.dal.feature.FeatureSet;
46
import org.gvsig.fmap.dal.feature.FeatureStore;
47
import org.gvsig.fmap.dal.feature.FeatureType;
48
import org.gvsig.fmap.geom.Geometry;
49
import org.gvsig.fmap.geom.GeometryLocator;
50
import org.gvsig.fmap.geom.exception.CreateGeometryException;
51
import org.gvsig.fmap.geom.operation.GeometryOperationException;
52
import org.gvsig.fmap.geom.operation.GeometryOperationNotSupportedException;
53
import org.gvsig.fmap.geom.primitive.Envelope;
54
import org.gvsig.fmap.geom.primitive.Point;
55
import org.gvsig.fmap.geom.type.GeometryType;
56
import org.gvsig.fmap.mapcontext.MapContext;
57
import org.gvsig.fmap.mapcontext.ViewPort;
58
import org.gvsig.fmap.mapcontext.layers.FLayer;
59
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
60
import org.gvsig.fmap.mapcontext.layers.vectorial.IntersectsEnvelopeEvaluator;
61
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelingMethod;
62
import org.gvsig.fmap.mapcontext.rendering.legend.styling.IPlacementConstraints;
63
import org.gvsig.fmap.mapcontext.rendering.legend.styling.IZoomConstraints;
64
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.impl.CartographicSupportToolkit;
65
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.text.impl.SimpleTextSymbol;
66
import org.gvsig.tools.ToolsLocator;
67
import org.gvsig.tools.dispose.DisposableIterator;
68
import org.gvsig.tools.dynobject.DynStruct;
69
import org.gvsig.tools.exception.BaseException;
70
import org.gvsig.tools.persistence.PersistenceManager;
71
import org.gvsig.tools.persistence.PersistentState;
72
import org.gvsig.tools.persistence.exception.PersistenceException;
73
import org.gvsig.tools.task.Cancellable;
74
import org.gvsig.tools.util.Callable;
75
import org.slf4j.Logger;
76

    
77
/**
78
 * LabelingStrategy used when the user wants to use label sizes, rotations, etc.
79
 * from the values included in fields of the datasource's table
80
 *
81
 * @author jaume dominguez faus - jaume.dominguez@iver.es
82
 *
83
 */
84
public class AttrInTableLabelingStrategy implements IAttrInTableLabelingStrategy {
85

    
86
    private static final String FIELD_LABELING_METHOD = "labelingMethod";
87
    private static final String FIELD_ZOOM_CONSTRAINTS = "zoomConstraints";
88
    private static final String FIELD_COLOR_FONT = "colorFont";
89
    private static final String FIELD_REFERENCE_SYSTEM = "referenceSystem";
90
    private static final String FIELD_FIXED_COLOR = "fixedColor";
91
    private static final String FIELD_USE_FIXED_COLOR = "useFixedColor";
92
    private static final String FIELD_FIXED_SIZE = "fixedSize";
93
    private static final String FIELD_USE_FIXED_SIZE = "useFixedSize";
94
    private static final String FIELD_FONT = "font";
95
    private static final String FIELD_UNIT = "Unit";
96
    private static final String FIELD_ROTATION = "RotationField";
97
    private static final String FIELD_COLOR = "ColorField";
98
    private static final String FIELD_HEIGHT = "HeightField";
99
    private static final String FIELD_TEXT = "TextField";
100
    private static final Logger logger = LoggerFactory.getLogger(AttrInTableLabelingStrategy.class);
101
    public static final double MIN_TEXT_SIZE = 3;
102
    private static final String ATTR_IN_TABLE_LABELING_STRATEGY_PERSISTENCE_DEFINITION_NAME
103
            = "AttrInTableLabelingStrategy";
104
    private ILabelingMethod method = new DefaultLabelingMethod();
105
    private IZoomConstraints zoom;
106
    private FLyrVect layer;
107
//        private double unitFactor = 1D;
108
    private double fixedSize = 10;
109
    private Color fixedColor;
110
    private int unit = -1; //(pixel)
111
    private boolean useFixedSize;
112
    private boolean useFixedColor;
113
    private int referenceSystem;
114
//        private boolean isPrinting;
115
    private String[] usedFields = null;
116
    private Font font;
117
    private Color colorFont;
118
    private String textFieldName;
119
    private String rotationFieldName;
120
    private String heightFieldName;
121
    private String colorFieldName;
122

    
123
    public ILabelingMethod getLabelingMethod() {
124
        return this.method;
125
    }
126

    
127
    public void setLabelingMethod(ILabelingMethod method) {
128
        this.method = method;
129
    }
130

    
131
    public IPlacementConstraints getPlacementConstraints() {
132
        return null; // (automatically handled by the driver)
133
    }
134

    
135
    public void setPlacementConstraints(IPlacementConstraints constraints) {
136
        // nothing
137
    }
138

    
139
    public IZoomConstraints getZoomConstraints() {
140
        return zoom;
141
    }
142

    
143
    public void setZoomConstraints(IZoomConstraints constraints) {
144
        this.zoom = constraints;
145
    }
146

    
147
//    private double getScale(ViewPort vp, PrintAttributes patts)
148
//            throws ReadException {
149
//
150
//        double dpi = 0;
151
//        if (patts != null) {
152
//            int len = PrintAttributes.PRINT_QUALITY_DPI.length;
153
//            int priq = patts.getPrintQuality();
154
//            if (priq < 0 || priq >= len) {
155
//                dpi = vp.getDPI();
156
//            } else {
157
//                dpi = PrintAttributes.PRINT_QUALITY_DPI[priq];
158
//            }
159
//        } else {
160
//            dpi = vp.getDPI();
161
//        }
162
//
163
//        // ============== We have dpi now ====================
164
//        IProjection proj = vp.getProjection();
165
//
166
//        if (vp.getImageSize() == null || vp.getAdjustedEnvelope() == null) {
167
//            throw new ReadException("",
168
//                    new Exception("Viewport does not have image size or envelope"));
169
//        }
170
//
171
//        double[] trans2Meter = MapContext.getDistanceTrans2Meter();
172
//        if (proj == null) {
173
//            double wmeters = ((vp.getImageSize().width / dpi) * 0.0254);
174
//            return (long) ((trans2Meter[vp.getMapUnits()] * vp.getAdjustedEnvelope().getLength(0))
175
//                    / wmeters);
176
//        } else {
177
//            return Math.round(proj.getScale(
178
//                    vp.getAdjustedEnvelope().getMinimum(0)
179
//                    * trans2Meter[vp.getMapUnits()],
180
//                    vp.getAdjustedEnvelope().getMaximum(0)
181
//                    * trans2Meter[vp.getMapUnits()],
182
//                    vp.getImageSize().width,
183
//                    dpi));
184
//        }
185
//
186
//    }
187

    
188
    private void draw(BufferedImage image, Graphics2D g, double scale, ViewPort viewPort,
189
            Cancellable cancel, PrintAttributes props) throws ReadException {
190

    
191
//        double scale = getScale(viewPort, props);
192

    
193
        SimpleTextSymbol sym = new SimpleTextSymbol();
194
        sym.setFont(getFont());
195
        sym.setUnit(unit);
196
        sym.setReferenceSystem(referenceSystem);
197
        if (zoom == null
198
                || (zoom.isUserDefined() && (scale >= zoom.getMaxScale())
199
                && (scale <= zoom.getMinScale()))) {
200
            FeatureSet set = null;
201
            DisposableIterator iterator = null;
202
            try {
203
                FilteredLogger logger = new FilteredLogger(AttrInTableLabelingStrategy.logger, 10);
204
                
205
                // limit the labeling to the visible extent
206
                List<String> fields = new ArrayList<String>();
207
                int heightPos = -1;
208
                int rotationPos = -1;
209
                int textPos = -1;
210
                int colorPos = -1;
211

    
212
                if (!this.usesFixedSize()) {
213
                    if (getHeightField() != null) {
214
                        heightPos = fields.size();
215
                        fields.add(getHeightField());
216
                    }
217
                }
218
                if (getRotationField() != null) {
219
                    rotationPos = fields.size();
220
                    fields.add(getRotationField());
221
                }
222
                if (getTextField() != null) {
223
                    textPos = fields.size();
224
                    fields.add(getTextField());
225
                }
226

    
227
                if (!this.usesFixedColor() && getColorField() != null) {
228
                    colorPos = fields.size();
229
                    fields.add(getColorField());
230
                }
231

    
232
                FeatureStore featureStore = layer.getFeatureStore();
233
                ICoordTrans ct = layer.getCoordTrans();
234

    
235
                String geomName = featureStore.getDefaultFeatureType().getDefaultGeometryAttributeName();
236
                fields.add(geomName);
237

    
238
                FeatureQuery featureQuery = layer.createFeatureQuery();
239

    
240
                if (viewPort.getAdjustedEnvelope().contains(
241
                        layer.getFullEnvelope())) {
242
                    /*
243
                     * viewport contains layer completely
244
                     */
245
                    set = featureStore.getFeatureSet(featureQuery);
246
                } else {
247
                    /*
248
                     * view port does not contain layer completely
249
                     */
250
                    IntersectsEnvelopeEvaluator iee = null;
251

    
252
                    IProjection data_proj = null;
253
                    Envelope env_in_store_crs = null;
254

    
255
                    if (ct == null) {
256
                        env_in_store_crs = viewPort.getAdjustedEnvelope();
257
                        data_proj = viewPort.getProjection();
258
                    } else {
259
                        env_in_store_crs = viewPort.getAdjustedEnvelope().convert(
260
                                ct.getInverted());
261
                        data_proj = ct.getPOrig();
262
                    }
263

    
264
                    iee = new IntersectsEnvelopeEvaluator(
265
                            env_in_store_crs,
266
                            data_proj,
267
                            featureStore.getDefaultFeatureType(),
268
                            geomName);
269
                    featureQuery.setAttributeNames((String[]) fields.toArray(new String[fields.size()]));
270
                    featureQuery.setFilter(iee);
271
                    set = featureStore.getFeatureSet(featureQuery);
272
                }
273

    
274
                /*
275
                 * 'set' now has the features that have to be labeled
276
                 */
277
                iterator = set.fastIterator();
278
                while (iterator.hasNext()) {
279
                    if (cancel.isCanceled()) {
280
                        return;
281
                    }
282
                    try {
283
                        Feature feature = (Feature) iterator.next();
284
                        Geometry geom = feature.getDefaultGeometry();
285
                        if( geom == null ) {
286
                            continue;
287
                        }
288
                        
289
                        double size = 0;
290
                        Color color = null;
291
                        if (useFixedSize) {
292
                            // uses fixed size
293
                            size = fixedSize;// * fontScaleFactor;
294
                        } else if (heightFieldName != null) {
295
                            // text size is defined in the table
296
                            try {
297
                                size = feature.getDouble(fields.get(heightPos));
298
                            } catch (Exception e) {
299
                                logger.warn("Null text height value for text '"+ feature.getString(fields.get(textPos))+"'.");
300
                                continue;
301
                            }
302
                        } else {
303
                            // otherwise will use the size in the symbol
304
                            size = sym.getFont().getSize();
305
                        }
306

    
307
                        double the_dpi = viewPort.getDPI();
308
                        if (props != null) {
309
                            int len = PrintAttributes.PRINT_QUALITY_DPI.length;
310
                            int priq = props.getPrintQuality();
311
                            if (priq < 0 || priq >= len) {
312
                                throw new ReadException(featureStore.getName(),
313
                                        new Exception("Bad print quality value: "+ priq));
314
                            } else {
315
                                the_dpi = PrintAttributes.PRINT_QUALITY_DPI[priq];
316
                            }
317
                        }
318

    
319
                        size = CartographicSupportToolkit.getCartographicLength(this,
320
                                        size,
321
                                        viewPort,
322
                                        the_dpi);
323
                        if (size <= MIN_TEXT_SIZE) {
324
                                                // label is too small to be readable, will be skipped
325
                            // this speeds up the rendering in wider zooms
326
                            continue;
327
                        }
328

    
329
                        /*
330
                         * ym.setFontSize(int) assumes dpi = 72
331
                         */
332
                        double font_size = size * 72 / the_dpi;
333
                        sym.setFontSize(font_size);
334

    
335
                        if (useFixedColor) {
336
                            color = fixedColor;
337
                        } else if (colorFieldName != null) {
338
                            // text size is defined in the table
339
                            try {
340
                                color = new Color(feature.getInt(fields.get(colorPos)));
341
                            } catch (ClassCastException ccEx) {
342
                                if (feature.get(fields.get(colorPos)) != null) {
343
                                    throw new ReadException("Unknown", ccEx);
344
                                }
345
                                logger.warn("Null color value for text '"+feature.getString(textFieldName)+"'.");
346
                                continue;
347
                            }
348
                        } else {
349
                            color = sym.getTextColor();
350
                        }
351

    
352
                        sym.setTextColor(color);
353

    
354
                        if (ct != null) {
355
                            /*
356
                             * Reproject from store CRS to view CRS
357
                             */
358
                            geom = geom.cloneGeometry();
359
                            geom.reProject(ct);
360
                        }
361

    
362
                        double rotation = 0D;
363
                        Point p = null;
364
                        if (rotationFieldName != null) {
365
                            // text rotation is defined in the table
366
                            rotation = -Math.toRadians(((Number) feature.get(fields.get(rotationPos))).doubleValue());
367
                            p = createLabelPoint(geom);
368
                        } else {
369
                            GeometryType gty = geom.getGeometryType();
370
                            if (gty.isTypeOf(Geometry.TYPES.CURVE)
371
                                    || gty.isTypeOf(Geometry.TYPES.MULTICURVE)) {
372

    
373
                                Geometry aux_geom = geom.cloneGeometry();
374
                                aux_geom.transform(viewPort.getAffineTransform());
375

    
376
                                PathLength pathLen = new PathLength(aux_geom);
377
                                float length = pathLen.lengthOfPath();
378
                                float distance = (float) (length * 0.4);
379
                                rotation = pathLen.angleAtLength(distance);
380
                                if (rotation < (-Math.PI / 2)) {
381
                                    rotation = rotation + Math.PI;
382
                                } else {
383
                                    if (rotation > (Math.PI / 2)) {
384
                                        rotation = rotation - Math.PI;
385
                                    }
386
                                }
387
                                double norm = -rotation + Math.PI / 2;
388

    
389
                                Point2D p2 = pathLen.pointAtLength(distance);
390
                                Point2D p2_anchor = new Point2D.Double();
391

    
392
                                try {
393
                                    viewPort.getAffineTransform().inverseTransform(
394
                                            p2, p2_anchor);
395
                                } catch (NoninvertibleTransformException e) {
396
                                    logger.warn("While computing anchor point", e);
397
                                }
398
                                double font_offset = 0.8 * font_size
399
                                        / viewPort.getAffineTransform().getScaleX();
400
                                p2_anchor.setLocation(
401
                                        /*
402
                                         * Move away from line
403
                                         */
404
                                        p2_anchor.getX() + font_offset * Math.cos(norm),
405
                                        p2_anchor.getY() + font_offset * Math.sin(norm));
406

    
407
                                p = GeometryLocator.getGeometryManager().createPoint(
408
                                        p2_anchor.getX(),
409
                                        p2_anchor.getY(), Geometry.SUBTYPES.GEOM2D);
410

    
411
                            } else {
412
                                p = createLabelPoint(geom);
413
                            }
414

    
415
                        }
416

    
417
                        sym.setText(feature.getString(fields.get(textPos)));
418
                        sym.setRotation(rotation);
419

    
420
                        if (p != null) {
421
                            if (props == null) {
422
                                sym.draw(g, viewPort.getAffineTransform(), p, feature, cancel);
423
                            } else {
424
                                sym.print(g, viewPort.getAffineTransform(), p, props);
425
                            }
426
                        }
427
                    } catch(Exception ex) {
428
                        logger.warn("",ex);
429
                    }
430
                }
431

    
432
            } catch (BaseException e) {
433
                throw new ReadException(
434
                        "Could not draw annotation in the layer.", e);
435
            } finally {
436
                if (iterator != null) {
437
                    iterator.dispose();
438
                }
439
                if (set != null) {
440
                    set.dispose();
441
                }
442

    
443
            }
444

    
445
        }
446
    }
447

    
448
    static class FilteredLogger {
449
        private int count = 0;
450
        private final Logger logger;
451
        private final int max;
452
        
453
        public FilteredLogger(Logger logger, int max) {
454
            this.max = max;
455
            this.logger = logger;
456
        }
457
        public void warn(String msg, Throwable th) {
458
            if( ++this.count < this.max ) {
459
                this.logger.warn(msg,th);
460
            } else if( this.count == this.max ) {
461
                this.logger.warn(msg,th);
462
                this.logger.warn("Too many errors, don't dump more in this process.");
463
            }
464
        }
465
        public void warn(String msg) {
466
            if( ++this.count < this.max ) {
467
                this.logger.warn(msg);
468
            } else if( this.count == this.max ) {
469
                this.logger.warn(msg);
470
                this.logger.warn("Too many errors, don't dump more in this process.");
471
            }
472
        }
473
        public void info(String msg) {
474
            if( ++this.count < this.max ) {
475
                this.logger.info(msg);
476
            } else if( this.count == this.max ) {
477
                this.logger.info(msg);
478
                this.logger.info("Too many errors, don't dump more in this process.");
479
            }
480
        }
481
    }
482
    
483
    public void draw(BufferedImage image, Graphics2D g, double scale, ViewPort viewPort,
484
            Cancellable cancel, double dpi) throws ReadException {
485
        draw(image, g, scale, viewPort, cancel, null);
486
    }
487

    
488
    private org.gvsig.fmap.geom.primitive.Point createLabelPoint(org.gvsig.fmap.geom.Geometry geom)
489
            throws CreateGeometryException {
490

    
491
        try {
492
            return geom.centroid();
493
        } catch (GeometryOperationNotSupportedException e) {
494
            return null;
495
        } catch (GeometryOperationException e) {
496
            return null;
497
        }
498
    }
499

    
500
//        public String getClassName() {
501
//                return getClass().getName();
502
//        }
503
    public String getRotationField() {
504
        return this.rotationFieldName;
505
    }
506

    
507
    public String getTextField() {
508
        return this.textFieldName;
509
    }
510

    
511
    public String getHeightField() {
512
        return this.heightFieldName;
513
    }
514

    
515
    public String getColorField() {
516
        return this.colorFieldName;
517
    }
518

    
519
    public void setTextField(String textFieldName) {
520
        this.textFieldName = textFieldName;
521
        this.usedFields = null;
522
    }
523

    
524
    public void setRotationField(String rotationFieldName) {
525
        this.rotationFieldName = rotationFieldName;
526
        this.usedFields = null;
527
    }
528

    
529
    /**
530
     * Sets the field that contains the size of the text. The size is computed
531
     * in meters. To use any other unit, call setUnit(int) with the scale factor
532
     * from meters (for centimeters, call <b>setUnitFactor(0.01))</b>.
533
     *
534
     * @param heightFieldName
535
     */
536
    public void setHeightField(String heightFieldName) {
537
        this.heightFieldName = heightFieldName;
538
        this.usedFields = null;
539
    }
540

    
541
    public void setColorField(String colorFieldName) {
542
        this.colorFieldName = colorFieldName;
543
    }
544

    
545
    public void print(Graphics2D g, double scale, ViewPort viewPort, Cancellable cancel,
546
            PrintAttributes props) throws ReadException {
547
        draw(null, g, scale, viewPort, cancel, props);
548
    }
549

    
550
    public void setUsesFixedSize(boolean b) {
551
        useFixedSize = b;
552
        this.usedFields = null;
553
    }
554

    
555
    public boolean usesFixedSize() {
556
        return useFixedSize;
557
    }
558

    
559
    public double getFixedSize() {
560
        return fixedSize;
561
    }
562

    
563
    public void setFixedSize(double fixedSize) {
564
        this.fixedSize = fixedSize;
565
        this.usedFields = null;
566
    }
567

    
568
    public void setUsesFixedColor(boolean b) {
569
        useFixedColor = b;
570
        this.usedFields = null;
571
    }
572

    
573
    public boolean usesFixedColor() {
574
        return useFixedColor;
575
    }
576

    
577
    public Color getFixedColor() {
578
        return fixedColor;
579
    }
580

    
581
    public void setFixedColor(Color fixedColor) {
582
        this.fixedColor = fixedColor;
583
    }
584

    
585
    public void setUnit(int unitIndex) {
586
        unit = unitIndex;
587

    
588
    }
589

    
590
    public int getUnit() {
591
        return unit;
592
    }
593

    
594
    public String[] getUsedFields() {
595
        if (this.usedFields == null) {
596
            List<String> v = new ArrayList<String>(4);
597
            if (!this.usesFixedSize()) {
598
                if (getHeightField() != null) {
599
                    v.add(getHeightField());
600
                }
601
            }
602
            if (getRotationField() != null) {
603
                v.add(getRotationField());
604
            }
605
            if (getTextField() != null) {
606
                v.add(getTextField());
607
            }
608

    
609
            if (!this.usesFixedColor() && getColorField() != null) {
610
                v.add(getColorField());
611
            }
612
            this.usedFields = (String[]) v.toArray(new String[v.size()]);
613
        }
614
        return this.usedFields;
615
    }
616

    
617
    public int getReferenceSystem() {
618
        return referenceSystem;
619
    }
620

    
621
    public void setReferenceSystem(int referenceSystem) {
622
        this.referenceSystem = referenceSystem;
623
    }
624

    
625
    public double toCartographicSize(ViewPort viewPort, double dpi, Geometry geom) {
626
        // not required here
627
        throw new Error("Undefined in this context");
628
    }
629

    
630
    public void setCartographicSize(double cartographicSize, Geometry geom) {
631
        // not required here
632
        throw new Error("Undefined in this context");
633
    }
634

    
635
    public double getCartographicSize(ViewPort viewPort, double dpi, Geometry geom) {
636
        // not required here
637
        throw new Error("Undefined in this context");
638

    
639
    }
640

    
641
    public void setLayer(FLayer layer) {
642
        this.layer = (FLyrVect) layer;
643
        if (layer == null) {
644
            return;
645
        }
646
        FeatureType type;
647
        try {
648
            type = this.layer.getFeatureStore().getDefaultFeatureType();
649
        } catch (DataException e) {
650
            throw new RuntimeException(this.getClass().getName(), e);
651
        }
652

    
653
        if (textFieldName != null) {
654
            if (type.getIndex(textFieldName) < 0) {
655
                // FIXME exception ??
656
            }
657
        }
658
        if (rotationFieldName != null) {
659
            if (type.getIndex(rotationFieldName) < 0) {
660
                // FIXME exception ??
661
            }
662
        }
663
        if (heightFieldName != null) {
664
            if (type.getIndex(heightFieldName) < 0) {
665
                // FIXME exception ??
666
            }
667
        }
668
        if (colorFieldName != null) {
669
            if (type.getIndex(colorFieldName) < 0) {
670
                // FIXME exception ??
671
            }
672
        }
673
    }
674

    
675
    public boolean shouldDrawLabels(double scale) {
676
        return layer.isWithinScale(scale);
677
    }
678

    
679
    public Color getColorFont() {
680
        return colorFont;
681
    }
682

    
683
    public void setColorFont(Color colorFont) {
684
        this.colorFont = colorFont;
685
    }
686

    
687
    public Font getFont() {
688
        return font;
689
    }
690

    
691
    public void setFont(Font selFont) {
692
        this.font = selFont;
693
    }
694

    
695
    /* (non-Javadoc)
696
     * @see org.gvsig.tools.persistence.Persistent#loadFromState(org.gvsig.tools.persistence.PersistentState)
697
     */
698
    public void loadFromState(PersistentState state)
699
            throws PersistenceException {
700

    
701
        setTextField(state.getString(FIELD_TEXT));
702
        setHeightField(state.getString(FIELD_HEIGHT));
703
        setColorField(state.getString(FIELD_COLOR));
704
        setRotationField(state.getString(FIELD_ROTATION));
705
        setUnit(state.getInt(FIELD_UNIT));
706
        setFont((Font) state.get(FIELD_FONT));
707
        useFixedSize = state.getBoolean(FIELD_USE_FIXED_SIZE);
708
        setFixedSize(state.getDouble(FIELD_FIXED_SIZE));
709
        useFixedColor = state.getBoolean(FIELD_USE_FIXED_COLOR);
710
        setFixedColor((Color) state.get(FIELD_FIXED_COLOR));
711
        setReferenceSystem(state.getInt(FIELD_REFERENCE_SYSTEM));
712
        setColorFont((Color) state.get(FIELD_COLOR_FONT));
713
        setZoomConstraints((IZoomConstraints) state.get(FIELD_ZOOM_CONSTRAINTS));
714
        setLabelingMethod((ILabelingMethod) state.get(FIELD_LABELING_METHOD));
715
    }
716

    
717
    /* (non-Javadoc)
718
     * @see org.gvsig.tools.persistence.Persistent#saveToState(org.gvsig.tools.persistence.PersistentState)
719
     */
720
    public void saveToState(final PersistentState state) throws PersistenceException {
721
        state.set(FIELD_TEXT, getTextField());
722
        state.set(FIELD_HEIGHT, getHeightField());
723
        state.set(FIELD_COLOR, getColorField());
724
        state.set(FIELD_ROTATION, getRotationField());
725
        state.set(FIELD_UNIT, getUnit());
726
        state.set(FIELD_FONT, getFont());
727
        state.set(FIELD_USE_FIXED_SIZE, useFixedSize);
728
        state.set(FIELD_FIXED_SIZE, getFixedSize());
729
        state.set(FIELD_USE_FIXED_COLOR, useFixedColor);
730
        state.set(FIELD_FIXED_COLOR, getFixedColor());
731
        state.set(FIELD_REFERENCE_SYSTEM, getReferenceSystem());
732
        state.set(FIELD_COLOR_FONT, getColorFont());
733
        state.set(FIELD_ZOOM_CONSTRAINTS, getZoomConstraints());
734
        state.set(FIELD_LABELING_METHOD, getLabelingMethod());
735
    }
736

    
737
    public static class RegisterPersistence implements Callable {
738

    
739
        public Object call() throws Exception {
740
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
741
            if (manager.getDefinition(ATTR_IN_TABLE_LABELING_STRATEGY_PERSISTENCE_DEFINITION_NAME) == null) {
742
                DynStruct definition = manager.addDefinition(
743
                        AttrInTableLabelingStrategy.class,
744
                        ATTR_IN_TABLE_LABELING_STRATEGY_PERSISTENCE_DEFINITION_NAME,
745
                        ATTR_IN_TABLE_LABELING_STRATEGY_PERSISTENCE_DEFINITION_NAME + " Persistence definition",
746
                        null,
747
                        null
748
                );
749
                definition.addDynFieldString(FIELD_TEXT).setMandatory(true);
750
                definition.addDynFieldString(FIELD_HEIGHT).setMandatory(false);
751
                definition.addDynFieldString(FIELD_COLOR).setMandatory(false);
752
                definition.addDynFieldString(FIELD_ROTATION).setMandatory(false);
753
                definition.addDynFieldInt(FIELD_UNIT).setMandatory(true);
754
                definition.addDynFieldObject(FIELD_FONT).setMandatory(false).setClassOfValue(Font.class);
755
                definition.addDynFieldBoolean(FIELD_USE_FIXED_SIZE).setMandatory(true);
756
                definition.addDynFieldDouble(FIELD_FIXED_SIZE).setMandatory(false);
757
                definition.addDynFieldBoolean(FIELD_USE_FIXED_COLOR).setMandatory(true);
758
                definition.addDynFieldObject(FIELD_FIXED_COLOR).setMandatory(false).setClassOfValue(Color.class);
759
                definition.addDynFieldInt(FIELD_REFERENCE_SYSTEM).setMandatory(true);
760
                definition.addDynFieldObject(FIELD_COLOR_FONT).setMandatory(false).setClassOfValue(Color.class);
761
                definition.addDynFieldObject(FIELD_ZOOM_CONSTRAINTS).setMandatory(false).setClassOfValue(IZoomConstraints.class);
762
                definition.addDynFieldObject(FIELD_LABELING_METHOD).setMandatory(true).setClassOfValue(ILabelingMethod.class);
763
            }
764
            return Boolean.TRUE;
765
        }
766

    
767
    }
768
}