Statistics
| Revision:

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

History | View | Annotate | Download (17.6 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.print.attribute.PrintRequestAttributeSet;
118
import javax.swing.JFrame;
119
import javax.swing.JPanel;
120

    
121
import org.apache.log4j.Logger;
122
import org.gvsig.fmap.data.exceptions.ReadException;
123
import org.gvsig.fmap.geom.Geometry;
124
import org.gvsig.fmap.mapcontext.Messages;
125
import org.gvsig.fmap.mapcontext.ViewPort;
126
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.IStyle;
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
import com.iver.utiles.swing.threads.Cancellable;
133

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

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

    
161

    
162
        public static Color DefaultSymbolColor = FactoryDefaultSymbolColor;
163
        public static Color DefaultFillSymbolColor = FactoryDefaultFillSymbolColor;
164
        public static Font DefaultTextFont = FactoryDefaultTextFont;
165
        public static String SymbolLibraryPath = FactorySymbolLibraryPath;
166

    
167
        private static Logger logger = Logger.getLogger(SymbologyFactory.class.getName());
168
        private static WarningSymbol warningSymbol;
169

    
170
        /**
171
         * Factory that allows to create <b>ISymbol</b>'s from an ISymbol xml
172
         * descriptor. A barely specific XMLEntity object. The string passed in the
173
         * second argument is the description text that will be used in case no description
174
         * is supplied by the symbol's xml descriptor.
175
         *
176
         * @param xml, the symbol's xml descriptor
177
         * @param defaultDescription, a human readable description string for the symbol.
178
         * @return ISymbol
179
         */
180
        public static ISymbol createSymbolFromXML(XMLEntity xml, String defaultDescription) {
181
                if (!xml.contains("desc")) {
182
                        if (defaultDescription == null) defaultDescription = "";
183
                        xml.putProperty("desc", defaultDescription);
184
                }
185
                return (ISymbol) createFromXML(xml);
186
        }
187

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

    
203
                        xml.putProperty("desc", defaultDescription);
204
                }
205
                return (IStyle) createFromXML(xml);
206
        }
207

    
208
        /**
209
         * Creates an <b>Object</b> described by the <b>XMLEntity</b> xml, please reffer to the
210
         * XMLEntity definition contract to know what is the format of the xml argument.
211
         * The result of this method is an <b>Object</b> that you can cast to the type you were
212
         * looking for by means of the xml entity.
213
         *
214
         * @param xml
215
         * @return Object
216
         */
217
        private static Object createFromXML(XMLEntity xml) {
218
                String className = null;
219
                try {
220
                        className = xml.getStringProperty("className");
221
                } catch (NotExistInXMLEntity e) {
222
                        logger.error("Class name not set.\n" +
223
                                                " Maybe you forgot to add the" +
224
                                                " putProperty(\"className\", yourClassName)" +
225
                                                " call in the getXMLEntity method of your class", e);
226
                }
227

    
228

    
229
                Class clazz = null;
230
                IPersistence obj = null;
231
                String s = className;
232

    
233
                try {
234
                        clazz = Class.forName(className);
235

    
236
                        if (xml.contains("desc")) {
237
                                s += " \"" + xml.getStringProperty("desc") +"\"";
238
                        }
239
                        // TODO remove the patch the day we deprecate FSymbol
240
                        // begin patch
241
                        if (clazz.equals(FSymbol.class))
242
                                obj = FSymbol.createFromXML(xml);
243
                        else {
244
                        // end patch
245

    
246

    
247
                                obj = (IPersistence) clazz.newInstance();
248
                                logger.info(Messages.getString("creating")+"....... "+s);
249
                                try {
250
                                        obj.setXMLEntity(xml);
251
                                } catch (NotExistInXMLEntity neiXML) {
252
                                        logger.error(Messages.getString("failed_creating_object")+": "+s);
253
                                        throw neiXML;
254
                                } catch (XMLException e) {
255
                                        logger.error(Messages.getString("failed_creating_object")+": "+s);
256
                                        throw new NotExistInXMLEntity();
257
                                }
258

    
259
                        }
260

    
261
                } catch (InstantiationException e) {
262
                        logger.error("Trying to instantiate an interface" +
263
                                                " or abstract class + "+className, e);
264
                } catch (IllegalAccessException e) {
265
                        logger.error("IllegalAccessException: does your class have an" +
266
                                        " anonymous constructor?", e);
267
                } catch (ClassNotFoundException e) {
268
                        logger.error("No class called " + className +
269
                                        " was found.\nCheck the following.\n<br>" +
270
                                        "\t- The fullname of the class you're looking " +
271
                                                "for matches the value in the className " +
272
                                                "property of the XMLEntity ("+className+").\n<br>" +
273
                                        "\t- The jar file containing your symbol class is in" +
274
                                                "the application classpath<br>", e);
275
                }
276
                return obj;
277
        }
278

    
279
        /**
280
         * Returns a new empty instance of a <b>IMultiLayer</b> that can be one of:
281
         * <b>MultiLayerMarkerSymbol</b>, <b>MultiLayerLineSymbol</b>, or
282
         * <b>MultiLayerFillSymbol</b> depending on the shape type passed.
283
         *
284
         * @param shapeType, one of Geometry.TYPES.POINT, Geometry.TYPES.CURVE, or Geometry.TYPES.SURFACE
285
         * @return IMultiLayerSymbol
286
         */
287
        public static IMultiLayerSymbol createEmptyMultiLayerSymbol(int shapeType) {
288
                IMultiLayerSymbol mSym;
289
                switch (shapeType) {
290
                case Geometry.TYPES.POINT:
291
                        mSym = new MultiLayerMarkerSymbol();
292
                        break;
293
                case Geometry.TYPES.CURVE:
294
                        mSym = new MultiLayerLineSymbol();
295
                        break;
296
                case Geometry.TYPES.SURFACE:
297
                        mSym =new MultiLayerFillSymbol();
298
                        break;
299
                default:
300
                        throw new Error("Shape type not yet supported for multilayer symbols");
301
                }
302

    
303
                if (mSym instanceof CartographicSupport) {
304
                        CartographicSupport cs = (CartographicSupport) mSym;
305
                        cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
306
                        cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
307
                }
308
                return mSym;
309
        }
310

    
311
        /**
312
         * Returns a new instance of an <b>IMarkerSymbol</b>.
313
         * @return IMarkerSymbol, the default symbol for markers
314
         */
315
        public static IMarkerSymbol createDefaultMarkerSymbol() {
316
                SimpleMarkerSymbol sms = new SimpleMarkerSymbol();
317
                sms.setColor(DefaultSymbolColor);
318
                sms.setSize(4);
319
                toDefaultCartographicProperties(sms);
320
                return sms;
321
        }
322

    
323
        /**
324
         * Returns a new instance of an <b>ILineSymbol</b>. A black line.
325
         * @return ILineSymbol, the default symbol for lines.
326
         */
327
        public static ILineSymbol createDefaultLineSymbol() {
328
                SimpleLineSymbol sls = new SimpleLineSymbol();
329
                sls.setLineColor(DefaultSymbolColor);
330
                sls.setLineWidth(1);
331
                toDefaultCartographicProperties(sls);
332
                return sls;
333
        }
334

    
335
        private static void toDefaultCartographicProperties(CartographicSupport cs) {
336
                cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
337
                cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
338
        }
339

    
340
        /**
341
         * Returns a new instance of an <b>IFillSymbol</b>. Black outline,
342
         * and transparent fill.
343
         * @return IFillSymbol, the default symbol for polygons
344
         */
345
        public static IFillSymbol createDefaultFillSymbol() {
346

    
347
                SimpleFillSymbol sfs = new SimpleFillSymbol();
348

    
349
                // Default symbol for polygons
350
                sfs.setOutline(createDefaultLineSymbol());
351
                sfs.setFillColor(DefaultFillSymbolColor); // transparent fill
352
                toDefaultCartographicProperties(sfs);
353
                return sfs;
354
    }
355

    
356
        /**
357
         * Returns a new instance of an <b>ITextSymbol</b>.
358
         * @return ITextSymbol, the default symbol for texts
359
         */
360
        public static ITextSymbol createDefaultTextSymbol() {
361
                SimpleTextSymbol sts = new SimpleTextSymbol();
362

    
363
                sts.setFont(DefaultTextFont);
364
                sts.setTextColor(DefaultSymbolColor);
365
                toDefaultCartographicProperties(sts);
366

    
367
                return sts;
368
        }
369

    
370
        /**
371
         * Creates a new instance of the default symbol whose type is defined
372
         * by the parameter <b>shapeType</b>
373
         * @param shapeType, one of Geometry.TYPES.POINT, Geometry.TYPES.CURVE, Geometry.TYPES.SURFACE,
374
         * Geometry.TYPES.MULTIPOINT, Geometry.TYPES.TEXT, or Geometry.TYPES.MULTI.
375
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
376
         */
377
        public static ISymbol createDefaultSymbolByShapeType(int shapeType) {
378
                switch (shapeType) {
379
                case Geometry.TYPES.POINT:
380
                        return createDefaultMarkerSymbol();
381
                case Geometry.TYPES.CURVE:
382
                        return createDefaultLineSymbol();
383
                case Geometry.TYPES.SURFACE:
384
                        return createDefaultFillSymbol();
385
                case Geometry.TYPES.MULTIPOINT:
386
                        return createDefaultMarkerSymbol();
387
                case Geometry.TYPES.TEXT:
388
                        return createDefaultTextSymbol();
389
                case Geometry.TYPES.GEOMETRY:
390
                        return new MultiShapeSymbol();
391
                case Geometry.TYPES.NULL:
392
                        return null;
393
                default:
394
                        throw new Error("shape type not yet supported");
395
                }
396
        }
397

    
398
        /**
399
         * Creates a new instance of the default symbol whose type is defined
400
         * by the parameter <b>shapeType</b> and uses the color defined by the
401
         * parameter color.
402
         * @param shapeType, one of Geometry.TYPES.POINT, Geometry.TYPES.CURVE, Geometry.TYPES.SURFACE,
403
         * @param color, the color to be applied to the new ISymbol.
404
         *
405
         * Geometry.TYPES.MULTIPOINT, Geometry.TYPES.TEXT, or Geometry.TYPES.MULTI.
406
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
407
         */
408
        public static ISymbol createDefaultSymbolByShapeType(int shapeType, Color color) {
409
                ISymbol sym = createDefaultSymbolByShapeType(shapeType);
410
                if (sym instanceof IMarkerSymbol) {
411
                        ((IMarkerSymbol) sym).setColor(color);
412
                }
413

    
414
                if (sym instanceof ILineSymbol) {
415
                        ((ILineSymbol) sym).setLineColor(color);
416
                }
417

    
418
                if (sym instanceof IFillSymbol) {
419
                        ((IFillSymbol) sym).setFillColor(color);
420
                }
421

    
422
                if (sym instanceof ITextSymbol) {
423
                        ((ITextSymbol) sym).setTextColor(color);
424
                }
425

    
426
                return sym;
427
        }
428

    
429

    
430

    
431
        public static ISymbol getWarningSymbol(String message, String symbolDesc, int symbolDrawExceptionType) {
432
                if (warningSymbol == null) {
433
                        warningSymbol = new WarningSymbol();
434
                }
435
                warningSymbol.setDescription(symbolDesc);
436
                warningSymbol.setMessage(message);
437
                warningSymbol.setDrawExceptionType(symbolDrawExceptionType);
438
                return warningSymbol;
439
        }
440

    
441
        private static class WarningSymbol extends MultiShapeSymbol {
442
                private String desc;
443
                private String message;
444
                private int exceptionType;
445
                private SimpleTextSymbol text;
446

    
447
                public static void main(String[] args) {
448
                        JFrame f = new JFrame();
449
                        final ISymbol warning = SymbologyFactory.getWarningSymbol(SymbolDrawingException.STR_UNSUPPORTED_SET_OF_SETTINGS, "a description", SymbolDrawingException.UNSUPPORTED_SET_OF_SETTINGS);
450
                        JPanel preview = new JPanel() {
451
                                protected void paintComponent(Graphics g) {
452
                                        // TODO Auto-generated method stub
453
                                        super.paintComponent(g);
454
                                        Graphics2D g2 = (Graphics2D)g;
455
                                        try {
456
                                                warning.drawInsideRectangle(g2, g2.getTransform(), getBounds());
457
                                        } catch (SymbolDrawingException e) {
458
                                                // TODO Auto-generated catch block
459
                                                e.printStackTrace();
460
                                        }
461
                                }
462
                        };
463
                        f.setContentPane(preview);
464
                        f.pack();
465
                        f.setVisible(true);
466
                }
467

    
468
                public void draw(Graphics2D g, AffineTransform affineTransform,
469
                                Geometry geom, Cancellable cancel) {
470
                try {
471
                        drawInsideRectangle(g, g.getTransform(), geom.getBounds());
472
                } catch (SymbolDrawingException e) {
473
                        // IMPOSSIBLE
474
                }
475
                }
476

    
477
                public void setDrawExceptionType(int symbolDrawExceptionType) {
478
                        this.exceptionType = symbolDrawExceptionType;
479
                }
480

    
481
                public void setMessage(String message) {
482
                        this.message = message;
483
                }
484

    
485
                public void drawInsideRectangle(Graphics2D g,
486
                                AffineTransform scaleInstance, Rectangle r)
487
                                throws SymbolDrawingException {
488
                        g.setClip(r);
489
                        if (message == null) {
490
                                message = "Symbol undrawable.\nPlease, check errors.";
491
                        }
492

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

    
496
                        if (strokeWidth == 0) strokeWidth = 1;
497
                        g.setColor(Color.red);
498
                        g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
499
                        int x = r.x+strokeWidth;
500
                        int y = r.x+strokeWidth;
501
                        int width = r.width-(strokeWidth+strokeWidth);
502
                        int height = r.height-(strokeWidth+strokeWidth);
503
                        double radius = Math.min(width, height)*.5;
504
                        double centerX = r.getCenterX();
505
                        double centerY = r.getCenterY();
506
                        Ellipse2D circle = new Ellipse2D.Double(centerX - radius, centerY - radius, 2*radius, 2*radius);
507
                        g.draw(circle);
508
                        g.setClip(circle);
509
                        double aux = Math.cos(Math.PI*0.25)*radius;
510
                        g.drawLine((int) (centerX - aux), (int) (centerY - aux), (int) (centerX + aux), (int) (centerY + aux));
511
                        int fontSize = 20;
512
                        g.setFont(new Font("Arial", fontSize, Font.PLAIN));
513
                        g.setColor(Color.black);
514
                        g.setClip(null);
515

    
516
                        if (text == null) {
517
                                text = new SimpleTextSymbol();
518
                                text.setAutoresizeEnabled(true);
519

    
520
                        }
521

    
522
                        double lineHeight = (r.getHeight()-6)/messageLines.length;
523
                        Rectangle textRect = new Rectangle(
524
                                        (int) r.getMinX(),
525
                                        (int) r.getMinY()+6,
526
                                        (int) r.getWidth(),
527
                                        (int) lineHeight);
528
                        for (int i =0; i < messageLines.length; i++) {
529
                                text.setText(messageLines[i]);
530
                                text.drawInsideRectangle(g, null, textRect);
531
                                textRect.setLocation((int) r.getX(), (int) (r.getY()+r.getHeight()));
532
                        }
533
                }
534

    
535
                public XMLEntity getXMLEntity() {
536
                        XMLEntity xml = new XMLEntity();
537
                        xml.putProperty("className", getClass().getName());
538
                        xml.putProperty("desc", desc);
539
                        xml.putProperty("exceptionType", exceptionType);
540
                        xml.putProperty("message", message);
541
                        return xml;
542
                }
543

    
544
                public void setXMLEntity(XMLEntity xml) {
545
                        setDescription(xml.getStringProperty("desc"));
546
                        exceptionType = xml.getIntProperty("exceptionType");
547
                        message = xml.getStringProperty("message");
548
                }
549
        };
550
}