Statistics
| Revision:

root / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / core / SymbologyFactory.java @ 18621

History | View | Annotate | Download (17.3 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 18621 2008-02-08 07:59:54Z jdominguez $
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.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

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

    
147
/**
148
 * Factory for obtaining symbology of any kind from several sources like.
149
 * <ol>
150
 *         <li>
151
 *                 <b>XMLEntity's</b> that, at least, contains a full class name
152
 *                         string property that defines which class handles such symbol.
153
 *  </li>
154
 * </ol>
155
 *
156
 * @author jaume dominguez faus - jaume.dominguez@iver.es
157
 */
158
public class SymbologyFactory {
159
        
160
        /**
161
         * This Constants are only used in SymbologyPage (preferences page for symbology), 
162
         * do not use in other context.
163
         */
164
        public static final Color FactoryDefaultSymbolColor = Color.GRAY;
165
        public static final Color FactoryDefaultFillSymbolColor = new Color(60, 235, 235);
166
        public static final Font FactoryDefaultTextFont =  new Font("Serif", Font.PLAIN, 8);
167
        public static final String FactorySymbolLibraryPath =
168
                System.getProperty("user.home") +
169
                File.separator +
170
                "gvSIG" +
171
                File.separator +
172
                "Symbols";
173
        
174
        
175
        public static Color DefaultSymbolColor = FactoryDefaultSymbolColor;
176
        public static Color DefaultFillSymbolColor = FactoryDefaultFillSymbolColor;
177
        public static Font DefaultTextFont = FactoryDefaultTextFont;
178
        public static String SymbolLibraryPath = FactorySymbolLibraryPath;
179
        
180
        private static Logger logger = Logger.getLogger(SymbologyFactory.class.getName());
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) defaultDescription = "";
196
                        xml.putProperty("desc", defaultDescription);
197
                }
198
                return (ISymbol) createFromXML(xml);
199
        }
200

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

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

    
238

    
239
                Class clazz = null;
240
                IPersistence obj = null;
241
                String s = className;
242

    
243
                try {
244
                        clazz = Class.forName(className);
245

    
246
                        if (xml.contains("desc")) {
247
                                s += " \"" + xml.getStringProperty("desc") +"\"";
248
                        }
249
                        // TODO remove the patch the day we deprecate FSymbol
250
                        // begin patch
251
                        if (clazz.equals(FSymbol.class))
252
                                obj = FSymbol.createFromXML(xml);
253
                        else {
254
                        // end patch
255

    
256

    
257
                                obj = (IPersistence) clazz.newInstance();
258
                                logger.info(Messages.getString("creating")+"....... "+s);
259
                                try {
260
                                        obj.setXMLEntity(xml);
261
                                } catch (NotExistInXMLEntity neiXML) {
262
                                        logger.error(Messages.getString("failed_creating_object")+": "+s);
263
                                        throw neiXML;
264
                                }
265

    
266
                        }
267

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

    
286
        /**
287
         * Returns a new empty instance of a <b>IMultiLayer</b> that can be one of:
288
         * <b>MultiLayerMarkerSymbol</b>, <b>MultiLayerLineSymbol</b>, or
289
         * <b>MultiLayerFillSymbol</b> depending on the shape type passed.
290
         *
291
         * @param shapeType, one of FShape.POINT, FShape.LINE, or FShape.POLYGON
292
         * @return IMultiLayerSymbol
293
         */
294
        public static IMultiLayerSymbol createEmptyMultiLayerSymbol(int shapeType) {
295
                IMultiLayerSymbol mSym;
296
                switch (shapeType) {
297
                case FShape.POINT:
298
                        mSym = new MultiLayerMarkerSymbol();
299
                        break;
300
                case FShape.LINE:
301
                        mSym = new MultiLayerLineSymbol();
302
                        break;
303
                case FShape.POLYGON:
304
                        mSym =new MultiLayerFillSymbol();
305
                        break;
306
                default:
307
                        throw new Error("Shape type not yet supported for multilayer symbols");
308
                }
309
                
310
                if (mSym instanceof CartographicSupport) {
311
                        CartographicSupport cs = (CartographicSupport) mSym;
312
                        cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
313
                        cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
314
                }
315
                return mSym;
316
        }
317

    
318
        /**
319
         * Returns a new instance of an <b>IMarkerSymbol</b>.
320
         * @return IMarkerSymbol, the default symbol for markers
321
         */
322
        public static IMarkerSymbol createDefaultMarkerSymbol() {
323
                SimpleMarkerSymbol sms = new SimpleMarkerSymbol();
324
                sms.setColor(DefaultSymbolColor);
325
                sms.setSize(4);
326
                toDefaultCartographicProperties(sms);
327
                return sms;
328
        }
329

    
330
        /**
331
         * Returns a new instance of an <b>ILineSymbol</b>. A black line.
332
         * @return ILineSymbol, the default symbol for lines.
333
         */
334
        public static ILineSymbol createDefaultLineSymbol() {
335
                SimpleLineSymbol sls = new SimpleLineSymbol();
336
                sls.setLineColor(DefaultSymbolColor);
337
                sls.setLineWidth(1);
338
                toDefaultCartographicProperties(sls);
339
                return sls;
340
        }
341

    
342
        private static void toDefaultCartographicProperties(CartographicSupport cs) {
343
                cs.setUnit(CartographicSupportToolkit.DefaultMeasureUnit);
344
                cs.setReferenceSystem(CartographicSupportToolkit.DefaultReferenceSystem);
345
        }
346
        
347
        /**
348
         * Returns a new instance of an <b>IFillSymbol</b>. Black outline,
349
         * and transparent fill.
350
         * @return IFillSymbol, the default symbol for polygons
351
         */
352
        public static IFillSymbol createDefaultFillSymbol() {
353

    
354
                SimpleFillSymbol sfs = new SimpleFillSymbol();
355

    
356
                // Default symbol for polygons
357
                sfs.setOutline(createDefaultLineSymbol());
358
                sfs.setFillColor(DefaultFillSymbolColor); // transparent fill
359
                toDefaultCartographicProperties(sfs);
360
                return sfs;
361
    }
362

    
363
        /**
364
         * Returns a new instance of an <b>ITextSymbol</b>.
365
         * @return ITextSymbol, the default symbol for texts
366
         */
367
        public static ITextSymbol createDefaultTextSymbol() {
368
                SimpleTextSymbol sts = new SimpleTextSymbol();
369

    
370
                sts.setFont(DefaultTextFont);
371
                sts.setTextColor(DefaultSymbolColor);
372
                toDefaultCartographicProperties(sts);
373

    
374
                return sts;
375
        }
376

    
377
        /**
378
         * Creates a new instance of the default symbol whose type is defined
379
         * by the parameter <b>shapeType</b>
380
         * @param shapeType, one of FShape.POINT, FShape.LINE, FShape.POLYGON,
381
         * FShape.MULTIPOINT, FShape.TEXT, or FShape.MULTI.
382
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
383
         */
384
        public static ISymbol createDefaultSymbolByShapeType(int shapeType) {
385
                switch (shapeType) {
386
                case FShape.POINT:
387
                        return createDefaultMarkerSymbol();
388
                case FShape.LINE:
389
                        return createDefaultLineSymbol();
390
                case FShape.POLYGON:
391
                        return createDefaultFillSymbol();
392
                case FShape.MULTIPOINT:
393
                        return createDefaultMarkerSymbol();
394
                case FShape.TEXT:
395
                        return createDefaultTextSymbol();
396
                case FShape.MULTI:
397
                        return new MultiShapeSymbol();
398
                case FShape.NULL:
399
                        return null;
400
                default:
401
                        throw new Error("shape type not yet supported");
402
                }
403
        }
404

    
405
        /**
406
         * Creates a new instance of the default symbol whose type is defined
407
         * by the parameter <b>shapeType</b> and uses the color defined by the
408
         * parameter color.
409
         * @param shapeType, one of FShape.POINT, FShape.LINE, FShape.POLYGON,
410
         * @param color, the color to be applied to the new ISymbol.
411
         *
412
         * FShape.MULTIPOINT, FShape.TEXT, or FShape.MULTI.
413
         * @return ISymbol, the default symbol for the shape type defined by <b>shapeType</b>
414
         */
415
        public static ISymbol createDefaultSymbolByShapeType(int shapeType, Color color) {
416
                ISymbol sym = createDefaultSymbolByShapeType(shapeType);
417
                if (sym instanceof IMarkerSymbol) {
418
                        ((IMarkerSymbol) sym).setColor(color);
419
                }
420

    
421
                if (sym instanceof ILineSymbol) {
422
                        ((ILineSymbol) sym).setLineColor(color);
423
                }
424

    
425
                if (sym instanceof IFillSymbol) {
426
                        ((IFillSymbol) sym).setFillColor(color);
427
                }
428

    
429
                if (sym instanceof ITextSymbol) {
430
                        ((ITextSymbol) sym).setTextColor(color);
431
                }
432

    
433
                return sym;
434
        }
435

    
436
        
437

    
438
        public static ISymbol getWarningSymbol(String message, String symbolDesc, int symbolDrawExceptionType) {
439
                if (warningSymbol == null) {
440
                        warningSymbol = new WarningSymbol();
441
                }
442
                warningSymbol.setDescription(symbolDesc);
443
                warningSymbol.setMessage(message);
444
                warningSymbol.setDrawExceptionType(symbolDrawExceptionType);
445
                return warningSymbol;
446
        }
447
        
448
        private static class WarningSymbol implements ISymbol {
449
                private String desc;
450
                private String message;
451
                private int exceptionType;
452
                
453
                public static void main(String[] args) {
454
                        JFrame f = new JFrame();
455
                        final ISymbol warning = SymbologyFactory.getWarningSymbol(SymbolDrawingException.STR_UNSUPPORTED_SET_OF_SETTINGS, "a description", SymbolDrawingException.UNSUPPORTED_SET_OF_SETTINGS);
456
                        JPanel preview = new JPanel() {
457
                                @Override
458
                                protected void paintComponent(Graphics g) {
459
                                        // TODO Auto-generated method stub
460
                                        super.paintComponent(g);
461
                                        Graphics2D g2 = (Graphics2D)g;
462
                                        try {
463
                                                warning.drawInsideRectangle(g2, g2.getTransform(), getBounds());
464
                                        } catch (SymbolDrawingException e) {
465
                                                // TODO Auto-generated catch block
466
                                                e.printStackTrace();
467
                                        }
468
                                }
469
                        };
470
                        f.setContentPane(preview);
471
                        f.pack();
472
                        f.setVisible(true);
473
                }
474

    
475
                public void draw(Graphics2D g, AffineTransform affineTransform,
476
                                FShape shp, Cancellable cancel) {
477
                try {
478
                        drawInsideRectangle(g, g.getTransform(), shp.getBounds());
479
                } catch (SymbolDrawingException e) {
480
                        // IMPOSSIBLE
481
                }
482
                }
483

    
484
                public void setDrawExceptionType(int symbolDrawExceptionType) {
485
                        this.exceptionType = symbolDrawExceptionType;
486
                }
487

    
488
                public void setMessage(String message) {
489
                        this.message = message;
490
                }
491

    
492
                public void drawInsideRectangle(Graphics2D g,
493
                                AffineTransform scaleInstance, Rectangle r)
494
                                throws SymbolDrawingException {
495
                        if (message == null) {
496
                                message = "Symbol undrawable.\nPlease, check errors.";
497
                        }
498
                        
499
                        String[] messageLines = message.split("\n");
500
                        int strokeWidth = 5;
501
                        g.setColor(Color.red);
502
                        g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
503
                        int x = r.x+strokeWidth;
504
                        int y = r.x+strokeWidth;
505
                        int width = r.width-(strokeWidth+strokeWidth);
506
                        int height = r.height-(strokeWidth+strokeWidth);
507
                        
508
//                        g.drawOval(x, y, width, height);
509
//                        g.drawLine(x, y, width, height);
510
                        int fontSize = 20;
511
                        int vAlign = (int) (r.getCenterY() - ((fontSize+2)*messageLines.length/2));  
512
                        g.setFont(new Font("Arial", fontSize, Font.PLAIN));
513
                        g.setColor(Color.black);
514
                        
515
                        for (int i = 0; i < messageLines.length; i++) {
516
                                g.drawString(messageLines[i], 2, -vAlign);
517
                                System.out.println(messageLines[i]);
518
                                vAlign += fontSize + 2;
519
                        }
520
                }
521
                
522
                public XMLEntity getXMLEntity() {
523
                        throw new Error("Found symbology problems, please fix them before saving."); }
524

    
525
                public String getDescription() { return desc; }
526
                public int getOnePointRgb() { return 0; }
527
                public ISymbol getSymbolForSelection() { return this; }
528
                public void getPixExtentPlus(FShape shp, float[] distances, ViewPort viewPort, int dpi) {}
529
                public int getSymbolType() { return 0; }
530
                public boolean isShapeVisible() { return false; }
531
                public boolean isSuitableFor(IGeometry geom) { return true; }
532
                public void setDescription(String desc) { this.desc = desc; }
533
                public void setXMLEntity(XMLEntity xml) { }
534
                public String getClassName() { return null;        }
535

    
536
                public void print(Graphics2D g, AffineTransform at,
537
                                FShape shape, PrintRequestAttributeSet properties)
538
                                throws ReadDriverException {
539
                        throw new ReadDriverException("Your symbology contains errors, please check them before printing.", 
540
                                        new SymbolDrawingException(exceptionType));
541
                }
542

    
543
                
544
        };
545
}