001    package net.sourceforge.mp3dings.editors;
002    import java.awt.BorderLayout;
003    import java.awt.Component;
004    import java.awt.Container;
005    import java.awt.Dialog;
006    import java.awt.Dimension;
007    import java.awt.FlowLayout;
008    import java.awt.Frame;
009    import java.awt.GridBagConstraints;
010    import java.awt.GridBagLayout;
011    import java.awt.Insets;
012    import java.awt.Window;
013    import java.awt.event.ActionEvent;
014    import java.awt.event.ActionListener;
015    import java.awt.event.MouseAdapter;
016    import java.awt.event.MouseEvent;
017    import java.io.ByteArrayInputStream;
018    import java.io.File;
019    import java.io.FileInputStream;
020    import java.io.FileOutputStream;
021    import java.io.IOException;
022    import java.io.InputStream;
023    import java.net.MalformedURLException;
024    import java.net.URL;
025    import java.nio.ByteBuffer;
026    import java.nio.channels.FileChannel;
027    import java.util.ArrayList;
028    import java.util.HashMap;
029    import java.util.Iterator;
030    import java.util.List;
031    import java.util.Arrays;
032    import java.util.Comparator;
033    import java.util.Map;
034    import java.util.logging.Logger;
035    import javax.swing.JOptionPane;
036    import javax.swing.JFileChooser;
037    import javax.swing.JTextField;
038    import javax.swing.AbstractAction;
039    import javax.swing.JList;
040    import javax.swing.ListCellRenderer;
041    import javax.swing.JPopupMenu;
042    import javax.swing.Action;
043    import javax.swing.JDialog;
044    import javax.swing.JButton;
045    import javax.swing.JComboBox;
046    import javax.swing.JPanel;
047    import javax.swing.SwingUtilities;
048    import javax.swing.JLabel;
049    import javax.swing.JComponent;
050    import javax.swing.UIManager;
051    import javax.swing.filechooser.FileFilter;
052    import javax.swing.text.AttributeSet;
053    import javax.swing.text.BadLocationException;
054    import javax.swing.text.PlainDocument;
055    import de.mospace.swing.ExtensionFileFilter;
056    import de.mospace.swing.PathInput;
057    import helliker.id3.APICImage;
058    import net.sourceforge.mp3dings.Globals;
059    import net.sourceforge.mp3dings.editors.imageeditor.*;
060    import net.sourceforge.mp3dings.utils.MimeTypeManager;
061    import helliker.id3.APICImage.PictureType;
062    
063    /*
064       Copyright (C) 2007 Moritz Ringler
065       This library is free software; you can redistribute it and/or
066       modify it under the terms of the GNU Lesser General Public
067       License as published by the Free Software Foundation; either
068       version 2.1 of the License, or (at your option) any later version.
069       This library is distributed in the hope that it will be useful,
070       but WITHOUT ANY WARRANTY; without even the implied warranty of
071       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
072       Lesser General Public License for more details.
073       You should have received a copy of the GNU Lesser General Public
074       License along with this library; if not, write to the Free Software
075       Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
076      */
077    
078    public class APICImageEditor{
079        private static final Logger logger = Logger.getLogger(APICImageEditor.class.getPackage().getName());
080        private final static MimeTypeManager mtm = MimeTypeManager.getDefault();
081        /** Maximum display size for images */
082        public static final int IMAGE_MAX_DIMENSION = 300;
083    
084        public static final int DESCRIPTION_MAX_LENGTH = 64;
085        /** Action command string for notifications of image (size) changes */
086        public static final String ACTION_IMAGE_CHANGED = "ImageChanged";
087        private static transient String lastSavePath = "";
088    
089        private final PathInput urlOrPath = new PathInput("", "*.png *.jpg *.jpeg");
090        //A JTextField with at most 64 characters
091        private final JTextField description = new JTextField(
092            new PlainDocument(){
093                public void insertString(int offset, String str, AttributeSet a)
094                        throws BadLocationException {
095                    if (getLength() + str.length() <= DESCRIPTION_MAX_LENGTH) {
096                        super.insertString(offset, str, a);
097                    } else {
098                        super.insertString(offset,
099                            str.substring(0, DESCRIPTION_MAX_LENGTH - getLength()),
100                            a);
101                    }
102                }
103            }, "", 20);
104        private final JComboBox pictureType;
105        private byte[] data;
106        private File file;
107        private String mimeType;
108        private Container ui = new JPanel();
109        private final Container imageContainer = new JPanel(new BorderLayout());
110        private ImageComponent imageComponent;
111        private final ImageComponent noRenderer = asImageComponent(
112            new JLabel(Globals.getString("IMAGE_CANNOT_DISPLAY"), JLabel.CENTER)
113        );
114        private final ImageComponent noImage = asImageComponent(
115            new JLabel(Globals.getString("IMAGE_NO_IMAGE"), JLabel.CENTER)
116        );
117        private final ImageComponent ioError = asImageComponent(
118            new JLabel(Globals.getString("IMAGE_IOERROR"), JLabel.CENTER)
119        );
120        private Map renderers = new HashMap();
121    
122        private final ActionListener loadListener = new ActionListener(){
123            public void actionPerformed(ActionEvent e){
124                fireActionPerformed(e);
125            }
126        };
127    
128        private final MouseAdapter saveListener = new MouseAdapter(){
129            public void mousePressed(MouseEvent e){
130                maybeShowPopup(e);
131            }
132    
133            public void mouseReleased(MouseEvent e){
134                maybeShowPopup(e);
135            }
136    
137            private void maybeShowPopup(MouseEvent e){
138                if(e.isPopupTrigger()){
139                    JPopupMenu popup = new JPopupMenu();
140                    popup.add(saveAction);
141                    popup.show((Component) e.getSource(), e.getX(), e.getY());
142                }
143            }
144        };
145    
146        private final Action saveAction = new AbstractAction(Globals.getString("SAVE")){
147            public void actionPerformed(ActionEvent e){
148                save();
149            }
150        };
151    
152        private static String getMimeType(String extension){
153            String mime = mtm.getMimeType(extension);
154            return (mime == null)? APICImage.MIME_TYPE_GENERIC : mime;
155        }
156    
157        public static void registerExtension(String extension, String mimetype){
158            mtm.registerExtension(extension, mimetype);
159        }
160    
161        private static class ModelFilter extends FileFilter{
162            private final String extension;
163    
164            public ModelFilter(String model){
165                extension = MimeTypeManager.getExtension(model);
166            }
167    
168            public boolean accept(File f){
169                return (extension == null)|| f.isDirectory() || f.getName().endsWith(extension);
170            }
171    
172            public String getDescription(){
173                return (extension == null)? "*" : "*" + extension;
174            }
175        }
176    
177        private List listeners = new ArrayList();
178    
179        public APICImageEditor(){
180            this(null);
181        }
182    
183        public APICImageEditor(APICImage pic){
184            Object[] picTypes = PictureType.values();
185            /*Arrays.sort(picTypes, new Comparator(){
186                    public int compare(Object o1, Object o2){
187                        return localizedName((PictureType) o1).compareTo(
188                               localizedName((PictureType) o2));
189                    }
190            });*/
191            pictureType = new JComboBox(picTypes);
192            final ListCellRenderer defaultRenderer = pictureType.getRenderer();
193            pictureType.setRenderer(new ListCellRenderer(){
194                    public Component getListCellRendererComponent(JList list,
195                                                  Object value,
196                                                  int index,
197                                                  boolean isSelected,
198                                                  boolean cellHasFocus){
199                        return defaultRenderer.getListCellRendererComponent(list,
200                            localizedName((PictureType) value), index, isSelected,
201                            cellHasFocus);
202                    }
203            });
204            loadImage(pic);
205            installListeners();
206            initUI();
207        }
208    
209        public void setImage(APICImage pic){
210            loadImage(pic);
211        }
212    
213        private static String localizedName(PictureType type){
214            return Globals.getString("APIC_TYPE_"+type.toString());
215        }
216    
217        private void loadImage(APICImage pic){
218            if(pic == null){
219                urlOrPath.getTextfield().setText("");
220                data = null;
221                mimeType = "image/";
222                file = null;
223            } else {
224                URL url = pic.getURL();
225                if(url == null){
226                    urlOrPath.getTextfield().setText("");
227                    data = pic.getImageData();
228                    mimeType = pic.getMimeType();
229                } else {
230                    urlOrPath.getTextfield().setText(url.toString());
231                // mime type will be determined by loadImage
232                }
233                description.setText(pic.getDescription());
234                pictureType.setSelectedItem(pic.getType());
235            }
236            loadImage();
237        }
238    
239        private void installListeners(){
240            urlOrPath.addActionListener(new ActionListener(){
241                public void actionPerformed(ActionEvent e){
242                    loadImage();
243                }
244            });
245        }
246    
247        private void initUI(){
248            urlOrPath.getTextfield().setToolTipText(Globals.getString("PATH_INPUT_TT"));
249            pictureType.setEditable(false);
250            ui.setLayout(new GridBagLayout());
251            ((JComponent) imageContainer).setTransferHandler(urlOrPath.getTextfield().getTransferHandler());
252    
253            GridBagConstraints gbc = new GridBagConstraints();
254            Insets ins2 = new Insets(2,0,0,0);
255            gbc.anchor = GridBagConstraints.WEST;
256            gbc.fill = GridBagConstraints.NONE;
257            gbc.gridheight = 1;
258            gbc.gridwidth = 2;
259            gbc.gridx = 0;
260            gbc.gridy = 0;
261            gbc.weightx = 1;
262            gbc.insets = ins2;
263            ui.add(new JLabel(Globals.getString("IMAGE_URL_OR_PATH")), gbc);
264    
265            gbc.gridy++;
266            gbc.fill = GridBagConstraints.BOTH;
267            ui.add(urlOrPath, gbc);
268    
269            gbc.gridy++;
270            gbc.insets = new Insets(10,0,10,0);
271            gbc.anchor = GridBagConstraints.CENTER;
272            gbc.fill = GridBagConstraints.BOTH;
273            gbc.weighty = 1;
274            ui.add(imageContainer, gbc);
275    
276            gbc.gridy++;
277            gbc.anchor = GridBagConstraints.WEST;
278            gbc.gridwidth = 1;
279            gbc.weighty = 0;
280            gbc.weightx = 0;
281            gbc.insets = new Insets(2,0,2,4);
282            gbc.gridx = 0;
283            ui.add(new JLabel(Globals.getString("IMAGE_TYPE")), gbc);
284            gbc.gridx++;
285            gbc.weightx = 1;
286            ui.add(pictureType, gbc);
287    
288            gbc.gridx = 0;
289            gbc.gridy++;
290            gbc.insets = ins2;
291            gbc.gridwidth = 2;
292            ui.add(new JLabel(Globals.getString("IMAGE_DESCRIPTION")), gbc);
293    
294            gbc.gridy++;
295            gbc.fill = GridBagConstraints.BOTH;
296            ui.add(description, gbc);
297        }
298    
299        private void loadImage(){
300            String address = urlOrPath.getPath();
301            if(address.length() > 0){
302                //URL or file
303                mimeType = getMimeType(MimeTypeManager.getExtension(address));
304                data = null;
305                final File f = new File(address);
306                file = (f.isFile())? f : null;
307            } else if(data == null) {
308                //no data
309                setImageComponent(noImage);
310                pictureType.setEnabled(false);
311                description.setEnabled(false);
312                return;
313            } else {
314                //data
315                file = null;
316            }
317            pictureType.setEnabled(true);
318            description.setEnabled(true);
319            ImageRenderer renderer = getRenderer(mimeType);
320            if(renderer == null){
321                renderer = getRenderer(APICImage.MIME_TYPE_GENERIC);
322            }
323            ImageComponent cimg = noRenderer;
324            try{
325                if(renderer != null){
326                    cimg = renderer.getImageComponent(mimeType, data, file, urlOrPath.getPath());
327                    if(cimg == null){
328                        cimg = noRenderer;
329                    }
330                }
331            } catch (IOException iox){
332                logger.warning(iox.toString());
333                cimg = ioError;
334            }
335            setImageComponent(cimg);
336        }
337    
338        public static ImageComponent asImageComponent(Component c){
339            return new SynchronousImageComponent(c);
340        }
341    
342        private void setImageComponent(ImageComponent cimg){
343            //uninstall
344            imageContainer.removeAll();
345            if(imageComponent != null){
346                imageComponent.removeActionListener(loadListener);
347                Component comp = imageComponent.getComponent();
348                comp.removeMouseListener(saveListener);
349            }
350            //install
351            imageComponent = cimg;
352            Component comp = imageComponent.getComponent();
353            imageContainer.add(comp, BorderLayout.CENTER);
354            if(cimg != noImage){
355                comp.addMouseListener(saveListener);
356            }
357            if(cimg.loadsAsynchronously()){
358                imageComponent.addActionListener(loadListener);
359            }
360            fireActionPerformed(ACTION_IMAGE_CHANGED);
361        }
362    
363        private void save(){
364            if(imageComponent == noImage){
365                return;
366            }
367            JFileChooser chooser = new JFileChooser(lastSavePath);
368            if(data != null){
369                String[] extensions = mtm.getExtensions(mimeType);
370                chooser.setFileFilter(new ExtensionFileFilter(
371                    (extensions.length == 0)? mimeType : null, extensions
372                ));
373            } else {
374                chooser.setFileFilter(new ModelFilter(urlOrPath.getPath()));
375            }
376            chooser.setDialogTitle(Globals.getString("IMAGE_SAVE_IMAGE"));
377            chooser.setMultiSelectionEnabled(false);
378            int status = chooser.showSaveDialog(ui);
379            if(status == JFileChooser.APPROVE_OPTION && chooser.getSelectedFile() != null){
380                try{
381                    saveImage(chooser.getSelectedFile());
382                } catch (Exception ex){
383                    JOptionPane.showMessageDialog(ui, ex,
384                            Globals.getString("SAVE_IMAGES_ERR"),
385                            JOptionPane.WARNING_MESSAGE);
386                }
387            }
388        }
389    
390        public static void saveImage(InputStream source, File ftarget) throws IOException{
391            FileOutputStream target = new FileOutputStream(ftarget);
392            try{
393                byte[] buff = new byte[0x4000];
394                int read = source.read(buff);
395                while(read != -1){
396                    target.write(buff, 0, read);
397                    read = source.read(buff);
398                }
399            } finally {
400                target.close();
401            }
402        }
403    
404        public void saveImage(File ftarget) throws IOException, MalformedURLException{
405            InputStream source = null;
406            try{
407                if(data != null){
408                    source = new ByteArrayInputStream(data);
409                } else if(file != null){
410                    if(file.equals(ftarget)){
411                        return;
412                    } else {
413                        try{
414                            if(file.getCanonicalPath().equals(ftarget.getCanonicalPath())){
415                                return;
416                            }
417                        } catch (IOException iox){
418                        }
419                    }
420                    source = new FileInputStream(file);
421                } else {
422                    source = new URL(urlOrPath.getPath()).openStream();
423                }
424                saveImage(source, ftarget);
425            } finally {
426                if(source != null){
427                    source.close();
428                }
429            }
430        }
431    
432        public APICImage getImage() throws MalformedURLException, IOException{
433            APICImage result = null;
434            if(data == null){
435                loadImage();
436            }
437            if(data != null){
438                result = new APICImage(mimeType, data);
439            } else if(file != null){
440                long len = file.length();
441                if(len > Integer.MAX_VALUE){
442                    throw new IOException("File too large.");
443                }
444                int ilen = (int) len;
445                ByteBuffer bb = ByteBuffer.allocate(ilen);
446                FileChannel fc = new FileInputStream(file).getChannel();
447                try{
448                    while(fc.read(bb) != -1 && bb.hasRemaining());
449                } finally {
450                    fc.close();
451                }
452                result = new APICImage(mimeType, bb.array());
453            } else if(urlOrPath.getPath().length() > 0){
454                result = new APICImage(new URL(urlOrPath.getPath()));
455            } else {
456                return null;
457            }
458            result.setType((PictureType) pictureType.getSelectedItem());
459            String descr = description.getText();
460            if(descr.length() > 64){
461                descr = descr.substring(0, 64);
462            }
463            result.setDescription(descr);
464            return result;
465        }
466    
467        public Component getUI(){
468            return ui;
469        }
470    
471        public void addActionListener(ActionListener al){
472            listeners.add(al);
473        }
474    
475        public void removeActionListener(ActionListener al){
476            listeners.remove(al);
477        }
478    
479        public void setRenderer(String mimetype, ImageRenderer renderer){
480            renderers.put(mimetype, renderer);
481            if(imageComponent == noRenderer){
482                loadImage();
483            }
484        }
485    
486        public void setDefaultRenderer(ImageRenderer renderer){
487            setRenderer(APICImage.MIME_TYPE_GENERIC, renderer);
488        }
489    
490        public void addRenderer(ImageRenderer renderer){
491            String[] types = renderer.getSupportedMimeTypes();
492            for(int i=0; i<types.length; i++){
493                renderers.put(types[i], renderer);
494            }
495            if(imageComponent == noRenderer){
496                loadImage();
497            }
498        }
499    
500        public ImageRenderer getRenderer(String mimetype){
501            return (ImageRenderer) renderers.get(mimetype);
502        }
503    
504        protected void fireActionPerformed(ActionEvent e){
505            Iterator it = listeners.iterator();
506            while(it.hasNext()){
507                ((ActionListener) it.next()).actionPerformed(e);
508            }
509        }
510    
511        protected void fireActionPerformed(String actionCommand){
512            ActionEvent e = new ActionEvent(this, ActionEvent.RESERVED_ID_MAX + 1, actionCommand);
513            fireActionPerformed(e);
514        }
515    
516        public static APICImageEditor getDefault(){
517            ImageRenderer svg = new SVGRenderer(IMAGE_MAX_DIMENSION);
518            ImageRenderer iir = new ImageIconRenderer(IMAGE_MAX_DIMENSION);
519            ImageRenderer jai = new JAIRenderer(IMAGE_MAX_DIMENSION);
520            final APICImageEditor editor = new APICImageEditor();
521            editor.addRenderer(jai);
522            editor.addRenderer(iir);
523            editor.setDefaultRenderer(jai);
524            editor.addRenderer(svg);
525            return editor;
526        }
527    
528        public static class EditorDialog extends JDialog{
529            public static String OK = "OK";
530            public static String CANCEL = "CANCEL";
531            private boolean okPressed = false;
532            private final APICImageEditor editor;
533            final JButton ok = new JButton(
534                    Globals.OK);
535            final JButton cancel = new JButton(
536                    Globals.CANCEL);
537    
538            public EditorDialog(Frame frame, APICImageEditor editor){
539                super(frame);
540                this.editor = (editor == null)? new APICImageEditor() : editor;
541                init();
542            }
543    
544            public EditorDialog(Dialog d, APICImageEditor editor){
545                super(d);
546                this.editor = (editor == null)? new APICImageEditor() : editor;
547                init();
548            }
549    
550            public EditorDialog(APICImageEditor editor){
551                super();
552                this.editor = (editor == null)? new APICImageEditor() : editor;
553                init();
554            }
555    
556            public void init(){
557                Container content = new JPanel(new BorderLayout());
558                ActionListener buttonListener = new ActionListener(){
559                    public void actionPerformed(ActionEvent e) {
560                        if (e.getSource() == ok) {
561                            okPressed = true;
562                        }
563                        setVisible(false);
564                    }
565                };
566                editor.addActionListener(new ActionListener(){
567                    public void actionPerformed(ActionEvent e){
568                        if(ACTION_IMAGE_CHANGED.equals(e.getActionCommand())){
569                            pack();
570                        }
571                    }
572                });
573                ok.setActionCommand(OK);
574                cancel.setActionCommand(CANCEL);
575                ok.addActionListener(buttonListener);
576                cancel.addActionListener(buttonListener);
577                Container buttons = new JPanel(new FlowLayout(FlowLayout.CENTER));
578                buttons.add(ok);
579                buttons.add(cancel);
580                content.add(editor.getUI(), BorderLayout.CENTER);
581                content.add(buttons, BorderLayout.SOUTH);
582                setContentPane(content);
583            }
584    
585            public void pack(){
586                super.pack();
587                Dimension d = getSize();
588                if(d.height < 420){
589                    d.height = 420;
590                }
591                setSize(d);
592            }
593    
594            public void setVisible(boolean b){
595                if(b){
596                    okPressed = false;
597                }
598                super.setVisible(b);
599            }
600    
601            public void setImage(APICImage image){
602                editor.setImage(image);
603                pack();
604            }
605    
606            public APICImage getImage() throws MalformedURLException, IOException{
607                return editor.getImage();
608            }
609    
610            public boolean isOKPressed(){
611                return okPressed;
612            }
613    
614            public void reset(){
615                okPressed = false;
616                editor.setImage(null);
617            }
618    
619            public void addActionListener(ActionListener al){
620                ok.addActionListener(al);
621                cancel.addActionListener(al);
622            }
623    
624            public void removeActionListener(ActionListener al){
625                ok.removeActionListener(al);
626                cancel.removeActionListener(al);
627            }
628        }
629        public static EditorDialog getDialog(Component parent, String title, APICImageEditor editor){
630            EditorDialog dialog = null;
631            Window w = (parent == null)
632                ? null
633                : (parent instanceof Window)
634                    ? (Window) parent
635                    : SwingUtilities.getWindowAncestor(parent);
636            if(w instanceof Dialog){
637                dialog = new EditorDialog((Dialog) w, editor);
638            } else if(w instanceof Frame){
639                dialog = new EditorDialog((Frame) w, editor);
640            } else {
641                dialog = new EditorDialog(editor);
642            }
643            dialog.setTitle(title);
644            return dialog;
645        }
646    
647        private static class SynchronousImageComponent implements ImageComponent{
648            public final Component comp;
649    
650            public SynchronousImageComponent(Component c){
651                comp = c;
652            }
653    
654            public Component getComponent(){
655                return comp;
656            }
657    
658            public void addActionListener(ActionListener al){
659            }
660    
661            public void removeActionListener(ActionListener al){
662            }
663    
664            public ActionListener[] getActionListeners(){
665                return new ActionListener[0];
666            }
667    
668            public boolean loadsAsynchronously(){
669                return false;
670            }
671        }
672    
673    
674    }