Statistics
| Revision:

svn-gvsig-desktop / branches / v10 / applications / appgvSIG / src / com / iver / cit / gvsig / gui / layout / fframes / FFramePicture.java @ 9449

History | View | Annotate | Download (14 KB)

1
/*
2
 * Created on 20-feb-2004
3
 *
4
 */
5
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
6
 *
7
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
22
 *
23
 * For more information, contact:
24
 *
25
 *  Generalitat Valenciana
26
 *   Conselleria d'Infraestructures i Transport
27
 *   Av. Blasco Ib??ez, 50
28
 *   46010 VALENCIA
29
 *   SPAIN
30
 *
31
 *      +34 963862235
32
 *   gvsig@gva.es
33
 *      www.gvsig.gva.es
34
 *
35
 *    or
36
 *
37
 *   IVER T.I. S.A
38
 *   Salamanca 50
39
 *   46005 Valencia
40
 *   Spain
41
 *
42
 *   +34 963163400
43
 *   dac@iver.es
44
 */
45
package com.iver.cit.gvsig.gui.layout.fframes;
46

    
47
import java.awt.Dimension;
48
import java.awt.Graphics2D;
49
import java.awt.Image;
50
import java.awt.RenderingHints;
51
import java.awt.geom.AffineTransform;
52
import java.awt.geom.Rectangle2D;
53
import java.awt.image.BufferedImage;
54
import java.awt.image.ImagingOpException;
55
import java.io.File;
56
import java.net.MalformedURLException;
57
import java.net.URI;
58
import java.net.URISyntaxException;
59
import java.net.URL;
60

    
61
import javax.swing.ImageIcon;
62

    
63
import org.apache.batik.bridge.BridgeContext;
64
import org.apache.batik.bridge.DocumentLoader;
65
import org.apache.batik.bridge.GVTBuilder;
66
import org.apache.batik.bridge.UserAgentAdapter;
67
import org.apache.batik.bridge.ViewBox;
68
import org.apache.batik.gvt.GraphicsNode;
69
import org.apache.batik.gvt.renderer.StaticRenderer;
70
import org.apache.batik.util.ParsedURL;
71
import org.w3c.dom.Document;
72
import org.w3c.dom.Element;
73
import org.w3c.dom.svg.SVGDocument;
74

    
75
import com.iver.andami.PluginServices;
76
import com.iver.andami.messages.NotificationManager;
77
import com.iver.cit.gvsig.fmap.DriverException;
78
import com.iver.cit.gvsig.gui.layout.Layout;
79
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
80
import com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame;
81
import com.iver.utiles.XMLEntity;
82
import com.sun.jimi.core.Jimi;
83

    
84

    
85
/**
86
 * FFrame para introducir una imagen en el Layout o para dibujar sobre el
87
 * graphics un SVG.
88
 *
89
 * @author Vicente Caballero Navarro
90
 */
91
public class FFramePicture extends FFrame {
92
    protected static RenderingHints defaultRenderingHints;
93

    
94
    static {
95
        defaultRenderingHints = new RenderingHints(null);
96
        defaultRenderingHints.put(RenderingHints.KEY_ANTIALIASING,
97
            RenderingHints.VALUE_ANTIALIAS_ON);
98

    
99
        defaultRenderingHints.put(RenderingHints.KEY_INTERPOLATION,
100
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
101
    }
102

    
103
    private static final int PRESENTACION = 0;
104
    private static final int ACTIVO = 1;
105
    private BufferedImage m_image = null;
106
    private int m_quality = PRESENTACION;
107
    private int m_viewing = ACTIVO;
108
    private String m_path = null;
109
    private boolean isSVG = false;
110
    private StaticRenderer renderer = new StaticRenderer();
111
    private Element elt;
112
    private GVTBuilder gvtBuilder = new GVTBuilder();
113
    private GraphicsNode gvtRoot = null;
114

    
115
    /**
116
     * Creates a new FFramePicture object.
117
     */
118
    public FFramePicture() {
119
    }
120

    
121
    /**
122
     * M?todo que dibuja sobre el graphics que se le pasa como par?metro, seg?n
123
     * la transformada afin que se debe de aplicar y el rect?ngulo que se debe
124
     * de dibujar.
125
     *
126
     * @param g Graphics
127
     * @param at Transformada afin.
128
     * @param rv rect?ngulo sobre el que hacer un clip.
129
     * @param imgBase Imagen para acelerar el dibujado.
130
     */
131
    public void draw(Graphics2D g, AffineTransform at, Rectangle2D rv,
132
        BufferedImage imgBase) {
133
        Rectangle2D.Double r = getBoundingBox(at);
134
        g.rotate(Math.toRadians(getRotation()), r.x + (r.width / 2),
135
            r.y + (r.height / 2));
136

    
137
        double x = r.getMinX();
138
        double y = r.getMinY();
139
        double w = r.getWidth();
140
        double h = r.getHeight();
141

    
142
        if (intersects(rv, r)|| w!=0 || h!=0) {
143
            if ((m_image == null) && !isSVG) { //Que no hay una imagen.
144
                drawEmpty(g);
145
            } else {
146
                if ((rv == null) || (getQuality() == PRESENTACION)) {
147
                    if (!isSVG) {
148
                        double scalex = w / m_image.getWidth(null);
149
                        double scaley = h / m_image.getHeight(null);
150
                       try {
151
                        AffineTransform xform = AffineTransform.getScaleInstance(scalex,
152
                                scaley);
153
                        AffineTransform xpos = AffineTransform.getTranslateInstance(x,
154
                                y);
155
                        xpos.concatenate(xform);
156
                        g.drawRenderedImage(m_image, xpos);
157
                       }catch (ImagingOpException e) {
158
                       }
159
                    } else if (isSVG) {
160
                        try {
161
                            if (r != null) {
162
                                drawSVG(g, r, rv);
163
                            }
164
                        } catch (OutOfMemoryError e) {
165
                            System.out.println("Dibujando SVG = " + e);
166
                        } catch (IllegalArgumentException e) {
167
                            System.out.println("Dibujando SVG = " + e);
168
                        }
169

    
170
                        System.gc();
171
                    }
172
                } else {
173
                    drawDraft(g);
174
                }
175
            }
176
        }
177

    
178
        g.rotate(Math.toRadians(-getRotation()), r.x + (r.width / 2),
179
            r.y + (r.height / 2));
180
    }
181

    
182
    /**
183
     * Dibuja SVG sobre el Graphics que se pasa como par?metro.
184
     *
185
     * @param g Graphics
186
     * @param rect rect?ngulo que ocupa.
187
     * @param rv Rect?ngulo que forma la parte visible del Layout.
188
     */
189
    private void drawSVG(Graphics2D g, Rectangle2D rect, Rectangle2D rv) {
190
        AffineTransform ataux = new AffineTransform();
191
        
192
            Rectangle2D bounds = gvtRoot.getBounds();                
193
    
194
        double scaleX = rect.getWidth() / bounds.getWidth();
195
        double scaleY = rect.getHeight() / bounds.getHeight();
196
        AffineTransform aux = AffineTransform.getScaleInstance(scaleX, scaleY);
197
        
198
        // escalamos para ver d?nde nos queda el nuevo origen
199
        Rectangle2D auxBounds = gvtRoot.getTransformedBounds(aux);
200
        ataux.translate(rect.getX() - auxBounds.getMinX(), rect.getY() - auxBounds.getMinY());
201
        
202
        ataux.concatenate(aux);
203

    
204
        gvtRoot.setTransform(ataux);
205

    
206
        RenderingHints renderingHints = new RenderingHints(defaultRenderingHints);
207
        g.setRenderingHints(renderingHints);
208

    
209
        if (gvtRoot != null) {
210
            gvtRoot.paint(g);
211
        }
212
        gvtRoot.setTransform(new AffineTransform());
213
                
214
    }
215

    
216
    /**
217
     * Rellena la calidad seg?n el entero que se pasa como par?metro.
218
     *
219
     * @param q entero que representa el tipo de calidad elegido.
220
     */
221
    public void setQuality(int q) {
222
        m_quality = q;
223
    }
224

    
225
    /**
226
     * Devuelve la calidad que est? seleccionada.
227
     *
228
     * @return entero que representa la calidad seleccionada.
229
     */
230
    public int getQuality() {
231
        return m_quality;
232
    }
233

    
234
    /**
235
     * Devuelve un entero que representa la forma en que se actualiza la vista.
236
     *
237
     * @return forma que se actualiza la vista.
238
     */
239
    public int getViewing() {
240
        return m_viewing;
241
    }
242

    
243
    /**
244
     * Rellena la forma de actualizar la vista.
245
     *
246
     * @param v entero que representa la forma de actualizar la vista.
247
     */
248
    public void setViewing(int v) {
249
        m_viewing = v;
250
    }
251

    
252
    /**
253
     * Rellena el nombre de la imagen.
254
     *
255
     * @param path nombre de la imagen.
256
     */
257
    public void setPath(String path) {
258
        m_path = path;
259
    }
260

    
261
    /**
262
     * Devuelve la ruta del fichero.
263
     *
264
     * @return String
265
     */
266
    public String getPath() {
267
        return m_path;
268
    }
269

    
270
    /**
271
     * Rellena la imagen.
272
     *
273
     * @param image
274
     */
275
    public void setImage(BufferedImage image) {
276
        m_image = image;
277
    }
278

    
279
    /**
280
     * DOCUMENT ME!
281
     *
282
     * @return DOCUMENT ME!
283
     *
284
     * @throws SaveException
285
     *
286
     * @see com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame#getXMLEntity()
287
     */
288
    public XMLEntity getXMLEntity() throws SaveException {
289
        XMLEntity xml = super.getXMLEntity();
290

    
291
        try {
292
            xml.putProperty("type", Layout.RECTANGLEPICTURE);
293
            xml.putProperty("m_path", m_path);
294
            xml.putProperty("m_quality", m_quality);
295
            xml.putProperty("m_viewing", m_viewing);
296
        } catch (Exception e) {
297
            throw new SaveException(e, this.getClass().getName());
298
        }
299

    
300
        return xml;
301
    }
302

    
303
    /**
304
     * Devuelve la dimensi?n dela imagen.
305
     *
306
     * @param file Nombre del fichero donde se encuentra la imagen.
307
     *
308
     * @return DOCUMENT ME!
309
     */
310
    public Dimension getBound(String file) {
311
        Image img = load(file);
312

    
313
        if (isSVG) {
314
                return new Dimension((int) gvtRoot.getBounds().getWidth(),
315
                                (int) gvtRoot.getBounds().getHeight());
316
            // return new Dimension(100, 100);
317
        }
318

    
319
        if (img == null) {
320
            return new Dimension((int) getBoundingBox(null).getWidth(),
321
                (int) getBoundingBox(null).getHeight());
322
        }
323

    
324
        return new Dimension(img.getWidth(null), img.getHeight(null));
325
    }
326

    
327
    /**
328
     * Carga el contnido del fichero.
329
     *
330
     * @param file Nombre del fichero a cargar.
331
     *
332
     * @return Imagen
333
     */
334
    public Image load(String file) {
335
        if (file==null)
336
                return null;
337
            ImageIcon tmpIcon = null;
338
        File f=new File(file);
339
        if (file == null || !f.exists()) {
340
            return null;
341
        }
342

    
343
        String iString = file.toLowerCase();
344

    
345
        if (iString.endsWith("jpg") || iString.endsWith("jpeg") ||
346
                iString.endsWith("gif")) {
347
            tmpIcon = new ImageIcon(Jimi.getImage(file, Jimi.VIRTUAL_MEMORY)); //((File)main.allImages.elementAt(x)).getAbsolutePath());
348
        } else if (iString.endsWith("png") || iString.endsWith("tif") ||
349
                iString.endsWith("ico") || iString.endsWith("xpm") ||
350
                iString.endsWith("bmp")) {
351
            tmpIcon = new ImageIcon(Jimi.getImage(file, Jimi.VIRTUAL_MEMORY)); //new ImageIcon(f.getPath());
352
        } else if (iString.endsWith("svg")) {
353
            isSVG = true;
354
            obtainStaticRenderer(new File(file));
355
        }
356

    
357
        if (!isSVG && (tmpIcon != null)) {
358
            Image image = tmpIcon.getImage();
359
            setPath(file);
360

    
361
            BufferedImage bi = new BufferedImage(image.getWidth(null),
362
                    image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
363
            Graphics2D biContext = bi.createGraphics();
364
            biContext.drawImage(image, 0, 0, null);
365

    
366
            setImage(bi);
367

    
368
            return image;
369
        }
370

    
371
        return null;
372
    }
373

    
374
    /**
375
     * Obtiene el renderer para svg a partir del svg.
376
     *
377
     * @param file Nombre del fichero.
378
     */
379
    private void obtainStaticRenderer(File file) {
380
        try {
381
            UserAgentAdapter userAgent = new UserAgentAdapter();
382
            DocumentLoader loader = new DocumentLoader(userAgent);
383
            BridgeContext ctx = new BridgeContext(userAgent, loader);
384
            Document svgDoc = loader.loadDocument(file.toURI().toString());
385
            gvtRoot = gvtBuilder.build(ctx, svgDoc);
386
            
387
            renderer.setTree(gvtRoot);
388
            elt = ((SVGDocument) svgDoc).getRootElement();
389
            
390
        } catch (Exception ex) {
391
            ex.printStackTrace();
392
        }
393
    }
394

    
395
    /**
396
     * Incorpora los atributos del XMLEntity en el objeto actual.
397
     *
398
     * @param xml XMLEntity
399
     * @param l Referencia al Layout.
400
     */
401
    public void setXMLEntity03(XMLEntity xml, Layout l) {
402
        if (xml.getIntProperty("m_Selected") != 0) {
403
            this.setSelected(true);
404
        } else {
405
            this.setSelected(false);
406
        }
407

    
408
        this.m_path = xml.getStringProperty("m_path");
409

    
410
        try {
411
            load(this.m_path);
412
        } catch (Exception ex) {
413
            NotificationManager.addError("Excepci?n :", ex);
414
        }
415

    
416
        this.m_quality = xml.getIntProperty("m_quality");
417
        this.m_viewing = xml.getIntProperty("m_viewing");
418
    }
419

    
420
    /**
421
     * Incorpora los atributos del XMLEntity en el objeto actual.
422
     *
423
     * @param xml XMLEntity
424
     */
425
    public void setXMLEntity(XMLEntity xml) {
426
        if (xml.getIntProperty("m_Selected") != 0) {
427
            this.setSelected(true);
428
        } else {
429
            this.setSelected(false);
430
        }
431

    
432
        this.m_path = xml.getStringProperty("m_path");
433

    
434
        try {
435
            load(this.m_path);
436
        } catch (Exception ex) {
437
            NotificationManager.addError("Excepci?n :", ex);
438
        }
439

    
440
        this.m_quality = xml.getIntProperty("m_quality");
441
        this.m_viewing = xml.getIntProperty("m_viewing");
442
        setRotation(xml.getDoubleProperty("m_rotation"));
443
    }
444

    
445
    /**
446
     * @see com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame#getNameFFrame()
447
     */
448
    public String getNameFFrame() {
449
        return PluginServices.getText(this, "imagen")+ num;
450
    }
451

    
452
    /**
453
     * @see com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame#print(java.awt.Graphics2D,
454
     *      java.awt.geom.AffineTransform)
455
     */
456
    public void print(Graphics2D g, AffineTransform at)
457
        throws DriverException {
458
        draw(g, at, null, null);
459
    }
460

    
461
    public void initialize() {
462
        // TODO Auto-generated method stub
463

    
464
    }
465

    
466
    public void cloneActions(IFFrame frame) {
467
        // TODO Auto-generated method stub
468

    
469
    }
470
}