Statistics
| Revision:

root / branches / piloto3d / applications / appgvSIG / src / com / iver / cit / gvsig / gui / layout / fframes / FFramePicture.java @ 9529

History | View | Annotate | Download (13.8 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

    
57
import javax.swing.ImageIcon;
58

    
59
import org.apache.batik.bridge.BridgeContext;
60
import org.apache.batik.bridge.DocumentLoader;
61
import org.apache.batik.bridge.GVTBuilder;
62
import org.apache.batik.bridge.UserAgentAdapter;
63
import org.apache.batik.bridge.ViewBox;
64
import org.apache.batik.gvt.GraphicsNode;
65
import org.apache.batik.gvt.renderer.StaticRenderer;
66
import org.w3c.dom.Document;
67
import org.w3c.dom.Element;
68
import org.w3c.dom.svg.SVGDocument;
69

    
70
import com.iver.andami.PluginServices;
71
import com.iver.andami.messages.NotificationManager;
72
import com.iver.cit.gvsig.fmap.DriverException;
73
import com.iver.cit.gvsig.gui.layout.Layout;
74
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
75
import com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame;
76
import com.iver.utiles.XMLEntity;
77
import com.sun.jimi.core.Jimi;
78

    
79

    
80
/**
81
 * FFrame para introducir una imagen en el Layout o para dibujar sobre el
82
 * graphics un SVG.
83
 *
84
 * @author Vicente Caballero Navarro
85
 */
86
public class FFramePicture extends FFrame {
87
    protected static RenderingHints defaultRenderingHints;
88

    
89
    static {
90
        defaultRenderingHints = new RenderingHints(null);
91
        defaultRenderingHints.put(RenderingHints.KEY_ANTIALIASING,
92
            RenderingHints.VALUE_ANTIALIAS_ON);
93

    
94
        defaultRenderingHints.put(RenderingHints.KEY_INTERPOLATION,
95
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
96
    }
97

    
98
    private static final int PRESENTACION = 0;
99
    private static final int ACTIVO = 1;
100
    private BufferedImage m_image = null;
101
    private int m_quality = PRESENTACION;
102
    private int m_viewing = ACTIVO;
103
    private String m_path = null;
104
    private boolean isSVG = false;
105
    private StaticRenderer renderer = new StaticRenderer();
106
    private Element elt;
107
    private GVTBuilder gvtBuilder = new GVTBuilder();
108
    private GraphicsNode gvtRoot = null;
109

    
110
    /**
111
     * Creates a new FFramePicture object.
112
     */
113
    public FFramePicture() {
114
    }
115

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

    
132
        double x = r.getMinX();
133
        double y = r.getMinY();
134
        double w = r.getWidth();
135
        double h = r.getHeight();
136

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

    
165
                        System.gc();
166
                    }
167
                } else {
168
                    drawDraft(g);
169
                }
170
            }
171
        }
172

    
173
        g.rotate(Math.toRadians(-getRotation()), r.x + (r.width / 2),
174
            r.y + (r.height / 2));
175
    }
176

    
177
    /**
178
     * Dibuja SVG sobre el Graphics que se pasa como par?metro.
179
     *
180
     * @param g Graphics
181
     * @param rect rect?ngulo que ocupa.
182
     * @param rv Rect?ngulo que forma la parte visible del Layout.
183
     */
184
    private void drawSVG(Graphics2D g, Rectangle2D rect, Rectangle2D rv) {
185
        if ((rv == null) || rv.contains(rect)) {
186
            AffineTransform ataux = new AffineTransform();
187

    
188
            ataux.translate(rect.getX(), rect.getY());
189

    
190
            try {
191
                ataux.concatenate(ViewBox.getViewTransform(null, elt,
192
                        (float) rect.getWidth(), (float) rect.getHeight()));
193
                gvtRoot.setTransform(ataux);
194
            } catch (Exception e) {
195
                // TODO: handle exception
196
            }
197
        } else {
198
            AffineTransform ataux = new AffineTransform();
199

    
200
            ataux.translate(rect.getX(), rect.getY());
201
            ataux.concatenate(ViewBox.getViewTransform(null, elt,
202
                    (float) rect.getWidth(), (float) rect.getHeight()));
203

    
204
            gvtRoot.setTransform(ataux);
205
        }
206

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

    
210
        if (gvtRoot != null) {
211
            gvtRoot.paint(g);
212
        }
213
    }
214

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

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

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

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

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

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

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

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

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

    
299
        return xml;
300
    }
301

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

    
312
        if (isSVG) {
313
            return new Dimension(100, 100);
314
        }
315

    
316
        if (img == null) {
317
            return new Dimension((int) getBoundingBox(null).getWidth(),
318
                (int) getBoundingBox(null).getHeight());
319
        }
320

    
321
        return new Dimension(img.getWidth(null), img.getHeight(null));
322
    }
323

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

    
340
        String iString = file.toLowerCase();
341

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

    
354
        if (!isSVG && (tmpIcon != null)) {
355
            Image image = tmpIcon.getImage();
356
            setPath(file);
357

    
358
            BufferedImage bi = new BufferedImage(image.getWidth(null),
359
                    image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
360
            Graphics2D biContext = bi.createGraphics();
361
            biContext.drawImage(image, 0, 0, null);
362

    
363
            setImage(bi);
364

    
365
            return image;
366
        }
367

    
368
        return null;
369
    }
370

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

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

    
403
        this.m_path = xml.getStringProperty("m_path");
404

    
405
        try {
406
            load(this.m_path);
407
        } catch (Exception ex) {
408
            NotificationManager.addError("Excepci?n :", ex);
409
        }
410

    
411
        this.m_quality = xml.getIntProperty("m_quality");
412
        this.m_viewing = xml.getIntProperty("m_viewing");
413
    }
414

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

    
427
        this.m_path = xml.getStringProperty("m_path");
428

    
429
        try {
430
            load(this.m_path);
431
        } catch (Exception ex) {
432
            NotificationManager.addError("Excepci?n :", ex);
433
        }
434

    
435
        this.m_quality = xml.getIntProperty("m_quality");
436
        this.m_viewing = xml.getIntProperty("m_viewing");
437
        setRotation(xml.getDoubleProperty("m_rotation"));
438
    }
439

    
440
    /**
441
     * @see com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame#getNameFFrame()
442
     */
443
    public String getNameFFrame() {
444
        return PluginServices.getText(this, "imagen")+ num;
445
    }
446

    
447
    /**
448
     * @see com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame#print(java.awt.Graphics2D,
449
     *      java.awt.geom.AffineTransform)
450
     */
451
    public void print(Graphics2D g, AffineTransform at)
452
        throws DriverException {
453
        draw(g, at, null, null);
454
    }
455

    
456
    public void initialize() {
457
        // TODO Auto-generated method stub
458

    
459
    }
460

    
461
    public void cloneActions(IFFrame frame) {
462
        // TODO Auto-generated method stub
463

    
464
    }
465
}