Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / libraries / libFMap_mapcontext / src / org / gvsig / fmap / mapcontext / rendering / symbols / SymbologyFactory.java @ 27989

History | View | Annotate | Download (18 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: SymbologyFactory.java 21071 2008-06-02 10:55:35Z vcaballero $
45
* $Log$
46
* Revision 1.11  2007-09-20 09:33:15  jaume
47
* Refactored: fixed name of IPersistAnce to IPersistence
48
*
49
* Revision 1.10  2007/09/17 14:16:11  jaume
50
* multilayer symbols sizing bug fixed
51
*
52
* Revision 1.9  2007/09/17 09:32:05  jaume
53
* view refresh frame rate now configurable
54
*
55
* Revision 1.8  2007/07/18 06:54:34  jaume
56
* continuing with cartographic support
57
*
58
* Revision 1.7  2007/04/26 11:41:00  jaume
59
* attempting to let defining size in world units
60
*
61
* Revision 1.6  2007/03/27 09:28:40  jaume
62
* *** empty log message ***
63
*
64
* Revision 1.5  2007/03/21 11:02:51  jaume
65
* javadoc
66
*
67
* Revision 1.4  2007/03/20 15:59:03  jaume
68
* improved factory toolkit
69
*
70
* Revision 1.3  2007/03/13 16:58:36  jaume
71
* Added QuantityByCategory (Multivariable legend) and some bugfixes in symbols
72
*
73
* Revision 1.2  2007/03/09 11:20:57  jaume
74
* Advanced symbology (start committing)
75
*
76
* Revision 1.1.2.2  2007/02/15 16:23:44  jaume
77
* *** empty log message ***
78
*
79
* Revision 1.1.2.1  2007/02/12 15:15:20  jaume
80
* refactored interval legend and added graduated symbol legend
81
*
82
* Revision 1.1.2.3  2007/02/09 07:47:05  jaume
83
* Isymbol moved
84
*
85
* Revision 1.1.2.2  2007/02/01 11:42:47  jaume
86
* *** empty log message ***
87
*
88
* Revision 1.1.2.1  2007/01/26 13:48:05  jaume
89
* patch for opening old projects
90
*
91
* Revision 1.1  2007/01/10 16:39:41  jaume
92
* ISymbol now belongs to com.iver.cit.gvsig.fmap.core.symbols package
93
*
94
* Revision 1.3  2006/11/06 16:06:52  jaume
95
* *** empty log message ***
96
*
97
* Revision 1.2  2006/11/06 07:33:54  jaume
98
* javadoc, source style
99
*
100
* Revision 1.1  2006/10/30 19:30:35  jaume
101
* *** empty log message ***
102
*
103
*
104
*/
105
package org.gvsig.fmap.mapcontext.rendering.symbols;
106

    
107
import java.awt.BasicStroke;
108
import java.awt.Color;
109
import java.awt.Font;
110
import java.awt.Graphics;
111
import java.awt.Graphics2D;
112
import java.awt.Rectangle;
113
import java.awt.geom.AffineTransform;
114
import java.awt.geom.Ellipse2D;
115
import java.io.File;
116

    
117
import javax.swing.JFrame;
118
import javax.swing.JPanel;
119

    
120
import org.gvsig.compat.CompatLocator;
121
import org.gvsig.fmap.geom.Geometry;
122
import org.gvsig.fmap.mapcontext.Messages;
123
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.IStyle;
124
import org.gvsig.tools.task.Cancellable;
125
import org.slf4j.Logger;
126
import org.slf4j.LoggerFactory;
127

    
128
import com.iver.utiles.IPersistence;
129
import com.iver.utiles.NotExistInXMLEntity;
130
import com.iver.utiles.XMLEntity;
131
import com.iver.utiles.XMLException;
132

    
133
/**
134
 * Factory for obtaining symbology of any kind from several sources like.
135
 * <ol>
136
 *         <li>
137
 *                 <b>XMLEntity's</b> that, at least, contains a full class name
138
 *                         string property that defines which class handles such symbol.
139
 *  </li>
140
 * </ol>
141
 *
142
 * @author jaume dominguez faus - jaume.dominguez@iver.es
143
 */
144
public class SymbologyFactory {
145

    
146
        /**
147
         * This Constants are only used in SymbologyPage (preferences page for symbology),
148
         * do not use in other context.
149
         */
150
        public static final Color FactoryDefaultSymbolColor = Color.GRAY;
151
        public static final Color FactoryDefaultFillSymbolColor = new Color(60, 235, 235);
152
        public static final Font FactoryDefaultTextFont =  new Font("Serif", Font.PLAIN, 8);
153
        public static final String FactorySymbolLibraryPath =
154
                System.getProperty("user.home") +
155
                File.separator +
156
                "gvSIG" +
157
                File.separator +
158
                "Symbols";
159

    
160
        public static final String FactoryStyleLibraryPath =
161
                System.getProperty("user.home") +
162
                File.separator +
163
                "gvSIG" +
164
                File.separator +
165
                "Styles";
166

    
167
        public static final Boolean FactoryDefaultAleatoryFillColor = Boolean.FALSE;
168

    
169

    
170
        public static Color DefaultSymbolColor = FactoryDefaultSymbolColor;
171
        public static Color DefaultFillSymbolColor = FactoryDefaultFillSymbolColor;
172
        public static Font DefaultTextFont = FactoryDefaultTextFont;
173
        public static String SymbolLibraryPath = FactorySymbolLibraryPath;
174
        public static String StyleLibraryPath = FactoryStyleLibraryPath;
175

    
176
        public static Boolean DefaultAleatoryFillColor = FactoryDefaultAleatoryFillColor;
177

    
178

    
179

    
180
        final static private Logger logger = LoggerFactory.getLogger(SymbologyFactory.class);
181
        private static WarningSymbol warningSymbol;
182

    
183
        /**
184
         * Factory that allows to create <b>ISymbol</b>'s from an ISymbol xml
185
         * descriptor. A barely specific XMLEntity object. The string passed in the
186
         * second argument is the description text that will be used in case no description
187
         * is supplied by the symbol's xml descriptor.
188
         *
189
         * @param xml, the symbol's xml descriptor
190
         * @param defaultDescription, a human readable description string for the symbol.
191
         * @return ISymbol
192
         */
193
        public static ISymbol createSymbolFromXML(XMLEntity xml, String defaultDescription) {
194
                if (!xml.contains("desc")) {
195
                        if (defaultDescription == null) {
196
                                defaultDescription = "";
197
                        }
198
                        xml.putProperty("desc", defaultDescription);
199
                }
200
                return (ISymbol) createFromXML(xml);
201
        }
202

    
203
        /**
204
         * Factory that allows to create <b>IStyle</b>'s from an <b>IStyle</b> xml descriptor. A barely
205
         * specific <b>XMLEntity</b> object. The string passed in the second argument is the
206
         * description text that will be used in case no description is supplied by the
207
         * style's xml descriptor.
208
         *
209
         * @param xml, the style's xml descriptor
210
         * @param defaultDescription, a human readable description string for the style
211
         * @return IStyle
212
         */
213
        public static IStyle createStyleFromXML(XMLEntity xml, String defaultDescription) {
214
                if (!xml.contains("desc")) {
215
                        if (defaultDescription == null) {
216
                                defaultDescription = "";
217
                        }
218

    
219
                        xml.putProperty("desc", defaultDescription);
220
                }
221
                return (IStyle) createFromXML(xml);
222
        }
223

    
224
        /**
225
         * Creates an <b>Object</b> described by the <b>XMLEntity</b> xml, please reffer to the
226
         * XMLEntity definition contract to know what is the format of the xml argument.
227
         * The result of this method is an <b>Object</b> that you can cast to the type you were
228
         * looking for by means of the xml entity.
229
         *
230
         * @param xml
231
         * @return Object
232
         */
233
        private static Object createFromXML(XMLEntity xml) {
234
                String className = null;
235
                try {
236
                        className = xml.getStringProperty("className");
237
                } catch (NotExistInXMLEntity e) {
238
                        logger.error("Class name not set.\n" +
239
                                                " Maybe you forgot to add the" +
240
                                                " putProperty(\"className\", yourClassName)" +
241
                                                " call in the getXMLEntity method of your class", e);
242
                }
243

    
244

    
245
                Class clazz = null;
246
                IPersistence obj = null;
247
                String s = className;
248

    
249
                try {
250
                        clazz = Class.forName(className);
251

    
252
                        if (xml.contains("desc")) {
253
                                s += " \"" + xml.getStringProperty("desc") +"\"";
254
                        }
255
                        // TODO remove the patch the day we deprecate FSymbol
256
                        // begin patch
257
                        if (clazz.equals(FSymbol.class)) {
258
                                obj = FSymbol.createFromXML(xml);
259
                        } else {
260
                        // end patch
261

    
262

    
263
                                obj = (IPersistence) clazz.newInstance();
264
                                logger.info(Messages.getString("creating")+"....... "+s);
265
                                try {
266
                                        obj.setXMLEntity(xml);
267
                                } catch (NotExistInXMLEntity neiXML) {
268
                                        logger.error(Messages.getString("failed_creating_object")+": "+s);
269
                                        throw neiXML;
270
                                } catch (XMLException e) {
271
                                        logger.error(Messages.getString("failed_creating_object")+": "+s);
272
                                        throw new NotExistInXMLEntity();
273
                                }
274

    
275
                        }
276

    
277
                } catch (InstantiationException e) {
278
                        logger.error("Trying to instantiate an interface" +
279
                                                " or abstract class + "+className, e);
280
                } catch (IllegalAccessException e) {
281
                        logger.error("IllegalAccessException: does your class have an" +
282
                                        " anonymous constructor?", e);
283
                } catch (ClassNotFoundException e) {
284
                        logger.error("No class called " + className +
285
                                        " was found.\nCheck the following.\n<br>" +
286
                                        "\t- The fullname of the class you're looking " +
287
                                                "for matches the value in the className " +
288
                                                "property of the XMLEntity ("+className+").\n<br>" +
289
                                        "\t- The jar file containing your symbol class is in" +
290
                                                "the application classpath<br>", e);
291
                }
292
                return obj;
293
        }
294

    
295
        /**
296
         * Returns a new empty instance of a <b>IMultiLayer</b> that can be one of:
297
         * <b>MultiLayerMarkerSymbol</b>, <b>MultiLayerLineSymbol</b>, or
298
         * <b>MultiLayerFillSymbol</b> depending on the shape type passed.
299
         *
300
         * @param shapeType, one of Geometry.TYPES.POINT, Geometry.TYPES.CURVE, or Geometry.TYPES.SURFACE
301
         * @return IMultiLayerSymbol
302
         */
303
        public static IMultiLayerSymbol createEmptyMultiLayerSymbol(int shapeType) {
304
                IMultiLayerSymbol mSym;
305
                switch (shapeType) {
306
                case Geometry.TYPES.POINT:
307
                        mSym = new MultiLayerMarkerSymbol();
308
                        break;
309
                case Geometry.TYPES.CURVE:
310
                        mSym = new MultiLayerLineSymbol();
311
                        break;
312
                case Geometry.TYPES.SURFACE:
313
                        mSym =new MultiLayerFillSymbol();
314
                        break;
315
                default:
316
                        throw new Error("Shape type not yet supported for multilayer symbols");
317
                }
318

    
319
                if (mSym instanceof CartographicSupport) {
320
                        CartographicSupport cs = (CartographicSupport) mSym;
321
                        cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
322
                        cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
323
                }
324
                return mSym;
325
        }
326

    
327
        /**
328
         * Returns a new instance of an <b>IMarkerSymbol</b>.
329
         * @return IMarkerSymbol, the default symbol for markers
330
         */
331
        public static IMarkerSymbol createDefaultMarkerSymbol() {
332
                SimpleMarkerSymbol sms = new SimpleMarkerSymbol();
333
                sms.setColor(DefaultSymbolColor);
334
                sms.setSize(4);
335
                toDefaultCartographicProperties(sms);
336
                return sms;
337
        }
338

    
339
        /**
340
         * Returns a new instance of an <b>ILineSymbol</b>. A black line.
341
         * @return ILineSymbol, the default symbol for lines.
342
         */
343
        public static ILineSymbol createDefaultLineSymbol() {
344
                SimpleLineSymbol sls = new SimpleLineSymbol();
345
                sls.setLineColor(DefaultSymbolColor);
346
                sls.setLineWidth(1);
347
                toDefaultCartographicProperties(sls);
348
                return sls;
349
        }
350

    
351
        private static void toDefaultCartographicProperties(CartographicSupport cs) {
352
                cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
353
                cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
354
        }
355

    
356
        /**
357
         * Returns a new instance of an <b>IFillSymbol</b>. Black outline,
358
         * and transparent fill.
359
         * @return IFillSymbol, the default symbol for polygons
360
         */
361
        public static IFillSymbol createDefaultFillSymbol() {
362

    
363
                SimpleFillSymbol sfs = new SimpleFillSymbol();
364

    
365
                // Default symbol for polygons
366
                sfs.setOutline(createDefaultLineSymbol());
367
                sfs.setFillColor(DefaultFillSymbolColor); // transparent fill
368
                toDefaultCartographicProperties(sfs);
369
                return sfs;
370
    }
371

    
372
        /**
373
         * Returns a new instance of an <b>ITextSymbol</b>.
374
         * @return ITextSymbol, the default symbol for texts
375
         */
376
        public static ITextSymbol createDefaultTextSymbol() {
377
                SimpleTextSymbol sts = new SimpleTextSymbol();
378

    
379
                sts.setFont(DefaultTextFont);
380
                sts.setTextColor(DefaultSymbolColor);
381
                toDefaultCartographicProperties(sts);
382

    
383
                return sts;
384
        }
385

    
386
        /**
387
         * Creates a new instance of the default symbol whose type is defined
388
         * by the parameter <b>shapeType</b>
389
         * @param shapeType, one of Geometry.TYPES.POINT, Geometry.TYPES.CURVE, Geometry.TYPES.SURFACE,
390
         * Geometry.TYPES.MULTIPOINT, Geometry.TYPES.TEXT, or Geometry.TYPES.MULTI.
391
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
392
         */
393
        public static ISymbol createDefaultSymbolByShapeType(int shapeType) {
394
                switch (shapeType) {
395
                case Geometry.TYPES.POINT:
396
                case Geometry.TYPES.MULTIPOINT:
397
                        return createDefaultMarkerSymbol();
398
                case Geometry.TYPES.CURVE:
399
                case Geometry.TYPES.MULTICURVE:
400
                        return createDefaultLineSymbol();
401
                case Geometry.TYPES.SURFACE:
402
                case Geometry.TYPES.MULTISURFACE:
403
                        return createDefaultFillSymbol();
404
                case Geometry.TYPES.TEXT:
405
                        return createDefaultTextSymbol();
406
                case Geometry.TYPES.GEOMETRY:
407
                        return new MultiShapeSymbol();
408
                case Geometry.TYPES.NULL:
409
                        return null;
410
                default:
411
                        throw new Error("shape type not yet supported");
412
                }
413
        }
414

    
415
        /**
416
         * Creates a new instance of the default symbol whose type is defined
417
         * by the parameter <b>shapeType</b> and uses the color defined by the
418
         * parameter color.
419
         * @param shapeType, one of Geometry.TYPES.POINT, Geometry.TYPES.CURVE, Geometry.TYPES.SURFACE,
420
         * @param color, the color to be applied to the new ISymbol.
421
         *
422
         * Geometry.TYPES.MULTIPOINT, Geometry.TYPES.TEXT, or Geometry.TYPES.MULTI.
423
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
424
         */
425
        public static ISymbol createDefaultSymbolByShapeType(int shapeType, Color color) {
426
                ISymbol sym = createDefaultSymbolByShapeType(shapeType);
427
                if (sym instanceof IMarkerSymbol) {
428
                        ((IMarkerSymbol) sym).setColor(color);
429
                }
430

    
431
                if (sym instanceof ILineSymbol) {
432
                        ((ILineSymbol) sym).setLineColor(color);
433
                }
434

    
435
                if (sym instanceof IFillSymbol) {
436
                        ((IFillSymbol) sym).setFillColor(color);
437
                }
438

    
439
                if (sym instanceof ITextSymbol) {
440
                        ((ITextSymbol) sym).setTextColor(color);
441
                }
442

    
443
                return sym;
444
        }
445

    
446

    
447

    
448
        public static ISymbol getWarningSymbol(String message, String symbolDesc, int symbolDrawExceptionType) {
449
                if (warningSymbol == null) {
450
                        warningSymbol = new WarningSymbol();
451
                }
452
                warningSymbol.setDescription(symbolDesc);
453
                warningSymbol.setMessage(message);
454
                warningSymbol.setDrawExceptionType(symbolDrawExceptionType);
455
                return warningSymbol;
456
        }
457

    
458
        private static class WarningSymbol extends MultiShapeSymbol {
459
                private String desc;
460
                private String message;
461
                private int exceptionType;
462
                private SimpleTextSymbol text;
463

    
464
                public static void main(String[] args) {
465
                        JFrame f = new JFrame();
466
                        final ISymbol warning = SymbologyFactory.getWarningSymbol(SymbolDrawingException.STR_UNSUPPORTED_SET_OF_SETTINGS, "a description", SymbolDrawingException.UNSUPPORTED_SET_OF_SETTINGS);
467
                        JPanel preview = new JPanel() {
468
                                protected void paintComponent(Graphics g) {
469
                                        // TODO Auto-generated method stub
470
                                        super.paintComponent(g);
471
                                        Graphics2D g2 = (Graphics2D)g;
472
                                        try {
473
                                                warning.drawInsideRectangle(g2, g2.getTransform(), getBounds());
474
                                        } catch (SymbolDrawingException e) {
475
                                                // TODO Auto-generated catch block
476
                                                e.printStackTrace();
477
                                        }
478
                                }
479
                        };
480
                        f.setContentPane(preview);
481
                        f.pack();
482
                        f.setVisible(true);
483
                }
484

    
485
                public void draw(Graphics2D g, AffineTransform affineTransform,
486
                                Geometry geom, Cancellable cancel) {
487
                try {
488
                        drawInsideRectangle(g, g.getTransform(), geom.getBounds());
489
                } catch (SymbolDrawingException e) {
490
                        // IMPOSSIBLE
491
                }
492
                }
493

    
494
                public void setDrawExceptionType(int symbolDrawExceptionType) {
495
                        this.exceptionType = symbolDrawExceptionType;
496
                }
497

    
498
                public void setMessage(String message) {
499
                        this.message = message;
500
                }
501

    
502
                public void drawInsideRectangle(Graphics2D g,
503
                                AffineTransform scaleInstance, Rectangle r)
504
                                throws SymbolDrawingException {
505
                        g.setClip(r);
506
                        if (message == null) {
507
                                message = "Symbol undrawable.\nPlease, check errors.";
508
                        }
509

    
510
                        String[] messageLines = CompatLocator.getStringUtils().split(message,"\n");
511
                        int strokeWidth = (int) (Math.min(r.width, r.height)*.1);
512

    
513
                        if (strokeWidth == 0) {
514
                                strokeWidth = 1;
515
                        }
516
                        g.setColor(Color.red);
517
                        g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
518
                        int x = r.x+strokeWidth;
519
                        int y = r.x+strokeWidth;
520
                        int width = r.width-(strokeWidth+strokeWidth);
521
                        int height = r.height-(strokeWidth+strokeWidth);
522
                        double radius = Math.min(width, height)*.5;
523
                        double centerX = r.getCenterX();
524
                        double centerY = r.getCenterY();
525
                        Ellipse2D circle = new Ellipse2D.Double(centerX - radius, centerY - radius, 2*radius, 2*radius);
526
                        g.draw(circle);
527
                        g.setClip(circle);
528
                        double aux = Math.cos(Math.PI*0.25)*radius;
529
                        g.drawLine((int) (centerX - aux), (int) (centerY - aux), (int) (centerX + aux), (int) (centerY + aux));
530
                        int fontSize = 20;
531
                        g.setFont(new Font("Arial", fontSize, Font.PLAIN));
532
                        g.setColor(Color.black);
533
                        g.setClip(null);
534

    
535
                        if (text == null) {
536
                                text = new SimpleTextSymbol();
537
                                text.setAutoresizeEnabled(true);
538

    
539
                        }
540

    
541
                        double lineHeight = (r.getHeight()-6)/messageLines.length;
542
                        Rectangle textRect = new Rectangle(
543
                                        (int) r.getMinX(),
544
                                        (int) r.getMinY()+6,
545
                                        (int) r.getWidth(),
546
                                        (int) lineHeight);
547
                        for (int i =0; i < messageLines.length; i++) {
548
                                text.setText(messageLines[i]);
549
                                text.drawInsideRectangle(g, null, textRect);
550
                                textRect.setLocation((int) r.getX(), (int) (r.getY()+r.getHeight()));
551
                        }
552
                }
553

    
554
                public XMLEntity getXMLEntity() {
555
                        XMLEntity xml = new XMLEntity();
556
                        xml.putProperty("className", getClass().getName());
557
                        xml.putProperty("desc", desc);
558
                        xml.putProperty("exceptionType", exceptionType);
559
                        xml.putProperty("message", message);
560
                        return xml;
561
                }
562

    
563
                public void setXMLEntity(XMLEntity xml) {
564
                        setDescription(xml.getStringProperty("desc"));
565
                        exceptionType = xml.getIntProperty("exceptionType");
566
                        message = xml.getStringProperty("message");
567
                }
568
        };
569
}