Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / gui / layout / fframes / FFramePicture.java @ 7304

History | View | Annotate | Download (13.5 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 com.iver.andami.PluginServices;
48
import com.iver.andami.messages.NotificationManager;
49

    
50
import com.iver.cit.gvsig.fmap.DriverException;
51
import com.iver.cit.gvsig.gui.layout.Layout;
52
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
53
import com.iver.cit.gvsig.project.documents.layout.fframes.IFFrame;
54

    
55
import com.iver.utiles.XMLEntity;
56

    
57
import com.sun.jimi.core.Jimi;
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

    
67
import org.w3c.dom.Document;
68
import org.w3c.dom.Element;
69
import org.w3c.dom.svg.SVGDocument;
70

    
71
import java.awt.Dimension;
72
import java.awt.Graphics2D;
73
import java.awt.Image;
74
import java.awt.RenderingHints;
75
import java.awt.geom.AffineTransform;
76
import java.awt.geom.Rectangle2D;
77
import java.awt.image.BufferedImage;
78

    
79
import java.io.File;
80

    
81
import javax.swing.ImageIcon;
82

    
83

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
205
            gvtRoot.setTransform(ataux);
206
        }
207

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

    
211
        if (gvtRoot != null) {
212
            gvtRoot.paint(g);
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(100, 100);
315
        }
316

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

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

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

    
339
        String iString = file.toLowerCase();
340

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

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

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

    
362
            setImage(bi);
363

    
364
            return image;
365
        }
366

    
367
        return null;
368
    }
369

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

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

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

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

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

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

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

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

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

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

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

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

    
458
        }
459
}