Statistics
| Revision:

svn-gvsig-desktop / branches / v2_0_0_prep / applications / appgvSIG / src / org / gvsig / app / project / documents / layout / fframes / FFramePicture.java @ 33647

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 org.gvsig.app.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.swing.ImageIcon;
58

    
59
import com.sun.jimi.core.Jimi;
60

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

    
72
import org.gvsig.andami.PluginServices;
73
import org.gvsig.andami.messages.NotificationManager;
74
import org.gvsig.compat.print.PrintAttributes;
75
import org.gvsig.fmap.geom.Geometry;
76
import org.gvsig.tools.ToolsLocator;
77
import org.gvsig.tools.dynobject.DynStruct;
78
import org.gvsig.tools.persistence.PersistenceManager;
79
import org.gvsig.tools.persistence.PersistentState;
80
import org.gvsig.tools.persistence.exception.PersistenceException;
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
        public static final String PERSISTENCE_DEFINITION_NAME = "FFramePicture";
91
        
92
        private static final String PATH_FIELD = "path";
93
        private static final String QUALITY_FIELD = "quality";  
94
        private static final String VIEWING_FIELD = "viewing"; 
95
        
96
        protected static RenderingHints defaultRenderingHints;
97

    
98
    static {
99
        defaultRenderingHints = new RenderingHints(null);
100
        defaultRenderingHints.put(RenderingHints.KEY_ANTIALIASING,
101
            RenderingHints.VALUE_ANTIALIAS_ON);
102

    
103
        defaultRenderingHints.put(RenderingHints.KEY_INTERPOLATION,
104
            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
105
    }
106

    
107
    private static final int PRESENTACION = 0;
108
    private static final int ACTIVO = 1;
109
    private BufferedImage m_image = null;
110
    private int m_quality = PRESENTACION;
111
    private int m_viewing = ACTIVO;
112
    private String m_path = null;
113
    private boolean isSVG = false;
114
    private StaticRenderer renderer = new StaticRenderer();
115
    private Element elt;
116
    private GVTBuilder gvtBuilder = new GVTBuilder();
117
    private GraphicsNode gvtRoot = null;
118
    private BridgeContext ctx;
119

    
120
    /**
121
     * Creates a new FFramePicture object.
122
     */
123
    public FFramePicture() {
124
    }
125

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

    
142
        double x = r.getMinX();
143
        double y = r.getMinY();
144
        double w = r.getWidth();
145
        double h = r.getHeight();
146

    
147
        if (intersects(rv, r)|| w!=0 || h!=0) {
148
            if ((m_image == null) && !isSVG) { //Que no hay una imagen.
149
                drawEmpty(g);
150
            } else {
151
                if ((rv == null) || (getQuality() == PRESENTACION)) {
152
                    if (!isSVG) {
153
                        double scalex = w / m_image.getWidth(null);
154
                        double scaley = h / m_image.getHeight(null);
155
                       try {
156
                        AffineTransform xform = AffineTransform.getScaleInstance(scalex,
157
                                scaley);
158
                        AffineTransform xpos = AffineTransform.getTranslateInstance(x,
159
                                y);
160
                        xpos.concatenate(xform);
161
                        g.drawRenderedImage(m_image, xpos);
162
                       }catch (ImagingOpException e) {
163
                               NotificationManager.addError("Dibujando FFramePicture", e);
164
                       }
165
                    } else if (isSVG) {
166
                        try {
167
                            if (r != null) {
168
                                drawSVG(g, r, rv);
169
                            }
170
                        } catch (OutOfMemoryError e) {
171
                                 NotificationManager.addError("Dibujando SVG FFramePicture", e);
172
                        } catch (IllegalArgumentException e) {
173
                                 NotificationManager.addError("Dibujando SVG FFramePicture", e);
174
                        }
175
                    }
176
                    System.gc();
177
                } else {
178
                    drawDraft(g);
179
                }
180
            }
181
        }
182

    
183
        g.rotate(Math.toRadians(-getRotation()), r.x + (r.width / 2),
184
            r.y + (r.height / 2));
185
    }
186

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

    
198
            ataux.translate(rect.getX(), rect.getY());
199

    
200
            try {
201
                ataux.concatenate(ViewBox.getViewTransform(null, elt,
202
                        (float) rect.getWidth(), (float) rect.getHeight(), ctx));
203
                gvtRoot.setTransform(ataux);
204
            } catch (Exception e) {
205
                // TODO: handle exception
206
            }
207
        } else {
208
            AffineTransform ataux = new AffineTransform();
209

    
210
            ataux.translate(rect.getX(), rect.getY());
211
            ataux.concatenate(ViewBox.getViewTransform(null, elt,
212
                    (float) rect.getWidth(), (float) rect.getHeight(), ctx));
213

    
214
            gvtRoot.setTransform(ataux);
215
        }
216

    
217
        RenderingHints renderingHints = defaultRenderingHints;
218
        g.setRenderingHints(renderingHints);
219

    
220
        if (gvtRoot != null) {
221
            gvtRoot.paint(g);
222
        }
223
    }
224

    
225
    /**
226
     * Rellena la calidad seg?n el entero que se pasa como par?metro.
227
     *
228
     * @param q entero que representa el tipo de calidad elegido.
229
     */
230
    public void setQuality(int q) {
231
        m_quality = q;
232
    }
233

    
234
    /**
235
     * Devuelve la calidad que est? seleccionada.
236
     *
237
     * @return entero que representa la calidad seleccionada.
238
     */
239
    public int getQuality() {
240
        return m_quality;
241
    }
242

    
243
    /**
244
     * Devuelve un entero que representa la forma en que se actualiza la vista.
245
     *
246
     * @return forma que se actualiza la vista.
247
     */
248
    public int getViewing() {
249
        return m_viewing;
250
    }
251

    
252
    /**
253
     * Rellena la forma de actualizar la vista.
254
     *
255
     * @param v entero que representa la forma de actualizar la vista.
256
     */
257
    public void setViewing(int v) {
258
        m_viewing = v;
259
    }
260

    
261
    /**
262
     * Rellena el nombre de la imagen.
263
     *
264
     * @param path nombre de la imagen.
265
     */
266
    public void setPath(String path) {
267
        m_path = path;
268
    }
269

    
270
    /**
271
     * Devuelve la ruta del fichero.
272
     *
273
     * @return String
274
     */
275
    public String getPath() {
276
        return m_path;
277
    }
278

    
279
    /**
280
     * Rellena la imagen.
281
     *
282
     * @param image
283
     */
284
    public void setImage(BufferedImage image) {
285
        m_image = image;
286
    }
287

    
288
    /**
289
     * Devuelve la dimensi?n dela imagen.
290
     *
291
     * @param file Nombre del fichero donde se encuentra la imagen.
292
     *
293
     * @return DOCUMENT ME!
294
     */
295
    public Dimension getBound(String file) {
296
        Image img = load(file);
297

    
298
        if (isSVG) {
299
            return new Dimension(100, 100);
300
        }
301

    
302
        if (img == null) {
303
            return new Dimension((int) getBoundingBox(null).getWidth(),
304
                (int) getBoundingBox(null).getHeight());
305
        }
306

    
307
        return new Dimension(img.getWidth(null), img.getHeight(null));
308
    }
309

    
310
    /**
311
     * Carga el contnido del fichero.
312
     *
313
     * @param file Nombre del fichero a cargar.
314
     *
315
     * @return Imagen
316
     */
317
    public Image load(String file) {
318
        if (file==null) {
319
                        return null;
320
                }
321
            ImageIcon tmpIcon = null;
322
        File f=new File(file);
323
        if (file == null || !f.exists()) {
324
            return null;
325
        }
326
        setPath(file);
327
        String iString = file.toLowerCase();
328

    
329
        if (iString.endsWith("jpg") || iString.endsWith("jpeg") ||
330
                iString.endsWith("gif")) {
331
            tmpIcon = new ImageIcon(Jimi.getImage(file, Jimi.VIRTUAL_MEMORY)); //((File)main.allImages.elementAt(x)).getAbsolutePath());
332
        } else if (iString.endsWith("png") || iString.endsWith("tif") ||
333
                iString.endsWith("ico") || iString.endsWith("xpm") ||
334
                iString.endsWith("bmp")) {
335
            tmpIcon = new ImageIcon(Jimi.getImage(file, Jimi.VIRTUAL_MEMORY)); //new ImageIcon(f.getPath());
336
        } else if (iString.endsWith("svg")) {
337
            isSVG = true;
338
            obtainStaticRenderer(new File(file));
339
        }else {
340
                tmpIcon=new ImageIcon(file);
341
        }
342

    
343
        if (!isSVG && (tmpIcon != null)) {
344
            Image image = tmpIcon.getImage();
345

    
346
            if (image.getWidth(null)==-1 || image.getHeight(null)==-1){
347
                    NotificationManager.showMessageError(PluginServices.getText(this,"unsupported_format"), new Exception());
348
                    return null;
349
            }
350

    
351
            BufferedImage bi = new BufferedImage(image.getWidth(null),
352
                    image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
353
            Graphics2D biContext = bi.createGraphics();
354
            biContext.drawImage(image, 0, 0, null);
355

    
356
            setImage(bi);
357

    
358
            return image;
359
        }
360

    
361
        return null;
362
    }
363

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

    
384
    /**
385
     * @see org.gvsig.app.project.documents.layout.fframes.IFFrame#getNameFFrame()
386
     */
387
    public String getNameFFrame() {
388
        return PluginServices.getText(this, "imagen")+ num;
389
    }
390
    
391
    public String getName() {
392
        return PERSISTENCE_DEFINITION_NAME;
393
    }
394

    
395
    public void initialize() {
396
        // TODO Auto-generated method stub
397

    
398
    }
399

    
400
    public void cloneActions(IFFrame frame) {
401
       m_image=null;
402
    }
403

    
404
        public void print(Graphics2D g, AffineTransform at, Geometry geom,
405
                        PrintAttributes properties) {
406
                draw(g, at, null, null);
407
        }
408
        
409
        public static void registerPersistent() {
410
                PersistenceManager manager = ToolsLocator.getPersistenceManager();
411
                if( manager.getDefinition(PERSISTENCE_DEFINITION_NAME)==null ) {
412
                        DynStruct definition = manager.addDefinition(
413
                                        FFramePicture.class,
414
                                        PERSISTENCE_DEFINITION_NAME,
415
                                        "FFramePicture persistence definition",
416
                                        null, 
417
                                        null
418
                        ); 
419

    
420
                        definition.extend(manager.getDefinition(FFrame.PERSISTENCE_DEFINITION_NAME));        
421

    
422
                        definition.addDynFieldString(PATH_FIELD).setMandatory(true);        
423
                        definition.addDynFieldInt(QUALITY_FIELD).setMandatory(true);        
424
                        definition.addDynFieldInt(VIEWING_FIELD).setMandatory(true);        
425
                }
426
        }
427

    
428
        @Override
429
        public void loadFromState(PersistentState state)
430
        throws PersistenceException {
431
                super.loadFromState(state);
432
                m_path = state.getString(PATH_FIELD);
433
                m_quality = state.getInt(QUALITY_FIELD);  
434
                m_viewing = state.getInt(VIEWING_FIELD); 
435
        }
436

    
437
        @Override
438
        public void saveToState(PersistentState state) throws PersistenceException {
439
                super.saveToState(state);
440
                state.set(PATH_FIELD, m_path);
441
                state.set(QUALITY_FIELD, m_quality);  
442
                state.set(VIEWING_FIELD, m_viewing); 
443
        }
444
}