Statistics
| Revision:

root / branches / v2_0_0_prep / libFMap_mapcontext / src / org / gvsig / fmap / mapcontext / rendering / symbols / SymbologyFactory.java @ 21200

History | View | Annotate | Download (17 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.io.File;
115

    
116
import javax.print.attribute.PrintRequestAttributeSet;
117
import javax.swing.JFrame;
118
import javax.swing.JPanel;
119

    
120
import org.apache.log4j.Logger;
121
import org.gvsig.data.ReadException;
122
import org.gvsig.fmap.geom.Geometry;
123
import org.gvsig.fmap.mapcontext.Messages;
124
import org.gvsig.fmap.mapcontext.ViewPort;
125
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.IStyle;
126

    
127
import com.iver.utiles.IPersistence;
128
import com.iver.utiles.NotExistInXMLEntity;
129
import com.iver.utiles.XMLEntity;
130
import com.iver.utiles.swing.threads.Cancellable;
131

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

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

    
159

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

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

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

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

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

    
223

    
224
                Class clazz = null;
225
                IPersistence obj = null;
226
                String s = className;
227

    
228
                try {
229
                        clazz = Class.forName(className);
230

    
231
                        if (xml.contains("desc")) {
232
                                s += " \"" + xml.getStringProperty("desc") +"\"";
233
                        }
234
                        // TODO remove the patch the day we deprecate FSymbol
235
                        // begin patch
236
                        if (clazz.equals(FSymbol.class))
237
                                obj = FSymbol.createFromXML(xml);
238
                        else {
239
                        // end patch
240

    
241

    
242
                                obj = (IPersistence) clazz.newInstance();
243
                                logger.info(Messages.getString("creating")+"....... "+s);
244
                                try {
245
                                        obj.setXMLEntity(xml);
246
                                } catch (NotExistInXMLEntity neiXML) {
247
                                        logger.error(Messages.getString("failed_creating_object")+": "+s);
248
                                        throw neiXML;
249
                                }
250

    
251
                        }
252

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

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

    
295
                if (mSym instanceof CartographicSupport) {
296
                        CartographicSupport cs = (CartographicSupport) mSym;
297
                        cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
298
                        cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
299
                }
300
                return mSym;
301
        }
302

    
303
        /**
304
         * Returns a new instance of an <b>IMarkerSymbol</b>.
305
         * @return IMarkerSymbol, the default symbol for markers
306
         */
307
        public static IMarkerSymbol createDefaultMarkerSymbol() {
308
                SimpleMarkerSymbol sms = new SimpleMarkerSymbol();
309
                sms.setColor(DefaultSymbolColor);
310
                sms.setSize(4);
311
                toDefaultCartographicProperties(sms);
312
                return sms;
313
        }
314

    
315
        /**
316
         * Returns a new instance of an <b>ILineSymbol</b>. A black line.
317
         * @return ILineSymbol, the default symbol for lines.
318
         */
319
        public static ILineSymbol createDefaultLineSymbol() {
320
                SimpleLineSymbol sls = new SimpleLineSymbol();
321
                sls.setLineColor(DefaultSymbolColor);
322
                sls.setLineWidth(1);
323
                toDefaultCartographicProperties(sls);
324
                return sls;
325
        }
326

    
327
        private static void toDefaultCartographicProperties(CartographicSupport cs) {
328
                cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
329
                cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
330
        }
331

    
332
        /**
333
         * Returns a new instance of an <b>IFillSymbol</b>. Black outline,
334
         * and transparent fill.
335
         * @return IFillSymbol, the default symbol for polygons
336
         */
337
        public static IFillSymbol createDefaultFillSymbol() {
338

    
339
                SimpleFillSymbol sfs = new SimpleFillSymbol();
340

    
341
                // Default symbol for polygons
342
                sfs.setOutline(createDefaultLineSymbol());
343
                sfs.setFillColor(DefaultFillSymbolColor); // transparent fill
344
                toDefaultCartographicProperties(sfs);
345
                return sfs;
346
    }
347

    
348
        /**
349
         * Returns a new instance of an <b>ITextSymbol</b>.
350
         * @return ITextSymbol, the default symbol for texts
351
         */
352
        public static ITextSymbol createDefaultTextSymbol() {
353
                SimpleTextSymbol sts = new SimpleTextSymbol();
354

    
355
                sts.setFont(DefaultTextFont);
356
                sts.setTextColor(DefaultSymbolColor);
357
                toDefaultCartographicProperties(sts);
358

    
359
                return sts;
360
        }
361

    
362
        /**
363
         * Creates a new instance of the default symbol whose type is defined
364
         * by the parameter <b>shapeType</b>
365
         * @param shapeType, one of FShape.POINT, FShape.LINE, FShape.POLYGON,
366
         * FShape.MULTIPOINT, FShape.TEXT, or FShape.MULTI.
367
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
368
         */
369
        public static ISymbol createDefaultSymbolByShapeType(int shapeType) {
370
                switch (shapeType) {
371
                case Geometry.TYPES.POINT:
372
                        return createDefaultMarkerSymbol();
373
                case Geometry.TYPES.CURVE:
374
                        return createDefaultLineSymbol();
375
                case Geometry.TYPES.SURFACE:
376
                        return createDefaultFillSymbol();
377
                case Geometry.TYPES.MULTIPOINT:
378
                        return createDefaultMarkerSymbol();
379
                case Geometry.TYPES.TEXT:
380
                        return createDefaultTextSymbol();
381
                case Geometry.TYPES.AGGREGATE:
382
                        return new MultiShapeSymbol();
383
                case Geometry.TYPES.NULL:
384
                        return null;
385
                default:
386
                        throw new Error("shape type not yet supported");
387
                }
388
        }
389

    
390
        /**
391
         * Creates a new instance of the default symbol whose type is defined
392
         * by the parameter <b>shapeType</b> and uses the color defined by the
393
         * parameter color.
394
         * @param shapeType, one of FShape.POINT, FShape.LINE, FShape.POLYGON,
395
         * @param color, the color to be applied to the new ISymbol.
396
         *
397
         * FShape.MULTIPOINT, FShape.TEXT, or FShape.MULTI.
398
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
399
         */
400
        public static ISymbol createDefaultSymbolByShapeType(int shapeType, Color color) {
401
                ISymbol sym = createDefaultSymbolByShapeType(shapeType);
402
                if (sym instanceof IMarkerSymbol) {
403
                        ((IMarkerSymbol) sym).setColor(color);
404
                }
405

    
406
                if (sym instanceof ILineSymbol) {
407
                        ((ILineSymbol) sym).setLineColor(color);
408
                }
409

    
410
                if (sym instanceof IFillSymbol) {
411
                        ((IFillSymbol) sym).setFillColor(color);
412
                }
413

    
414
                if (sym instanceof ITextSymbol) {
415
                        ((ITextSymbol) sym).setTextColor(color);
416
                }
417

    
418
                return sym;
419
        }
420

    
421

    
422

    
423
        public static ISymbol getWarningSymbol(String message, String symbolDesc, int symbolDrawExceptionType) {
424
                if (warningSymbol == null) {
425
                        warningSymbol = new WarningSymbol();
426
                }
427
                warningSymbol.setDescription(symbolDesc);
428
                warningSymbol.setMessage(message);
429
                warningSymbol.setDrawExceptionType(symbolDrawExceptionType);
430
                return warningSymbol;
431
        }
432

    
433
        private static class WarningSymbol implements ISymbol {
434
                private String desc;
435
                private String message;
436
                private int exceptionType;
437

    
438
                public static void main(String[] args) {
439
                        JFrame f = new JFrame();
440
                        final ISymbol warning = SymbologyFactory.getWarningSymbol(SymbolDrawingException.STR_UNSUPPORTED_SET_OF_SETTINGS, "a description", SymbolDrawingException.UNSUPPORTED_SET_OF_SETTINGS);
441
                        JPanel preview = new JPanel() {
442
                                @Override
443
                                protected void paintComponent(Graphics g) {
444
                                        // TODO Auto-generated method stub
445
                                        super.paintComponent(g);
446
                                        Graphics2D g2 = (Graphics2D)g;
447
                                        try {
448
                                                warning.drawInsideRectangle(g2, g2.getTransform(), getBounds());
449
                                        } catch (SymbolDrawingException e) {
450
                                                // TODO Auto-generated catch block
451
                                                e.printStackTrace();
452
                                        }
453
                                }
454
                        };
455
                        f.setContentPane(preview);
456
                        f.pack();
457
                        f.setVisible(true);
458
                }
459

    
460
                public void draw(Graphics2D g, AffineTransform affineTransform,
461
                                Geometry geom, Cancellable cancel) {
462
                try {
463
                        drawInsideRectangle(g, g.getTransform(), geom.getBounds());
464
                } catch (SymbolDrawingException e) {
465
                        // IMPOSSIBLE
466
                }
467
                }
468

    
469
                public void setDrawExceptionType(int symbolDrawExceptionType) {
470
                        this.exceptionType = symbolDrawExceptionType;
471
                }
472

    
473
                public void setMessage(String message) {
474
                        this.message = message;
475
                }
476

    
477
                public void drawInsideRectangle(Graphics2D g,
478
                                AffineTransform scaleInstance, Rectangle r)
479
                                throws SymbolDrawingException {
480
                        if (message == null) {
481
                                message = "Symbol undrawable.\nPlease, check errors.";
482
                        }
483

    
484
                        String[] messageLines = message.split("\n");
485
                        int strokeWidth = 5;
486
                        g.setColor(Color.red);
487
                        g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
488
                        int x = r.x+strokeWidth;
489
                        int y = r.x+strokeWidth;
490
                        int width = r.width-(strokeWidth+strokeWidth);
491
                        int height = r.height-(strokeWidth+strokeWidth);
492

    
493
//                        g.drawOval(x, y, width, height);
494
//                        g.drawLine(x, y, width, height);
495
                        int fontSize = 20;
496
                        int vAlign = (int) (r.getCenterY() - ((fontSize+2)*messageLines.length/2));
497
                        g.setFont(new Font("Arial", fontSize, Font.PLAIN));
498
                        g.setColor(Color.black);
499

    
500
                        for (int i = 0; i < messageLines.length; i++) {
501
                                g.drawString(messageLines[i], 2, -vAlign);
502
                                System.out.println(messageLines[i]);
503
                                vAlign += fontSize + 2;
504
                        }
505
                }
506

    
507
                public XMLEntity getXMLEntity() {
508
                        throw new Error("Found symbology problems, please fix them before saving."); }
509

    
510
                public String getDescription() { return desc; }
511
                public int getOnePointRgb() { return 0; }
512
                public ISymbol getSymbolForSelection() { return this; }
513
                public void getPixExtentPlus(Geometry geom, float[] distances, ViewPort viewPort, int dpi) {}
514
                public int getSymbolType() { return 0; }
515
                public boolean isShapeVisible() { return false; }
516
                public boolean isSuitableFor(Geometry geom) { return true; }
517
                public void setDescription(String desc) { this.desc = desc; }
518
                public void setXMLEntity(XMLEntity xml) { }
519
                public String getClassName() { return null;        }
520

    
521
                public void print(Graphics2D g, AffineTransform at,
522
                                Geometry geom, PrintRequestAttributeSet properties)
523
                                throws ReadException {
524
                        throw new ReadException("Your symbology contains errors, please check them before printing.",
525
                                        new SymbolDrawingException(exceptionType));
526
                }
527

    
528

    
529
        };
530
}