Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / com / iver / cit / gvsig / project / documents / layout / fframes / FFramePicture.java @ 24759

History | View | Annotate | Download (14.2 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.project.documents.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.print.attribute.PrintRequestAttributeSet;
58
import javax.swing.ImageIcon;
59

    
60
import org.apache.batik.bridge.BridgeContext;
61
import org.apache.batik.bridge.DocumentLoader;
62
import org.apache.batik.bridge.GVTBuilder;
63
import org.apache.batik.bridge.UserAgentAdapter;
64
import org.apache.batik.bridge.ViewBox;
65
import org.apache.batik.gvt.GraphicsNode;
66
import org.apache.batik.gvt.renderer.StaticRenderer;
67
import org.gvsig.fmap.dal.exception.ReadException;
68
import org.gvsig.fmap.geom.Geometry;
69
import org.w3c.dom.Document;
70
import org.w3c.dom.Element;
71
import org.w3c.dom.svg.SVGDocument;
72

    
73
import com.iver.andami.PluginServices;
74
import com.iver.andami.messages.NotificationManager;
75
import com.iver.cit.gvsig.project.documents.exceptions.SaveException;
76
import com.iver.cit.gvsig.project.documents.layout.fframes.gui.dialogs.FFramePictureDialog;
77
import com.iver.cit.gvsig.project.documents.layout.fframes.gui.dialogs.IFFrameDialog;
78
import com.iver.cit.gvsig.project.documents.layout.gui.Layout;
79
import com.iver.utiles.XMLEntity;
80
import com.sun.jimi.core.Jimi;
81

    
82

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

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

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

    
101
    private static final int PRESENTACION = 0;
102
    private static final int ACTIVO = 1;
103
    private BufferedImage m_image = null;
104
    private int m_quality = PRESENTACION;
105
    private int m_viewing = ACTIVO;
106
    private String m_path = null;
107
    private boolean isSVG = false;
108
    private StaticRenderer renderer = new StaticRenderer();
109
    private Element elt;
110
    private GVTBuilder gvtBuilder = new GVTBuilder();
111
    private GraphicsNode gvtRoot = null;
112
    private BridgeContext ctx;
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) throws ReadException {
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)|| w!=0 || h!=0) {
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
                       try {
150
                        AffineTransform xform = AffineTransform.getScaleInstance(scalex,
151
                                scaley);
152
                        AffineTransform xpos = AffineTransform.getTranslateInstance(x,
153
                                y);
154
                        xpos.concatenate(xform);
155
                        g.drawRenderedImage(m_image, xpos);
156
                       }catch (ImagingOpException e) {
157
                               NotificationManager.addError("Dibujando FFramePicture", e);
158
                       }
159
                    } else if (isSVG) {
160
                        try {
161
                            if (r != null) {
162
                                drawSVG(g, r, rv);
163
                            }
164
                        } catch (OutOfMemoryError e) {
165
                                 NotificationManager.addError("Dibujando SVG FFramePicture", e);
166
                        } catch (IllegalArgumentException e) {
167
                                 NotificationManager.addError("Dibujando SVG FFramePicture", e);
168
                        }
169
                    }
170
                    System.gc();
171
                } else {
172
                    drawDraft(g);
173
                }
174
            }
175
        }
176

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

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

    
192
            ataux.translate(rect.getX(), rect.getY());
193

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

    
204
            ataux.translate(rect.getX(), rect.getY());
205
            ataux.concatenate(ViewBox.getViewTransform(null, elt,
206
                    (float) rect.getWidth(), (float) rect.getHeight(), ctx));
207

    
208
            gvtRoot.setTransform(ataux);
209
        }
210

    
211
        RenderingHints renderingHints = defaultRenderingHints;
212
        g.setRenderingHints(renderingHints);
213

    
214
        if (gvtRoot != null) {
215
            gvtRoot.paint(g);
216
        }
217
    }
218

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

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

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

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

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

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

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

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

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

    
303
        return xml;
304
    }
305

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

    
316
        if (isSVG) {
317
            return new Dimension(100, 100);
318
        }
319

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

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

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

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

    
361
        if (!isSVG && (tmpIcon != null)) {
362
            Image image = tmpIcon.getImage();
363

    
364

    
365
            BufferedImage bi = new BufferedImage(image.getWidth(null),
366
                    image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
367
            Graphics2D biContext = bi.createGraphics();
368
            biContext.drawImage(image, 0, 0, null);
369

    
370
            setImage(bi);
371

    
372
            return image;
373
        }
374

    
375
        return null;
376
    }
377

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

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

    
411
        this.m_path = xml.getStringProperty("m_path");
412

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

    
419
        this.m_quality = xml.getIntProperty("m_quality");
420
        this.m_viewing = xml.getIntProperty("m_viewing");
421
    }
422

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

    
435
        this.m_path = xml.getStringProperty("m_path");
436

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

    
443
        this.m_quality = xml.getIntProperty("m_quality");
444
        this.m_viewing = xml.getIntProperty("m_viewing");
445
        setRotation(xml.getDoubleProperty("m_rotation"));
446
    }
447

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

    
455

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

    
459
    }
460

    
461
    public void cloneActions(IFFrame frame) {
462
       m_image=null;
463

    
464
    }
465

    
466
        public IFFrameDialog getPropertyDialog() {
467
                return new FFramePictureDialog(getLayout(), this);
468
        }
469

    
470
        public void print(Graphics2D g, AffineTransform at, Geometry geom, PrintRequestAttributeSet properties) throws ReadException {
471
                draw(g, at, null, null);
472
        }
473
}