001    package net.sourceforge.mp3dings.utils;
002    
003    /*
004     *  Mp3dings - manage mp3 meta-information
005     *  Copyright (C) 2006 Moritz Ringler
006     *  $Id: BeanSetCustomizer.java,v 1.23 2006/11/23 17:35:21 ringler Exp $
007     *
008     *  This program is free software; you can redistribute it and/or
009     *  modify it under the terms of the GNU General Public License
010     *  as published by the Free Software Foundation; either version 2
011     *  of the License, or (at your option) any later version.
012     *
013     *  This program is distributed in the hope that it will be useful,
014     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
015     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
016     *  GNU General Public License for more details.
017     *
018     *  You should have received a copy of the GNU General Public License
019     *  along with this program; if not, write to the Free Software
020     *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
021     */
022    import java.awt.CardLayout;
023    import java.awt.Color;
024    import java.awt.Component;
025    import java.awt.Container;
026    import java.awt.Dimension;
027    import java.awt.GridBagConstraints;
028    import java.awt.GridBagLayout;
029    import java.awt.GridLayout;
030    import java.awt.Insets;
031    import java.awt.event.ActionEvent;
032    import java.awt.event.ActionListener;
033    import java.awt.event.WindowEvent;
034    import java.io.File;
035    import java.util.ArrayList;
036    import java.util.Arrays;
037    import java.util.Collection;
038    import java.util.HashMap;
039    import java.util.HashSet;
040    import java.util.Iterator;
041    import java.util.List;
042    import java.util.Map;
043    import java.util.logging.Level;
044    import java.util.logging.Logger;
045    import java.util.prefs.BackingStoreException;
046    import java.util.prefs.Preferences;
047    import javax.swing.BorderFactory;
048    import javax.swing.JButton;
049    import javax.swing.JComboBox;
050    import javax.swing.JComponent;
051    import javax.swing.JFileChooser;
052    import javax.swing.JFrame;
053    import javax.swing.JLabel;
054    import javax.swing.JOptionPane;
055    import javax.swing.JPanel;
056    import javax.swing.JScrollPane;
057    import javax.swing.ListSelectionModel;
058    import javax.swing.SwingUtilities;
059    import javax.swing.event.ListSelectionEvent;
060    import javax.swing.event.ListSelectionListener;
061    import net.sourceforge.mp3dings.Globals;
062    import net.sourceforge.mp3dings.MainFrame;
063    import net.sourceforge.mp3dings.PreferencesDialogue;
064    
065    /**
066     *  A Preference Module, a container for similar PrefPanels.
067     *
068     *@author     Moritz Ringler
069     *@version    $Revision: 1.23 $ ($Date: 2006/11/23 17:35:21 $)
070     */
071    public class BeanSetCustomizer extends JPanel {
072        private static final Logger logger = Logger.getLogger(BeanSetCustomizer.class.getPackage().getName());
073        /**  Description of the Field */
074        protected BeanSet beans;
075        private BeanList beanList;
076        private final static String EMPTY = "null";
077        private Map customizers = new HashMap();
078        private AbstractBeanCustomizer currentCustomizer;
079        private Container beanView;
080        //initialized by constructor
081        private Container controls;
082        //initialized by constructor
083        private MainFrame owner;
084        //lazily initialized by mainFrame();
085        /**  Description of the Field */
086        protected String name;
087        private String savePath = null;
088        //initialized by constructor
089    //{
090        // public void remove(Bean bean){
091        // super.remove(bean);
092        // if(model.getSize() <= 0){
093        // /* if no elements remain show an empty panel */
094        // showEmptyPanel();
095        // }
096        // }
097        //};
098        protected String prefnode = this.getClass().getName().replaceFirst(
099                "\\Q" + this.getClass().getPackage().getName() + ".\\E",
100                "").replaceFirst("Customizer$","");
101    
102        private static long lastID = 0l;
103    
104    
105        /**
106         *  Constructs a new BeanSetCustomizer.
107         *
108         *@param  name  Description of the Parameter
109         */
110        public BeanSetCustomizer(String name) {
111            beans = new BeanSet();
112            init(name);
113        }
114    
115    
116        /**
117         *  Constructs a new BeanSetCustomizer.
118         *
119         *@param  name   Description of the Parameter
120         *@param  beans  Description of the Parameter
121         */
122        public BeanSetCustomizer(String name, BeanSet beans) {
123            this.beans = beans;
124            init(name);
125        }
126    
127        /**
128         *  The main program for the BeanSetCustomizer class
129         *
130         *@param  argv           The command line arguments
131         *@exception  Exception  Description of the Exception
132         */
133        public static void main(String[] argv) throws Exception {
134            final BeanSetCustomizer bsc = new BeanSetCustomizer("test");
135            bsc.registerType(Bean.class);
136            JFrame frame =
137                new JFrame() {
138                    protected void processWindowEvent(WindowEvent e) {
139                        try {
140                            bsc.save();
141                        } catch (Exception ex) {
142                            ex.printStackTrace();
143                        }
144                        super.processWindowEvent(e);
145                        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
146                            System.exit(0);
147                        }
148                    }
149                };
150            frame.setContentPane(bsc);
151            frame.pack();
152            frame.setVisible(true);
153        }
154    
155    
156        /**
157         *  Description of the Method
158         *
159         *@param  name  Description of the Parameter
160         */
161        private void init(String name) {
162            this.name = name;
163            beanList = new BeanList(beans);
164    
165            setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
166            setBackground(new Color(-1184257));
167    
168            setLayout(new GridBagLayout());
169            GridBagConstraints gbc = new GridBagConstraints();
170    
171            gbc.fill = GridBagConstraints.BOTH;
172            gbc.gridx = 0;
173            gbc.gridy = 0;
174            gbc.gridwidth = 4;
175            gbc.gridheight = 1;
176            gbc.weightx = 1.0;
177            gbc.weighty = .0;
178            add(makeTitle(), gbc);
179    
180            gbc.gridx = 0;
181            gbc.gridy = 1;
182            gbc.gridwidth = 1;
183            gbc.gridheight = 1;
184            gbc.ipadx = 2;
185            gbc.weighty = 0.;
186            gbc.weightx = 0.7;
187            gbc.fill = GridBagConstraints.BOTH;
188            gbc.anchor = GridBagConstraints.CENTER;
189            gbc.insets = new Insets(5, 5, 5, 0);
190            JComboBox typeSelection = beanList.getTypeSelector();
191            add(typeSelection, gbc);
192    
193            gbc.gridy = 2;
194            gbc.insets = new Insets(0, 5, 5, 5);
195            JComponent jc = new JScrollPane(beanList);
196            jc.setPreferredSize(new Dimension(150, 150));
197            add(jc, gbc);
198    
199            gbc.gridx = 1;
200            gbc.gridy = 1;
201            gbc.gridheight = 2;
202            gbc.weighty = 0.;
203            gbc.weightx = 1.0;
204            gbc.insets = new Insets(5, 5, 5, 5);
205            gbc.fill = GridBagConstraints.NONE;
206            add(getControls(), gbc);
207    
208            gbc.gridx = 0;
209            gbc.gridy = 3;
210            gbc.gridwidth = 2;
211            gbc.gridheight = 1;
212            gbc.weightx = 1.0;
213            gbc.weighty = 1.;
214            gbc.fill = GridBagConstraints.BOTH;
215    
216            beanView = new JPanel(new CardLayout());
217            ((JPanel) beanView).setBorder(
218                    BorderFactory.createMatteBorder(5, 5, 5, 5, ((JPanel) beanView).getBackground()));
219    
220            JPanel empty = new JPanel();
221            //empty.setPreferredSize(new Dimension(300,300));
222            beanView.add(empty, EMPTY);
223            add(beanView, gbc);
224    
225            beanList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
226            beanList.addListSelectionListener(
227                new ListSelectionListener() {
228                    public void valueChanged(ListSelectionEvent e) {
229                        if (beanList.getSelectedValue() == null) {
230                            showEmptyPanel();
231                        } else{
232                            loadCustomizer((Bean) beanList.getSelectedValue());
233                        }
234                    }
235                });
236        }
237    
238        private Bean getFirstInvalidBean(){
239            Iterator it = beans.iterator();
240            Bean result = null;
241            while(it.hasNext()){
242                result = (Bean) it.next();
243                if(result.isSavable()){
244                    result = null;
245                } else {
246                    break;
247                }
248            }
249            return result;
250        }
251    
252        protected void showFirstInvalidBean(){
253            beanList.setSelectedValue(getFirstInvalidBean(), true);
254            //loadCustomizer(getFirstInvalidBean());
255        }
256    
257        public boolean isSavable(){
258            return (getFirstInvalidBean() == null);
259        }
260    
261        private Bean currentBean(){
262           return (currentCustomizer == null)? null : currentCustomizer.getModel();
263        }
264    
265        protected boolean currentBeanIsValid(){
266            Bean b = currentBean();
267            return (b == null) || b.isSavable();
268        }
269    
270    
271        /**  Description of the Method */
272        private void showEmptyPanel() {
273            CardLayout layout = (CardLayout) beanView.getLayout();
274            layout.show(beanView, EMPTY);
275        }
276    
277    
278        /**
279         *  Description of the Method
280         *
281         *@param  bean     Description of the Parameter
282         *@param  newName  Description of the Parameter
283         *@return          Description of the Return Value
284         */
285        public boolean renameBean(Bean bean, String newName) {
286            return beans.renameBean(bean, newName);
287        }
288    
289    
290        /**
291         *  Description of the Method
292         *
293         *@param  beanClass  Description of the Parameter
294         */
295        public void registerType(Class beanClass) {
296            beanList.registerType(beanClass);
297        }
298    
299    
300        /**
301         *  Description of the Method
302         *
303         *@param  bean  Description of the Parameter
304         */
305        private void loadCustomizer(Bean bean) {
306            if (bean == null) {
307                return;
308            }
309            Class beanClass = bean.getClass();
310            AbstractBeanCustomizer customizer = (AbstractBeanCustomizer) customizers.get(beanClass);
311            CardLayout layout = (CardLayout) beanView.getLayout();
312            if (customizer == null) {
313                try {
314                    Class customizerClass = getCustomizerClass(beanClass);
315                    customizer = (AbstractBeanCustomizer) customizerClass.newInstance();
316                } catch (Exception ex) {
317                    logger.severe("Cannot create customizer for class :" + beanClass.getName());
318                    Globals.logStackTrace(logger, Level.SEVERE, ex);
319                }
320    
321                customizers.put(beanClass, customizer);
322                beanView.add(customizer.getUI(), beanClass.getName());
323            }
324            customizer.setModel(bean);
325            currentCustomizer = customizer;
326            layout.show(beanView, beanClass.getName());
327        }
328    
329    
330        /**
331         *  Gets the name attribute of the BeanSetCustomizer object
332         *
333         *@return    The name value
334         */
335        public String getName() {
336            return name;
337        }
338    
339    
340        /**
341         *  Adds a bean to this Customizer's BeanSet if it does not
342         *  contain a bean with the same name yet. The client must take care
343         *  that the bean has a valid id.
344         *
345         *@param  bean  The bean to add to the BeanSet
346         *@return <code>true</code> if the bean has indeed been added to the BeanSet
347         *
348         *@see Bean#setId
349         *@see #getNewID
350         */
351        public boolean addBean(Bean bean) {
352            // no check is necessary here: the BeanSets Comparator uses
353            // getName(), therefore only beans whose getName methods returns
354            // a result different from the names of all beans already in the
355            // set will be added
356            return beans.add(bean);
357        }
358    
359    
360        /**
361         *  Gets the beanForName attribute of the BeanSetCustomizer object
362         *
363         *@param  name  Description of the Parameter
364         *@return       The beanForName value
365         */
366        public Bean getBeanForName(String name) {
367            return beans.getBeanForName(name);
368        }
369    
370    
371        /**
372         *  Adds those beans to this Customizer's BeanSet whose names are not
373         *  represented in this BeanSet yet. The client must take care
374         *  that the beans all have valid ids. No type-checking is done
375         *  by the BeanSet, the client must assure that the Collection contains
376         *  only Beans.
377         *
378         *@param  c  The beans to add to the BeanSet
379         *@return <code>true</code> if the BeanSet has changed as a
380         *        result of this operation
381         *
382         *@see BeanSet#addAll
383         *@see Bean#setId
384         *@see #getNewID
385         */
386        public boolean addAllBeans(Collection c) {
387            // no check is necessary here: the BeanSets Comparator uses
388            // getName(), therefore only beans whose getName methods returns
389            // a result different from the names of all beans already in the
390            // set will be added
391            return beans.addAll(c);
392        }
393    
394    
395    
396        public void setSavePath(String s){
397            savePath = s;
398        }
399    
400        public String getSavePath(){
401            return savePath;
402        }
403    
404        /**
405         *  Description of the Method
406         *
407         *@exception  BackingStoreException  Description of the Exception
408         */
409        public void save() throws BackingStoreException {
410            Preferences p = Globals.getPrefNode().node(prefnode);
411            Bean b;
412    
413            Collection newKeys = new HashSet();
414    
415            /*
416             *  fill in missing ids, at this point p must still exist
417             */
418            Iterator it = beans.iterator();
419            while (it.hasNext()) {
420                b = (Bean) it.next();
421                if(!b.isSavable()){
422                    continue;
423                }
424                //the following section should no longer be necessary
425                //since we now assign valid IDs in getNewBean()
426                if (b.getId() == Bean.NO_ID) {
427                    b.setId(getNewID(p));
428                    //System.out.println("newBeanId for "+ b.getName() + ": " + Long.toString(b.getId(), 16));
429                }
430                newKeys.add(Long.toString(b.getId(), 16));
431            }
432    
433    
434            /*
435             *  delete pref entries of deleted beans
436             */
437            Collection keysToRemove = new ArrayList();
438            keysToRemove.addAll(Arrays.asList(p.keys()));
439            keysToRemove.removeAll(newKeys);
440            it = keysToRemove.iterator();
441            while (it.hasNext()) {
442                p.remove((String) it.next());
443            }
444    
445            /*
446             *  save the beans
447             */
448            it = beans.iterator();
449            while (it.hasNext()) {
450                b = (Bean) it.next();
451                if(b.isSavable()){
452                    b.save(p, Long.toString(b.getId(), 16), getSavePath());
453                }
454            }
455        }
456    
457    
458        /**
459         *  Description of the Method
460         *
461         *@param  beanClass                  Description of the Parameter
462         *@exception  BackingStoreException  Description of the Exception
463         */
464        public void load(Class beanClass) throws BackingStoreException {
465            Preferences p = Globals.getPrefNode().node(prefnode);
466            String[] keys = p.keys();
467            Bean b = null;
468            for (int i = 0; i < keys.length; i++) {
469                try {
470                    b = Bean.load(p, keys[i]);
471                } catch (Exception ex) {
472                    logger.severe("Could not load bean at " + p.toString() +
473                            "/" + keys[i]);
474                    Globals.logStackTrace(logger, Level.SEVERE, ex);
475                }
476                if (b != null && beanClass.isInstance(b)) {
477                    addBean(b);
478                } else if(b == null){
479                    logger.severe("Could not load bean at " + p.toString() +
480                            "/" + keys[i]);
481                }
482                b = null;
483            }
484        }
485    
486    
487        /**
488         *  Gets the newID attribute of the BeanSetCustomizer class
489         *
490         *@param  pref  Description of the Parameter
491         *@return       The newID value
492         */
493        public static long getNewID(Preferences pref) {
494            long id;
495            for (id = lastID + 1; pref.get(Long.toString(id, 16), null) != null; id++);
496            lastID = id;
497            return id;
498        }
499    
500    
501        /**
502         *  Description of the Method
503         *
504         *@return    Description of the Return Value
505         */
506        private JComponent makeTitle() {
507            JLabel title = new JLabel(name);
508            title.setOpaque(true);
509            title.setBackground(Color.blue);
510            title.setFont(Globals.SANS_BOLD_12);
511            title.setForeground(Color.white);
512            title.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.blue));
513            return title;
514        }
515    
516    
517        /**
518         *  Gets the beans attribute of the BeanSetCustomizer object
519         *
520         *@return    The beans value
521         */
522        public BeanSet getBeans() {
523            return beans;
524        }
525    
526    
527        /**
528         *  This method must return a Container to which other Components can be
529         *  added.
530         *
531         *@return    The controls value
532         */
533        public Component getControls() {
534            if (controls == null) {
535                controls = new JPanel(new GridLayout(0, 2, 2, 2));
536                ((JPanel) controls).setOpaque(false);
537    
538                /*
539                 *  new Bean button
540                 */
541                JButton button =
542                        new JButton(Globals.getString("NEW"));
543                button.addActionListener(
544                    new ActionListener() {
545                        public void actionPerformed(ActionEvent e) {
546                            Bean b = getNewBean();
547                            if (b == null) {
548                                logger.severe("Cannot create new bean.");
549                            } else {
550                                if (!addBean(b)) {
551                                    logger.severe("Bean with the name " +
552                                            b.getName() + " was not added.");
553                                }
554                            }
555                        }
556                    });
557                controls.add(button);
558    
559                /*
560                 *  import bean button
561                 */
562                button =
563                        new JButton(Globals.getString("IMPORT"));
564                button.addActionListener(
565                    new ActionListener() {
566                        public void actionPerformed(ActionEvent e) {
567                            JFileChooser jfc = new JFileChooser();
568                            jfc.setMultiSelectionEnabled(true);
569                            int result = jfc.showOpenDialog(BeanSetCustomizer.this);
570                            if (result == JFileChooser.APPROVE_OPTION) {
571                                File[] files = jfc.getSelectedFiles();
572                                List newbeans = new ArrayList(files.length);
573                                Bean b;
574                                for (int i = 0; i < files.length; i++) {
575                                    b = Bean.load(files[i]);
576                                    b.setId(getNewID(Globals.getPrefNode().node(prefnode)));
577                                    if (b != null) {
578                                        if (getBeanForName(b.getName()) != null) {
579                                            JOptionPane.showMessageDialog(
580                                                    BeanSetCustomizer.this,
581                                                    Globals.getMessage(
582                                                    "BEAN_EXISTS_WARNING",
583                                                    b.getName()),
584                                                    Globals.getString("BEAN_EXISTS_WARNING_TITLE"),
585                                                    JOptionPane.WARNING_MESSAGE
586                                                    );
587                                        } else {
588                                            newbeans.add(b);
589                                        }
590                                    }
591                                }
592                                beans.addAll(newbeans);
593                            }
594                        }
595                    });
596                controls.add(button);
597    
598                /*
599                 *  rename Bean button
600                 */
601                button =
602                        new JButton(Globals.getString("RENAME"));
603                button.addActionListener(
604                    new ActionListener() {
605                        public void actionPerformed(ActionEvent e) {
606                            Bean b = (Bean) beanList.getSelectedValue();
607                            if (b != null) {
608                                String newName = JOptionPane.showInputDialog(
609                                        BeanSetCustomizer.this,
610                                        Globals.getString("NEW_NAME_PROMPT"),
611                                        b.getName()
612                                        );
613                                if (newName != null && !newName.equals("")) {
614                                    renameBean(b, newName);
615                                }
616                            }
617                        }
618                    });
619                controls.add(button);
620    
621                /*
622                 *  remove Bean button
623                 */
624                button = new JButton(Globals.getString("DELETE"));
625                button.addActionListener(
626                    new ActionListener() {
627                        public void actionPerformed(ActionEvent e) {
628                            if (beanList.getSelectedValue() != null) {
629                                Bean b = (Bean) beanList.getSelectedValue();
630                                beanList.remove(b);
631                            }
632                        }
633                    });
634                controls.add(button);
635    
636            }
637            return controls;
638        }
639    
640    
641        /**
642         *  Gets the customizerClass attribute of the BeanSetCustomizer object
643         *
644         *@param  beanClass                   Description of the Parameter
645         *@return                             The customizerClass value
646         *@exception  ClassNotFoundException  Description of the Exception
647         */
648        private Class getCustomizerClass(Class beanClass) throws ClassNotFoundException {
649            String className = beanClass.getName();
650            className = className.replaceFirst("Bean$", "");
651            className = className.concat("Customizer");
652            return Class.forName(className);
653        }
654    
655    
656        /**
657         *  Gets the newBean attribute of the BeanSetCustomizer object
658         *
659         *@return    The newBean value
660         */
661        private Bean getNewBean() {
662            Bean result = null;
663            Class customizerClass;
664            Class beanClass;
665    
666            /*
667             *  try constructing a new instance of the beanset's current type
668             */
669            try {
670                beanClass = ((BeanSet.ListModel) beanList.getModel()).getType();
671                result = (Bean) beanClass.newInstance();
672                if (customizers.get(beanClass) == null) {
673                    customizerClass = getCustomizerClass(beanClass);
674                    AbstractBeanCustomizer customizer =
675                            (AbstractBeanCustomizer) customizerClass.newInstance();
676                    customizers.put(beanClass, customizer);
677                    beanView.add(customizer.getUI(), beanClass.getName());
678                }
679            } catch (Exception ex) {
680                result = null;
681            }
682    
683            /*
684             *  try constructing a peer of an existing bean
685             */
686            if (result == null) {
687                result = (Bean) beanList.getSelectedValue();
688                if (result == null && beanList.getModel().getSize() > 0) {
689                    result = (Bean) beanList.getModel().getElementAt(0);
690                }
691                if (result == null && beans.size() > 0) {
692                    result = (Bean) beans.first();
693                }
694    
695                if (result != null) {
696                    try {
697                        result = (Bean) result.getClass().newInstance();
698                    } catch (Exception ex) {
699                        result = null;
700                    }
701                }
702            }
703    
704            /*
705             *  try constructing one of the registered bean types
706             */
707            Iterator it = beanList.getRegisteredTypes().iterator();
708            while (it.hasNext() && result == null) {
709                try {
710                    beanClass = (Class) it.next();
711                    customizerClass = Class.forName(
712                            beanClass.getName().replaceFirst("Bean", "Customizer")
713                            );
714                    customizerClass.newInstance();
715                    result = (Bean) beanClass.newInstance();
716                } catch (Exception ex) {
717                    result = null;
718                }
719            }
720    
721            if (result != null) {
722                int num = 0;
723                String prefix = beanList.nameForClass(result.getClass());
724                while (getBeanForName(prefix + (++num)) != null);
725                result.setName(prefix + num);
726                result.setId(getNewID(Globals.getPrefNode().node(prefnode)));
727            }
728            return result;
729        }
730    
731    
732        /**
733         *  Description of the Method
734         *
735         *@return    Description of the Return Value
736         */
737        protected synchronized MainFrame mainFrame() {
738            if (owner == null) {
739                owner = (MainFrame) ((PreferencesDialogue) SwingUtilities.getAncestorOfClass(PreferencesDialogue.class, this)).getOwner();
740            }
741            return owner;
742        }
743    }