Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / core / SymbologyFactory.java @ 28367

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 28367 2009-05-04 15:30:10Z 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 com.iver.cit.gvsig.fmap.core;
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.print.attribute.PrintRequestAttributeSet;
118
import javax.swing.JFrame;
119
import javax.swing.JPanel;
120

    
121
import org.apache.log4j.Logger;
122

    
123
import com.iver.cit.gvsig.fmap.Messages;
124
import com.iver.cit.gvsig.fmap.core.styles.IStyle;
125
import com.iver.cit.gvsig.fmap.core.symbols.IFillSymbol;
126
import com.iver.cit.gvsig.fmap.core.symbols.ILineSymbol;
127
import com.iver.cit.gvsig.fmap.core.symbols.IMarkerSymbol;
128
import com.iver.cit.gvsig.fmap.core.symbols.IMultiLayerSymbol;
129
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
130
import com.iver.cit.gvsig.fmap.core.symbols.ITextSymbol;
131
import com.iver.cit.gvsig.fmap.core.symbols.MultiLayerFillSymbol;
132
import com.iver.cit.gvsig.fmap.core.symbols.MultiLayerLineSymbol;
133
import com.iver.cit.gvsig.fmap.core.symbols.MultiLayerMarkerSymbol;
134
import com.iver.cit.gvsig.fmap.core.symbols.MultiShapeSymbol;
135
import com.iver.cit.gvsig.fmap.core.symbols.SimpleFillSymbol;
136
import com.iver.cit.gvsig.fmap.core.symbols.SimpleLineSymbol;
137
import com.iver.cit.gvsig.fmap.core.symbols.SimpleMarkerSymbol;
138
import com.iver.cit.gvsig.fmap.core.symbols.SimpleTextSymbol;
139
import com.iver.cit.gvsig.fmap.core.symbols.SymbolDrawingException;
140
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
141
import com.iver.utiles.IPersistence;
142
import com.iver.utiles.NotExistInXMLEntity;
143
import com.iver.utiles.XMLEntity;
144
import com.iver.utiles.swing.threads.Cancellable;
145

    
146
/**
147
 * Factory for obtaining symbology of any kind from several sources like.
148
 * <ol>
149
 *         <li>
150
 *                 <b>XMLEntity's</b> that, at least, contains a full class name
151
 *                         string property that defines which class handles such symbol.
152
 *  </li>
153
 * </ol>
154
 *
155
 * @author jaume dominguez faus - jaume.dominguez@iver.es
156
 */
157
public class SymbologyFactory {
158

    
159
        /**
160
         * This Constants are only used in SymbologyPage (preferences page for symbology),
161
         * do not use in other context.
162
         */
163
        public static final Color FactoryDefaultSymbolColor = Color.GRAY;
164
        public static final Color FactoryDefaultFillSymbolColor = new Color(60, 235, 235);
165
        public static final Font FactoryDefaultTextFont =  new Font("Serif", Font.PLAIN, 8);
166
        public static final String FactorySymbolLibraryPath =
167
                System.getProperty("user.home") +
168
                File.separator +
169
                "gvSIG" +
170
                File.separator +
171
                "Symbols";
172

    
173
        public static final String FactoryStyleLibraryPath =
174
                System.getProperty("user.home") +
175
                File.separator +
176
                "gvSIG" +
177
                File.separator +
178
                "Styles";
179

    
180
        public static final Boolean FactoryDefaultAleatoryFillColor = false;
181

    
182
        public static Color DefaultSymbolColor = FactoryDefaultSymbolColor;
183
        public static Color DefaultFillSymbolColor = FactoryDefaultFillSymbolColor;
184
        public static Font DefaultTextFont = FactoryDefaultTextFont;
185
        public static String SymbolLibraryPath = FactorySymbolLibraryPath;
186
        public static String StyleLibraryPath = FactoryStyleLibraryPath;
187

    
188
        public static Boolean DefaultAleatoryFillColor = FactoryDefaultAleatoryFillColor;
189

    
190

    
191

    
192
        private static Logger logger = Logger.getLogger(SymbologyFactory.class.getName());
193
        private static WarningSymbol warningSymbol;
194

    
195
        /**
196
         * Factory that allows to create <b>ISymbol</b>'s from an ISymbol xml
197
         * descriptor. A barely specific XMLEntity object. The string passed in the
198
         * second argument is the description text that will be used in case no description
199
         * is supplied by the symbol's xml descriptor.
200
         *
201
         * @param xml, the symbol's xml descriptor
202
         * @param defaultDescription, a human readable description string for the symbol.
203
         * @return ISymbol
204
         */
205
        public static ISymbol createSymbolFromXML(XMLEntity xml, String defaultDescription) {
206
                if (!xml.contains("desc")) {
207
                        if (defaultDescription == null) defaultDescription = "";
208
                        xml.putProperty("desc", defaultDescription);
209
                }
210
                return (ISymbol) createFromXML(xml);
211
        }
212

    
213
        /**
214
         * Factory that allows to create <b>IStyle</b>'s from an <b>IStyle</b> xml descriptor. A barely
215
         * specific <b>XMLEntity</b> object. The string passed in the second argument is the
216
         * description text that will be used in case no description is supplied by the
217
         * style's xml descriptor.
218
         *
219
         * @param xml, the style's xml descriptor
220
         * @param defaultDescription, a human readable description string for the style
221
         * @return IStyle
222
         */
223
        public static IStyle createStyleFromXML(XMLEntity xml, String defaultDescription) {
224
                if (!xml.contains("desc")) {
225
                        if (defaultDescription == null)
226
                                defaultDescription = "";
227

    
228
                        xml.putProperty("desc", defaultDescription);
229
                }
230
                return (IStyle) createFromXML(xml);
231
        }
232

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

    
253

    
254
                Class clazz = null;
255
                IPersistence obj = null;
256
                String s = className;
257

    
258
                try {
259
                        clazz = Class.forName(className);
260

    
261
                        if (xml.contains("desc")) {
262
                                s += " \"" + xml.getStringProperty("desc") +"\"";
263
                        }
264
                        // TODO remove the patch the day we deprecate FSymbol
265
                        // begin patch
266
                        if (clazz.equals(FSymbol.class)){
267
                                obj = FSymbol.createFromXML(xml);
268
                        } else {
269
                        // end patch
270

    
271

    
272
                                obj = (IPersistence) clazz.newInstance();
273
                                logger.info(Messages.getString("creating")+"....... "+s);
274
                                try {
275
                                        obj.setXMLEntity(xml);
276
                                } catch (NotExistInXMLEntity neiXML) {
277
                                        logger.error(Messages.getString("failed_creating_object")+": "+s);
278
                                        throw neiXML;
279
                                }
280

    
281
                        }
282

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

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

    
325
                if (mSym instanceof CartographicSupport) {
326
                        CartographicSupport cs = (CartographicSupport) mSym;
327
                        cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
328
                        cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
329
                }
330
                return mSym;
331
        }
332

    
333
        /**
334
         * Returns a new instance of an <b>IMarkerSymbol</b>.
335
         * @return IMarkerSymbol, the default symbol for markers
336
         */
337
        public static IMarkerSymbol createDefaultMarkerSymbol() {
338
                SimpleMarkerSymbol sms = new SimpleMarkerSymbol();
339
                sms.setColor(DefaultSymbolColor);
340
                sms.setSize(4);
341
                toDefaultCartographicProperties(sms);
342
                return sms;
343
        }
344

    
345
        /**
346
         * Returns a new instance of an <b>ILineSymbol</b>. A black line.
347
         * @return ILineSymbol, the default symbol for lines.
348
         */
349
        public static ILineSymbol createDefaultLineSymbol() {
350
                SimpleLineSymbol sls = new SimpleLineSymbol();
351
                sls.setLineColor(DefaultSymbolColor);
352
                sls.setLineWidth(1);
353
                toDefaultCartographicProperties(sls);
354
                return sls;
355
        }
356

    
357
        private static void toDefaultCartographicProperties(CartographicSupport cs) {
358
                cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
359
                cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
360
        }
361

    
362
        /**
363
         * Returns a new instance of an <b>IFillSymbol</b>. Black outline,
364
         * and transparent fill.
365
         * @return IFillSymbol, the default symbol for polygons
366
         */
367
        public static IFillSymbol createDefaultFillSymbol() {
368

    
369
                SimpleFillSymbol sfs = new SimpleFillSymbol();
370

    
371
                // Default symbol for polygons
372
                sfs.setOutline(createDefaultLineSymbol());
373
                sfs.setFillColor(DefaultFillSymbolColor); // transparent fill
374
                toDefaultCartographicProperties(sfs);
375
                return sfs;
376
    }
377

    
378
        /**
379
         * Returns a new instance of an <b>ITextSymbol</b>.
380
         * @return ITextSymbol, the default symbol for texts
381
         */
382
        public static ITextSymbol createDefaultTextSymbol() {
383
                SimpleTextSymbol sts = new SimpleTextSymbol();
384

    
385
                sts.setFont(DefaultTextFont);
386
                sts.setTextColor(DefaultSymbolColor);
387
                toDefaultCartographicProperties(sts);
388

    
389
                return sts;
390
        }
391

    
392
        /**
393
         * Creates a new instance of the default symbol whose type is defined
394
         * by the parameter <b>shapeType</b>
395
         * @param shapeType, one of FShape.POINT, FShape.LINE, FShape.POLYGON,
396
         * FShape.MULTIPOINT, FShape.TEXT, or FShape.MULTI.
397
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
398
         */
399
        public static ISymbol createDefaultSymbolByShapeType(int shapeType) {
400
                if ((shapeType & FShape.POINT)!= 0){
401
                        return createDefaultMarkerSymbol();
402
                } else if ((shapeType & FShape.LINE) != 0){
403
                        return createDefaultLineSymbol();
404
                } else if ((shapeType & FShape.POLYGON) != 0){
405
                        return createDefaultFillSymbol();
406
                } else if ((shapeType & FShape.MULTIPOINT) != 0){
407
                        return createDefaultMarkerSymbol();
408
                } else if ((shapeType & FShape.TEXT) != 0){
409
                        return createDefaultTextSymbol();
410
                } else if ((shapeType & FShape.MULTI) != 0){
411
                        return new MultiShapeSymbol();
412
                } else if (shapeType == FShape.NULL){
413
                        return null;
414
                }
415
                throw new Error("shape type not yet supported");
416
        }
417

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

    
431
                if (sym instanceof IMarkerSymbol) {
432
                        ((IMarkerSymbol) sym).setColor(color);
433
                }
434

    
435
                if (sym instanceof ILineSymbol) {
436
                        ((ILineSymbol) sym).setLineColor(color);
437
                }
438

    
439
                if (sym instanceof IFillSymbol) {
440
                        ((IFillSymbol) sym).setFillColor(color);
441
                }
442

    
443
                if (sym instanceof ITextSymbol) {
444
                        ((ITextSymbol) sym).setTextColor(color);
445
                }
446

    
447
                return sym;
448
        }
449

    
450

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

    
461
        private static class WarningSymbol extends MultiShapeSymbol {
462
                private String desc;
463
                private String message;
464
                private int exceptionType;
465
                private SimpleTextSymbol text;
466

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

    
489
                public void draw(Graphics2D g, AffineTransform affineTransform,
490
                                FShape shp, Cancellable cancel) {
491
                        try {
492
                                drawInsideRectangle(g, g.getTransform(), shp.getBounds(), null);
493
                        } catch (SymbolDrawingException e) {
494
                                // IMPOSSIBLE
495
                        }
496
                }
497

    
498
                public void setDrawExceptionType(int symbolDrawExceptionType) {
499
                        this.exceptionType = symbolDrawExceptionType;
500
                }
501

    
502
                public void setMessage(String message) {
503
                        this.message = message;
504
                }
505

    
506
                public void drawInsideRectangle(Graphics2D g,
507
                                AffineTransform scaleInstance, Rectangle r, PrintRequestAttributeSet properties)
508
                                throws SymbolDrawingException {
509
                        g.setClip(r);
510
                        if (message == null) {
511
                                message = "Symbol undrawable.\nPlease, check errors.";
512
                        }
513

    
514

    
515
                        String[] messageLines = message.split("\n");
516
                        int strokeWidth = (int) (Math.min(r.width, r.height)*.1);
517

    
518
                        if (strokeWidth == 0) strokeWidth = 1;
519

    
520
                        g.setColor(Color.red);
521
                        g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
522
                        int x = r.x+strokeWidth;
523
                        int y = r.x+strokeWidth;
524
                        int width = r.width-(strokeWidth+strokeWidth);
525
                        int height = r.height-(strokeWidth+strokeWidth);
526

    
527
                        double radius = Math.min(width, height)*.5;
528
                        double centerX = r.getCenterX();
529
                        double centerY = r.getCenterY();
530
                        Ellipse2D circle = new Ellipse2D.Double(centerX - radius, centerY - radius, 2*radius, 2*radius);
531
                        g.draw(circle);
532
                        g.setClip(circle);
533
                        double aux = Math.cos(Math.PI*0.25)*radius;
534
                        g.drawLine((int) (centerX - aux), (int) (centerY - aux), (int) (centerX + aux), (int) (centerY + aux));
535
                        int fontSize = 20;
536
                        g.setFont(new Font("Arial", fontSize, Font.PLAIN));
537
                        g.setColor(Color.black);
538
                        g.setClip(null);
539

    
540
                        if (text == null) {
541
                                text = new SimpleTextSymbol();
542
                                text.setAutoresizeEnabled(true);
543

    
544
                        }
545

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

    
559
                @Override
560
                public XMLEntity getXMLEntity() {
561
                        XMLEntity xml = new XMLEntity();
562
                        xml.putProperty("className", getClass().getName());
563
                        xml.putProperty("desc", desc);
564
                        xml.putProperty("exceptionType", exceptionType);
565
                        xml.putProperty("message", message);
566
                        return xml;
567
                }
568

    
569
                @Override
570
                public void setXMLEntity(XMLEntity xml) {
571
                        setDescription(xml.getStringProperty("desc"));
572
                        exceptionType = xml.getIntProperty("exceptionType");
573
                        message = xml.getStringProperty("message");
574
                }
575

    
576
        }
577

    
578

    
579
}