Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / libraries / org.gvsig.symbology / org.gvsig.symbology.lib / org.gvsig.symbology.lib.impl / src / main / java / org / gvsig / symbology / fmap / mapcontext / rendering / symbol / line / impl / PictureLineSymbol.java @ 34297

History | View | Annotate | Download (13.2 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
package org.gvsig.symbology.fmap.mapcontext.rendering.symbol.line.impl;
42

    
43
import java.awt.BasicStroke;
44
import java.awt.Color;
45
import java.awt.Graphics2D;
46
import java.awt.Rectangle;
47
import java.awt.geom.AffineTransform;
48
import java.awt.geom.PathIterator;
49
import java.awt.geom.Point2D;
50
import java.io.IOException;
51
import java.net.URL;
52

    
53
import org.apache.batik.ext.awt.geom.PathLength;
54
import org.gvsig.compat.print.PrintAttributes;
55
import org.gvsig.fmap.dal.feature.Feature;
56
import org.gvsig.fmap.geom.Geometry;
57
import org.gvsig.fmap.mapcontext.MapContextLocator;
58
import org.gvsig.fmap.mapcontext.ViewPort;
59
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
60
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolDrawingException;
61
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
62
import org.gvsig.i18n.Messages;
63
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.impl.CartographicSupportToolkit;
64
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.line.IPictureLineSymbol;
65
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.style.BackgroundFileStyle;
66
import org.gvsig.tools.ToolsLocator;
67
import org.gvsig.tools.dynobject.DynStruct;
68
import org.gvsig.tools.persistence.PersistenceManager;
69
import org.gvsig.tools.persistence.PersistentState;
70
import org.gvsig.tools.persistence.exception.PersistenceException;
71
import org.gvsig.tools.task.Cancellable;
72
import org.gvsig.tools.util.Callable;
73
import org.slf4j.Logger;
74
import org.slf4j.LoggerFactory;
75

    
76

    
77
/**
78
 * PictureLineSymbol allows to use any symbol defined as an image (by an image file)
79
 * supported  by gvSIG.This symbol will be used as an initial object.The line will be
80
 * painted as a succession of puntual symbols through the path defined by it(the line).
81
 *
82
 * @author jaume dominguez faus - jaume.dominguez@iver.es
83
 */
84
public class PictureLineSymbol extends AbstractLineSymbol implements IPictureLineSymbol  {
85

    
86
        private static final Logger logger = LoggerFactory.getLogger(PictureLineSymbol.class);
87

    
88
    public static final String PICTURE_LINE_SYMBOL_PERSISTENCE_DEFINITION_NAME =
89
        "PictureLineSymbol";
90
    private static final String SELECTED = "selected";
91
    private static final String SELECTION_SYMBOL = "selectionSym";
92
    private static final String BACKGROUND_IMAGE = "bgImage";
93
    private static final String BACKGROUND_SELECTION_IMAGE = "bgSelImage";
94

    
95
        transient private PictureLineSymbol selectionSym;
96
        private double width;
97
        private boolean selected;
98
        private double xScale = 1, csXScale = xScale;
99
        private double yScale = 1, csYScale = yScale;
100

    
101
        private BackgroundFileStyle bgImage;
102
        private BackgroundFileStyle bgSelImage;
103
        private PrintAttributes properties;
104

    
105
        /**
106
         * Constructor method
107
         *
108
         */
109
        public PictureLineSymbol() {
110
                super();
111
        }
112
        /**
113
         * Constructor method
114
         * @param imageURL, URL of the normal image
115
         * @param selImageURL, URL of the image when it is selected in the map
116
         * @throws IOException
117
         */
118

    
119
        public PictureLineSymbol(URL imageURL, URL selImageURL) throws IOException {
120
                setImage(imageURL);
121
                if (selImageURL!=null)
122
                        setSelImage(selImageURL);
123
                else setSelImage(imageURL);
124
        }
125
        /**
126
         * Sets the URL for the image to be used as a picture line symbol
127
         * @param imageFile, File
128
         * @throws IOException
129
         */
130
        public void setImage(URL imageUrl) throws IOException{
131

    
132
                bgImage= BackgroundFileStyle.createStyleByURL(imageUrl);
133
        }
134
        /**
135
         * Sets the URL for the image to be used as a picture line symbol (when it is selected in the map)
136
         * @param imageFile, File
137
         * @throws IOException
138
         */
139
        public void setSelImage(URL selImageUrl) throws IOException{
140

    
141
                bgSelImage= BackgroundFileStyle.createStyleByURL(selImageUrl);
142
        }
143

    
144

    
145
        public void setLineWidth(double width) {
146
                this.width = width;
147
                getLineStyle().setLineWidth((float) width);
148
        }
149

    
150
        public double getLineWidth() {
151
                return width;
152
        }
153

    
154
        public ISymbol getSymbolForSelection() {
155
                if (selectionSym == null) {
156
                        selectionSym = (PictureLineSymbol) cloneForSelection();
157
                        selectionSym.selected=true;
158
                        selectionSym.selectionSym = selectionSym; // avoid too much lazy creations
159

    
160
                }
161
                return selectionSym;
162

    
163
        }
164

    
165
        public void draw(Graphics2D g, AffineTransform affineTransform,        Geometry geom, Feature f, Cancellable cancel) {
166
                draw(g, affineTransform, geom, cancel);
167
        }
168

    
169
        private void draw(Graphics2D g, AffineTransform affineTransform, Geometry geom, Cancellable cancel) {
170
                float csWidth = getLineStyle().getLineWidth();
171
                g.setClip(new BasicStroke((float) csWidth, BasicStroke.CAP_ROUND,BasicStroke.CAP_ROUND).createStrokedShape(geom));
172
                BackgroundFileStyle bg = (!selected) ? bgImage : bgSelImage ;
173

    
174
                if (csXScale<=0 &&  csYScale<=0)
175
                        return;
176

    
177
                Rectangle bounds = bg.getBounds();
178
                final double imageWidth  = bounds.getWidth()  * csXScale;
179
                final double imageHeight = bounds.getHeight() * csYScale;
180

    
181
                if (imageWidth==0 || imageHeight==0) return;
182
                int height = (int) csWidth;
183

    
184
                PathLength pl = new PathLength(geom);
185
                PathIterator iterator = geom.getPathIterator(null, 0.8);
186
                double[] theData = new double[6];
187
                Point2D firstPoint = null, startPoint = null, endPoint = null;
188
                if (!iterator.isDone()) {
189
                        if ( iterator.currentSegment(theData) != PathIterator.SEG_CLOSE) {
190
                                firstPoint = new Point2D.Double(theData[0], theData[1]);
191
                        }
192
                }
193
                float currentPathLength = 1;
194

    
195
                Rectangle rect = new Rectangle();
196

    
197
                while ((cancel==null || !cancel.isCanceled()) && !iterator.isDone()) {
198

    
199
                        int theType = iterator.currentSegment(theData);
200
                        switch (theType) {
201
                        case PathIterator.SEG_MOVETO:
202
                                startPoint = new Point2D.Double(theData[0], theData[1]);
203

    
204
                                endPoint = null;
205
                                iterator.next();
206

    
207
                                continue;
208

    
209
                        case PathIterator.SEG_LINETO:
210
                        case PathIterator.SEG_QUADTO:
211
                        case PathIterator.SEG_CUBICTO:
212
                                endPoint = new Point2D.Double(theData[0], theData[1]);
213

    
214
                                break;
215
                        case PathIterator.SEG_CLOSE:
216
                                endPoint = startPoint;
217
                                startPoint = firstPoint;
218
                                break;
219
                        }
220

    
221
                        double a = endPoint.getX() - startPoint.getX();
222
                        double b = endPoint.getY() - startPoint.getY();
223
                        double theta = pl.angleAtLength(currentPathLength);
224

    
225
                        double x = startPoint.getX();
226
                        double y = startPoint.getY();
227

    
228
                        // Theorem of Pythagoras
229
                        float segmentLength = (float) Math.sqrt(a*a + b*b);
230

    
231
                        // compute how many times the image has to be drawn
232
                        // to completely cover this segment's length
233
                        int count = (int) Math.ceil(segmentLength/imageWidth);
234

    
235
                        for (int i = 0; (cancel==null || !cancel.isCanceled()) && i < count; i++) {
236
                                g.translate(x, y);
237
                                g.rotate(theta);
238

    
239
                                double xOffsetTranslation = imageWidth*i;
240

    
241

    
242
                                g.translate(xOffsetTranslation, -csWidth);
243

    
244
                                rect.setBounds(0, (int) Math.round(height*.5), (int) Math.ceil(imageWidth), height);
245
                                try {
246
                                        bg.drawInsideRectangle(g, rect, false);
247
                                } catch (SymbolDrawingException e) {
248
                                        logger.warn(Messages.getText("label_style_could_not_be_painted"), e);
249
                                }
250
                                g.setColor(Color.red);
251
                                g.translate(-xOffsetTranslation, csWidth);
252

    
253
                                g.rotate(-theta);
254
                                g.translate(-x, -y);
255
                        }
256

    
257
                        startPoint = endPoint;
258
                        currentPathLength += segmentLength;
259
                        iterator.next();
260
                }
261

    
262
                g.setClip(null);
263
                g.setColor(Color.red);
264

    
265
        }
266

    
267
        /**
268
         * Sets the yscale for the picture line symbol
269
         * @param yScale
270
         */
271
        public void setYScale(double yScale) {
272
                this.yScale = yScale;
273
                this.csYScale = yScale;
274
        }
275
        /**
276
         * Sets the xscale for the picture line symbol
277
         * @param xScale
278
         */
279
        public void setXScale(double xScale) {
280
                this.xScale = xScale;
281
                this.csXScale = xScale;
282
        }
283

    
284
        public String getClassName() {
285
                return getClass().getName();
286
        }
287

    
288
        public void print(Graphics2D g, AffineTransform at, Geometry geom,
289
                        PrintAttributes properties) {
290
                this.properties=properties;
291
        draw(g, at, geom, null);
292
        this.properties=null;
293

    
294
        }
295
        
296
        /**
297
         * Returns the URL of the image that is used as a picture line symbol (when it
298
         * is selected in the map)
299
         * @return selimagePath,URL
300
         */
301
        public URL getSelectedSource(){
302
                return bgSelImage.getSource();
303
        }
304
        /**
305
         * Returns the URL of the image that is used as a picture line symbol
306
         * @return imagePath,URL
307
         */
308
        public URL getSource() {
309
                return bgImage.getSource();
310
        }
311
        
312
        /**
313
         * Returns the xscale for the picture line symbol
314
         * @param xScale
315
         */
316
        public double getXScale() {
317
                return xScale;
318
        }
319
        /**
320
         * Returns the yscale for the picture line symbol
321
         * @param yScale
322
         */
323
        public double getYScale() {
324
                return yScale;
325
        }
326

    
327
        @Override
328
        public void setCartographicSize(double cartographicSize, Geometry geom) {
329
                getLineStyle().setLineWidth((float) cartographicSize);
330
                double scale = cartographicSize/width;
331
                csXScale = xScale * scale;
332
                csYScale = yScale * scale;
333
        }
334

    
335
        @Override
336
        public double toCartographicSize(ViewPort viewPort, double dpi, Geometry geom) {
337
                double s = super.toCartographicSize(viewPort, dpi, geom);
338
                setCartographicSize(CartographicSupportToolkit.
339
                                getCartographicLength(this, width, viewPort, dpi), geom);
340
                return s;
341
        }
342
        
343
        
344
    public Object clone() throws CloneNotSupportedException {
345
        PictureLineSymbol copy = (PictureLineSymbol) super.clone();
346

    
347
        // clone selection
348
        if (selectionSym != null) {
349
                //to avoid an infinite loop
350
                if (this == selectionSym){
351
                        copy.selectionSym = copy;
352
                } else {
353
                        copy.selectionSym = (PictureLineSymbol) selectionSym.clone();
354
                }
355
        }
356

    
357
        // clone brackground image
358
        if (bgImage != null) {
359
            copy.bgImage = (BackgroundFileStyle) bgImage.clone();
360
        }
361

    
362
        // clone selection brackground image
363
        if (bgSelImage != null) {
364
            copy.bgSelImage = (BackgroundFileStyle) bgSelImage.clone();
365
        }
366

    
367
        // FIXME: clone properties
368
        
369
        return copy;
370
    }
371

    
372
    public void loadFromState(PersistentState state) throws PersistenceException {
373
        // Set parent style properties
374
        super.loadFromState(state);
375

    
376
        this.selected = (Boolean) state.get(SELECTED);
377
        this.selectionSym = (PictureLineSymbol) state.get(SELECTION_SYMBOL);
378
        this.bgImage = (BackgroundFileStyle) state.get(BACKGROUND_IMAGE);
379
        this.bgSelImage =
380
            (BackgroundFileStyle) state.get(BACKGROUND_SELECTION_IMAGE);
381
    }
382

    
383
    public void saveToState(PersistentState state) throws PersistenceException {
384
        // Save parent fill symbol properties
385
        super.saveToState(state);
386

    
387
        // Save own properties
388
        state.set(SELECTED, this.selected);
389
        state.set(SELECTION_SYMBOL, this.getSymbolForSelection());
390
        state.set(BACKGROUND_IMAGE, this.bgImage);
391
        state.set(BACKGROUND_SELECTION_IMAGE, this.bgSelImage);
392
    }
393

    
394
    public static class RegisterPersistence implements Callable {
395

    
396
        public Object call() throws Exception {
397
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
398
            if (manager.getDefinition(PICTURE_LINE_SYMBOL_PERSISTENCE_DEFINITION_NAME) == null) {
399
                DynStruct definition =
400
                    manager.addDefinition(PictureLineSymbol.class,
401
                                    PICTURE_LINE_SYMBOL_PERSISTENCE_DEFINITION_NAME,
402
                                    PICTURE_LINE_SYMBOL_PERSISTENCE_DEFINITION_NAME
403
                            + " Persistence definition",
404
                        null,
405
                        null);
406

    
407
                // Extend the Style base definition
408
                definition.extend(manager.getDefinition(LINE_SYMBOL_PERSISTENCE_DEFINITION_NAME));
409

    
410
                definition.addDynFieldBoolean(SELECTED).setMandatory(false);
411
                definition.addDynFieldObject(SELECTION_SYMBOL)
412
                    .setClassOfValue(PictureLineSymbol.class).setMandatory(false);
413
                definition.addDynFieldObject(BACKGROUND_IMAGE)
414
                    .setClassOfValue(BackgroundFileStyle.class).setMandatory(false);
415
                definition.addDynFieldObject(BACKGROUND_SELECTION_IMAGE)
416
                    .setClassOfValue(BackgroundFileStyle.class).setMandatory(false);
417
            }
418
            return Boolean.TRUE;
419
        }
420
    }
421
    
422
        public static class RegisterSymbol implements Callable {
423

    
424
                public Object call() throws Exception {
425
                        SymbolManager manager = MapContextLocator.getSymbolManager();
426

    
427
                        manager.registerSymbol(PICTURE_LINE_SYMBOL_PERSISTENCE_DEFINITION_NAME,
428
                            PictureLineSymbol.class);
429

    
430
                        return Boolean.TRUE;
431
                }
432
        }
433
}