001    package net.sourceforge.mp3dings.editors.imageeditor;
002    import java.awt.Component;
003    import java.awt.Dimension;
004    import java.awt.geom.AffineTransform;
005    import java.awt.event.MouseAdapter;
006    import java.awt.event.MouseEvent;
007    import java.io.ByteArrayInputStream;
008    import java.io.File;
009    import java.io.IOException;
010    import java.lang.reflect.InvocationTargetException;
011    import java.lang.reflect.Method;
012    import java.util.Timer;
013    import java.util.TimerTask;
014    import java.util.logging.Logger;
015    import javax.swing.JComponent;
016    import javax.swing.JLabel;
017    import javax.swing.SwingUtilities;
018    import net.sourceforge.mp3dings.Globals;
019    import net.sourceforge.mp3dings.editors.APICImageEditor;
020    import de.mospace.lang.BrowserLauncher;
021    
022    /*
023    Copyright (C) 2007 Moritz Ringler
024    This library is free software; you can redistribute it and/or
025    modify it under the terms of the GNU Lesser General Public
026    License as published by the Free Software Foundation; either
027    version 2.1 of the License, or (at your option) any later version.
028    This library is distributed in the hope that it will be useful,
029    but WITHOUT ANY WARRANTY; without even the implied warranty of
030    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
031    Lesser General Public License for more details.
032    You should have received a copy of the GNU Lesser General Public
033    License along with this library; if not, write to the Free Software
034    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
035    */
036    
037    public class SVGRenderer implements ImageRenderer{
038        private static final Logger logger = Logger.getLogger(SVGRenderer.class.getPackage().getName());
039        public final static String MIME_TYPE_SVG = "image/svg+xml";
040        private Class cSvgCanvas;
041        private Method setRenderingTransform;
042        private Method setURI;
043        private Timer svgTimer;
044        private final int maxDimension;
045        private ImageComponent installBatik;
046    
047        public SVGRenderer(int maxDimension){
048            if(maxDimension < 1){
049                throw new IllegalArgumentException();
050            }
051            this.maxDimension = maxDimension;
052        }
053    
054        public boolean isMimeTypeSupported(String mime){
055            return MIME_TYPE_SVG.equals(mime);
056        }
057    
058        public String[] getSupportedMimeTypes(){
059            return new String[]{MIME_TYPE_SVG};
060        }
061    
062        private class SVGImage extends AbstractImageComponent {
063            private File svgTempFile;
064            //need a JComponent here to have setPreferredSize in 1.4
065            private final JComponent svgCanvas;
066    
067            public SVGImage(byte[] data, File f, String url) throws InvocationTargetException, IOException{
068                if(data != null){
069                    //Save to temp file
070                    svgTempFile = File.createTempFile("APICImageEditor", ".svg");
071                    APICImageEditor.saveImage(new ByteArrayInputStream(data), svgTempFile);
072                }
073                final File file = (svgTempFile == null)? f : svgTempFile;
074                final String uri = (file == null)? url : file.toURI().toString();
075                try{
076                    svgCanvas = (JComponent) cSvgCanvas.newInstance();
077                    setURI.invoke(svgCanvas, new Object[]{uri});
078                } catch (IllegalAccessException ex){
079                    throw new Error(ex);
080                }  catch (InstantiationException ex){
081                    throw new Error(ex);
082                }
083                scheduleSVGMonitor();
084            }
085    
086            public Component getComponent(){
087                return svgCanvas;
088            }
089    
090            /**
091            public void addMouseListener(MouseListener ml){
092                super.addMouseListener(ml);
093                svgCanvas.addMouseListener(ml);
094            }
095    
096            public void removeMouseListener(MouseListener ml){
097                super.removeMouseListener(ml);
098                svgCanvas.removeMouseListener(ml);
099            }
100            **/
101    
102            private void scheduleSVGMonitor(){
103                TimerTask svgTimerTask = new TimerTask(){
104                    Dimension svgDim = svgCanvas.getPreferredSize();
105                    public void run(){
106                        if(!svgCanvas.getPreferredSize().equals(svgDim)){
107                            cancel();
108                            imageLoaded();
109                        }
110                    }
111                };
112                svgTimer.schedule(svgTimerTask, 100, 300);
113            }
114    
115            private void imageLoaded(){
116                final Dimension d = svgCanvas.getPreferredSize();
117                int dim = Math.max(d.height, d.width);
118                if(dim > maxDimension){
119                    double scaling = 1.0f * maxDimension/dim;
120                    try{
121                        AffineTransform atx = AffineTransform.getScaleInstance(scaling, scaling);
122                        setRenderingTransform.invoke(svgCanvas, new Object[]{atx});
123                        d.height = (int) (scaling * d.height);
124                        d.width  = (int) (scaling * d.width);
125                        svgCanvas.setPreferredSize(d);
126                    } catch (Exception ex){
127                        logger.warning("Cannot resize SVG image.");
128                        logger.warning(ex.toString());
129                    }
130                }
131                SwingUtilities.invokeLater(
132                    new Runnable(){
133                        public void run(){
134                            fireActionImageChanged();
135                        }
136                    }
137                    );
138                if(svgTempFile != null && svgTempFile.isFile()){
139                    svgTempFile.delete();
140                }
141            }
142        }
143    
144        private void loadClassesAndMethods() throws ClassNotFoundException{
145            cSvgCanvas = Class.forName("org.apache.batik.swing.JSVGCanvas");
146            try{
147                setURI = cSvgCanvas.getMethod("setURI", new Class[]{String.class});
148                setRenderingTransform = cSvgCanvas.getMethod("setRenderingTransform", new Class[]{AffineTransform.class});
149                Class[] inner = cSvgCanvas.getDeclaredClasses();
150            } catch (NoSuchMethodException nsmx){
151                throw new Error(nsmx);
152            }
153        }
154    
155        public ImageComponent getImageComponent(String mimetype, byte[] imagedata, File f, String url) throws IOException{
156            ImageComponent result = null;
157            try{
158                synchronized(this){
159                    if(cSvgCanvas == null){
160                        loadClassesAndMethods();
161                        svgTimer = new Timer();
162                    }
163                }
164            } catch (ClassNotFoundException ex){
165                synchronized(this){
166                    if(installBatik == null){
167                        JLabel batik = new JLabel(Globals.getString("BATIK_MISSING_ERR"), JLabel.CENTER);
168                        batik.addMouseListener(new MouseAdapter(){
169                                public void mouseClicked(MouseEvent e){
170                                    if(e.getButton() == MouseEvent.BUTTON1 &&
171                                       e.getClickCount() == 1 &&
172                                       !e.isPopupTrigger()){
173                                    try{
174                                        BrowserLauncher.openURL("http://xmlgraphics.apache.org/batik/download.cgi");
175                                    } catch (IOException ex){
176                                        logger.warning(ex.toString());
177                                    }
178                                   }
179                                }
180                        });
181                        installBatik = APICImageEditor.asImageComponent(batik);
182                    }
183                }
184                result = installBatik;
185            }
186            if(result == null){
187                try{
188                    result = new SVGImage(imagedata, f, url);
189                } catch (InvocationTargetException itx){
190                    Throwable cause = itx.getCause();
191                    if(cause instanceof IOException){
192                        throw (IOException) cause;
193                    } else {
194                        logger.warning("Error construction SVG image.");
195                        logger.warning(((cause == null)? itx : cause).toString());
196                    }
197                }
198            }
199            return result;
200        }
201    
202    }