001    package net.sourceforge.mp3dings.preferences;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003-2006 Moritz Ringler
005     * $Id: FilenamePatternModule.java,v 1.26 2007/02/01 13:51:43 ringler Exp $
006     *
007     * This program is free software; you can redistribute it and/or
008     * modify it under the terms of the GNU General Public License
009     * as published by the Free Software Foundation; either version 2
010     * of the License, or (at your option) any later version.
011     *
012     * This program is distributed in the hope that it will be useful,
013     * but WITHOUT ANY WARRANTY; without even the implied warranty of
014     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015     * GNU General Public License for more details.
016     *
017     * You should have received a copy of the GNU General Public License
018     * along with this program; if not, write to the Free Software
019     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
020     */
021    
022    import java.awt.Component;
023    import java.awt.GridBagConstraints;
024    import java.awt.GridBagLayout;
025    import java.awt.GridLayout;
026    import java.awt.Insets;
027    import java.awt.event.ActionEvent;
028    import java.awt.event.ActionListener;
029    import java.util.ArrayList;
030    import java.util.Arrays;
031    import java.util.Collection;
032    import java.util.Iterator;
033    import java.util.List;
034    import java.util.TreeSet;
035    import java.util.logging.Logger;
036    import java.util.regex.Matcher;
037    import java.util.regex.Pattern;
038    import java.util.regex.PatternSyntaxException;
039    import javax.swing.BorderFactory;
040    import javax.swing.ComboBoxModel;
041    import javax.swing.JButton;
042    import javax.swing.JOptionPane;
043    import javax.swing.JPanel;
044    import javax.swing.JScrollPane;
045    import javax.swing.SwingConstants;
046    import javax.swing.SwingUtilities;
047    import javax.swing.event.ChangeEvent;
048    import javax.swing.event.ChangeListener;
049    import javax.swing.event.EventListenerList;
050    import javax.swing.event.ListDataEvent;
051    import javax.swing.event.ListDataListener;
052    import net.sourceforge.mp3dings.Field;
053    import net.sourceforge.mp3dings.Globals;
054    import net.sourceforge.mp3dings.MainFrame;
055    import net.sourceforge.mp3dings.utils.FilenamePatterns;
056    
057    /**
058     * A Preference Module that manages a group of FilenamePatternPanels.
059     * @author Moritz Ringler
060     * @version $Revision: 1.26 $ ($Date: 2007/02/01 13:51:43 $)
061     */
062    public class FilenamePatternModule extends TabbedPrefModule {
063        private static final Logger logger = Logger.getLogger(FilenamePatternModule.class.getPackage().getName());
064        final public static int DATA_TAB = 0;
065        private String test="Blur - Far out.mp3";
066        private MainFrame owner;
067        private SetComboBoxModel availableFields = new SetComboBoxModel();
068        private FilenamePatternPanel currentPanel = null;
069    
070        /** Constructs a new FilenamePatternModule with the given display
071        * name by loading previous settings from the associated user preferences
072        * node. **/
073        static public FilenamePatternModule loadFromUserPrefs(String name, MainFrame owner){
074            FilenamePatterns fp = FilenamePatterns.load(
075                Globals.getPrefNode().node("filenamePatterns")
076            );
077            return new FilenamePatternModule(name, owner, fp);
078        }
079    
080        /** Constructs a new FilenamePatternModule with the given display
081        * name. **/
082        public FilenamePatternModule(String name, MainFrame owner){
083            super(name);
084            this.owner = owner;
085            init();
086        }
087    
088        /** Constructs a new FilenamePatternModule with the given display
089        * name and filename patterns. **/
090        public FilenamePatternModule(String name, MainFrame owner, FilenamePatterns fp){
091            super(name);
092            this.owner = owner;
093            init();
094            addPatterns(fp);
095        }
096    
097        /** Initializes this class and its GUI. Used by all constructors. **/
098        private void init(){
099    
100            /* Construct the Set of availableFields */
101            Field[] allowedFields = owner.getModel(DATA_TAB).getAllowedFields();
102            List ffields = new ArrayList(allowedFields.length);
103            for(int i=0; i<allowedFields.length; i++){
104                ffields.add(allowedFields[i]);
105            }
106            availableFields.addAll(ffields);
107    
108            /* Monitor active PatternPanel and adjust availableFields accordingly */
109            book.addChangeListener(availableFields);
110    
111            /* Control buttons */
112    
113            remove(book);
114            remove(getTitle());
115            setLayout(new GridBagLayout());
116            GridBagConstraints gbc = new GridBagConstraints();
117    
118            gbc.fill = GridBagConstraints.BOTH;
119            gbc.gridx = 0;
120            gbc.gridy = 0;
121            gbc.gridwidth = 4;
122            gbc.gridheight = 1;
123            gbc.weightx = 1.0;
124            gbc.weighty = .0;
125            add(getTitle(), gbc);
126    
127            gbc.gridx = 0;
128            gbc.gridy = 1;
129            gbc.gridwidth = 1;
130            gbc.gridheight = 1;
131            gbc.ipadx = 2;
132            gbc.weighty = 0.;
133            gbc.weightx = 0.5;
134            gbc.fill = GridBagConstraints.NONE;
135            gbc.anchor = GridBagConstraints.CENTER;
136            gbc.insets = new Insets(5,5,5,5);
137            add(makeButtons(SwingConstants.WEST), gbc);
138    
139            gbc.gridx = 1;
140            add(makeButtons(SwingConstants.EAST), gbc);
141    
142            gbc.gridx = 0;
143            gbc.gridy = 2;
144            gbc.gridwidth = 2;
145            gbc.gridheight = 1;
146            gbc.weightx = 1.0;
147            gbc.weighty = 1.0;
148            gbc.fill = GridBagConstraints.BOTH;
149            add(book, gbc);
150        }
151    
152        /** Creates the control buttons. This method should only be used in the
153        * initialization of this class. **/
154        private Component makeButtons(int which){
155            JPanel buttons = new JPanel(new GridLayout(0,1,0,2));
156            buttons.setBorder(BorderFactory.createEmptyBorder(30,0,30,0));
157            JButton b;
158    
159            if(which == SwingConstants.EAST){
160                /* "New pattern" button */
161                b = new JButton(Globals.getString("PREF_FPATTERN_NEW"));
162                b.addActionListener(new ActionListener(){
163                    public void actionPerformed(ActionEvent e){
164                        addNewPanel();
165                        SwingUtilities.updateComponentTreeUI(getRootPane());
166                    }
167                });
168                buttons.add(b);
169    
170                /* Delete pattern button */
171                b = new JButton(Globals.getString("DELETE"));
172                b.addActionListener( new ActionListener(){
173                    public void actionPerformed(ActionEvent e){
174                        remove((PrefPanel) book.getSelectedComponent());
175                        SwingUtilities.updateComponentTreeUI(getRootPane());
176                    }
177                });
178                buttons.add(b);
179    
180            } else if (which == SwingConstants.WEST){
181    
182                /* "Test patterns" button */
183                b = new JButton(Globals.getString("PREF_FPATTERN_TEST"));
184                b.addActionListener(new ActionListener(){
185                    public void actionPerformed(ActionEvent e){
186                        test();
187                    }
188                });
189                buttons.add(b);
190    
191                /* "Default patterns" button */
192                b = new JButton(Globals.getString("PREF_FPATTERN_DEFAULT"));
193                b.addActionListener(new ActionListener(){
194                    public void actionPerformed(ActionEvent e){
195                        addPatterns(FilenamePatterns.mp3dingsDefault());
196                        SwingUtilities.updateComponentTreeUI(getRootPane());
197                    }
198                });
199                buttons.add(b);
200            }
201    
202            buttons.setOpaque(false);
203            return buttons;
204        }
205    
206        /** Returns the ComboBoxModel that the Panels use to display a ComboBox
207         * for FieldSelection. The model is automatically updated when changes
208         * to the module occur.
209         */
210        protected ComboBoxModel getFieldSelector(){
211            return availableFields;
212        }
213    
214        /** Removes a preferences field from this module. **/
215        public void remove(PrefPanel panel){
216            if(panel == null){
217                return;
218            }
219            if(! (panel instanceof FilenamePatternPanel)){
220                throw new IllegalArgumentException("You can only add FilenamePatternPanels to a FilenamePatternModule.");
221            }
222    
223            /* prevent the removal of the currentPanel's panel
224               from availableFields */
225            currentPanel = null;
226    
227            /* remove the panel from the tabbedPane and the list of panels.
228               this will trigger a change event only for the last tab. */
229            super.remove(panel);
230    
231            /* force update of availableFields */
232            availableFields.stateChanged(null);
233        }
234    
235        /** Adds an existing FilenamePatternPanel to this Module. Adding any other
236        * PrefPanel will cause an IllegalArgumentException to be raised.
237        **/
238        public void addPanel(PrefPanel panel){
239            if(! (panel instanceof FilenamePatternPanel)){
240                throw new IllegalArgumentException("You can only add FilenamePatternPanels to a FilenamePatternModule.");
241            }
242    
243            /* remove the new panel from the set of available panels */
244            availableFields.remove(((FilenamePatternPanel) panel).getField());
245    
246            /* add the new panel */
247            super.addPanel(panel);
248        }
249    
250        /** Adds a new FilenamePatternPanel to this Module. **/
251        public void addNewPanel(){
252    
253            /* pick a field for the new panel */
254            /* do nothing if no field is available */
255            if(
256                (availableFields.size() == 0) ||
257                (currentPanel != null && availableFields.size() == 1)
258              ){
259                return;
260            }
261    
262            /* try to use the first available field */
263            Field newField = (Field) availableFields.first();
264    
265            /* if the first available field is identical to the one that is currently
266               edited use the last field instead. */
267            if(
268                ( currentPanel != null ) &&
269                ( newField == currentPanel.getField() )
270              ){
271                newField = (Field) availableFields.last();
272            }
273    
274            /* construct the new panel */
275            FilenamePatternPanel fpf = new FilenamePatternPanel(this, newField);
276    
277            /* add the new panel to the module */
278            addPanel(fpf);
279        }
280    
281        /** Constructs and adds new FilenamePatternPanels for a collection
282          * of FilenamePatterns. **/
283        public void addPatterns(FilenamePatterns fp){
284            /* retrieve the fields */
285            Field[] fields = fp.getFields();
286            Arrays.sort(fields, Field.BY_LONGNAME);
287    
288            /* construct and add panels for the patterns */
289            FilenamePatternPanel fpp;
290            Field field;
291            for(int i=0; i < fields.length; i++){
292                field =  fields[i];
293    
294                /* do not add patterns for fields that already have
295                * an associated pattern */
296                if(
297                    availableFields.contains(field) &&
298                    (
299                        currentPanel == null ||
300                        (currentPanel.getField() != field)
301                    )
302                  ){
303                    try{
304                        /* construct the new panel */
305                        fpp = new FilenamePatternPanel(
306                            this, //FilenamePatternModule parent
307                            field, //int field,
308                            fp.getPattern(field), //String p
309                            fp.getCgString(field) //String cgs
310                        );
311                        /* add the panel to the module */
312                        addPanel(fpp);
313    
314                    } catch (IllegalArgumentException ex){
315                        logger.severe("Error loading filename pattern panel for field " + field);
316                        logger.severe(ex.toString());
317                    }//try-catch
318                }//if
319            }//loop
320        }//method
321    
322        /** Displays an interactive dialog that allows the user to test the
323        * current settings in this FilenamePatternModule against a provided
324        * filename. **/
325        private void test(){
326    
327            /* prompt for a test input string */
328            test = (String) JOptionPane.showInputDialog(
329                this,
330                Globals.getString("PREF_FPATTERN_TESTPROMPT"),
331                Globals.getString("PREF_FPATTERN_TESTTITLE"),
332                JOptionPane.QUESTION_MESSAGE,
333                null,
334                null,
335                test);
336            if(test == null || test.equals("")){
337                return;
338            }
339    
340            /* allocate a result buffer */
341            StringBuffer result = new StringBuffer(128);
342            result.append(Globals.getString("PREF_FPATTERN_FPATTERN")).append("\n");
343    
344            /* retrieve the current panels and their patterns */
345            PrefPanel[] fpp = getPanels();
346            FilenamePatterns fp = readPatterns();
347    
348            /* perform matches and append labeled results to output */
349            for(int i=0, fid; i<fpp.length; i++){
350                Field field = ((FilenamePatternPanel) fpp[i]).getField();
351                try {
352                    result.append(field.longname());
353                    result.append(": ");
354                    result.append(fp.apply(test, field)).append("\n");
355                } catch (PatternSyntaxException ex){
356                }
357            }
358    
359            /* display the output */
360            JOptionPane.showMessageDialog(this,
361             result.toString(),
362             Globals.getString("PREF_FPATTERN_TESTTITLE"),
363             JOptionPane.INFORMATION_MESSAGE,
364             null);
365        }
366    
367        private FilenamePatterns readPatterns(){
368            PrefPanel[] panels = getPanels();
369            FilenamePatterns fp = new FilenamePatterns();
370            FilenamePatternPanel fpp;
371            String pattern, cgString;
372            Field field;
373            for(int i=0; i<panels.length; i++){
374                fpp = (FilenamePatternPanel) panels[i];
375                field = fpp.getField();
376                /* read the current pattern from the panel */
377                try{
378                    pattern = fpp.getPattern();
379                    cgString = checkCgString(pattern, fpp.getCgString());
380                    fpp.setCgString(cgString);
381                    fp.putPattern(field, pattern, cgString);
382                } catch (PatternSyntaxException ex){
383                    //don't save
384                }
385            }
386            return fp;
387        }
388    
389        //@Override
390        public void showInvalidPanel(){
391            FilenamePatternPanel pp = getFirstInvalidPanel();
392            if(pp != null){
393                book.setSelectedComponent(pp);
394                try{
395                    pp.getPattern();
396                } catch (PatternSyntaxException ex){
397                    pp.showErrorMessage(ex);
398                }
399            }
400        }
401    
402        //@Override
403        public boolean isSavable(){
404            return (getFirstInvalidPanel() == null);
405        }
406    
407        private FilenamePatternPanel getFirstInvalidPanel(){
408            PrefPanel[] panels = getPanels();
409            FilenamePatternPanel p = null;
410            int i = 0;
411            for(; i<panels.length; i++){
412                p = (FilenamePatternPanel) panels[i];
413                if(!p.isSavable()){
414                    break;
415                }
416            }
417            return (i == panels.length)? null : p;
418        }
419    
420        /* This method checks if the replacement string
421           contains illegal replacement group references
422           and returns a String in which those references
423           are escaped. */
424        private static String checkCgString(String pattern, String cgs){
425            StringBuffer result = null;
426            if (cgs != null){
427                Matcher m = Pattern.compile(pattern).matcher("");
428                final int numgroups = m.groupCount();
429                Matcher cgm = Pattern.compile("\\$(\\d+)").matcher(cgs);
430                int groupnum;
431                result = new StringBuffer();
432                while(cgm.find()){
433                    String snum = cgm.group(1);
434                    groupnum = Integer.parseInt(snum);
435                    /* only take subsequent digits into account if this
436                    leads to a valid group reference */
437                    while(groupnum > 9 && groupnum > numgroups){
438                        groupnum /= 10;
439                    }
440                    if(groupnum > numgroups){
441    
442                        /* we have an illegal capturing group reference
443                        if the dollar sign has not been escaped with a backslash.
444                        therefore we count leading backslashes.
445                        */
446                        int backslashcount = 0;
447                        for(int offset = cgm.start() -1;
448                        offset >= 0 && cgs.charAt(offset) == '\\';
449                        offset --)
450                        {
451                            backslashcount ++;
452                        }
453                        if (backslashcount % 2 == 0){
454    
455                            /* the dollar sign has not been escaped,
456                            we have an illegal group reference
457                            that must be escaped with a backslash
458                            */
459                            cgm.appendReplacement(result, "\\\\$0");
460                            continue;
461                        }
462                    }
463                    /* everything is OK, append unchanged */
464                    cgm.appendReplacement(result, "$0");
465                }
466                cgm.appendTail(result);
467            }
468            return (result ==  null)? null : result.toString();
469        }
470    
471        /** Shows this FilenamePatternModule in a modal
472            JOptionPane ConfirmDialog. **/
473        public void showDialog(){
474            int result = JOptionPane.showConfirmDialog(
475                owner,
476                new JScrollPane(this),
477                "",
478                JOptionPane.OK_CANCEL_OPTION,
479                JOptionPane.PLAIN_MESSAGE);
480            if(result == JOptionPane.OK_OPTION){
481                /* due to the specific way in which filename patterns are saved
482                 * it is not necessary to clear the pref node first */
483                save();
484            }
485        }
486    
487        public void save(){
488            readPatterns().save(Globals.getPrefNode().node("filenamePatterns"));
489        }
490        //End of FilenamePatternModule methods
491    
492        /** This set comprises all fields that do not currently have a filename
493         * initializer, plus the field initialized by the FilenamePattern in the
494         * current FilenamePatternPanel.<br>
495         * It is used as the ComboBoxModel for the field selectors in the
496         * FilenamePatternPanels.<br>
497         * It listens to changes in the TabbedPane to update its contents
498         * when the selected tab changes or when a tab is added or removed.
499         **/
500        private class SetComboBoxModel extends TreeSet implements ComboBoxModel, ChangeListener{
501            private Object selectedItem = null;
502    
503            public SetComboBoxModel(){
504                super(Field.BY_LONGNAME);
505            }
506    
507            public Object getSelectedItem(){
508                return selectedItem;
509            }
510    
511            public boolean add(Object o){
512                boolean b = super.add(o);
513                if(b) fireContentsChanged();
514                return  b;
515            }
516    
517            public boolean addAll(Collection c){
518                boolean b = super.addAll(c);
519                if(b) fireContentsChanged();
520                return  b;
521            }
522    
523            public void clear(){
524                super.clear();
525                fireContentsChanged();
526            }
527    
528            public boolean remove(Object o){
529                boolean b = super.remove(o);
530                if(b) fireContentsChanged();
531                return b;
532            }
533    
534            public boolean removeAll(Collection c){
535                boolean b = super.removeAll(c);
536                if(b) fireContentsChanged();
537                return b;
538            }
539    
540            public void setSelectedItem(Object anItem){
541                selectedItem = anItem;
542                if(anItem instanceof Field){
543                    currentPanel.setField((Field) anItem);
544                }
545                book.setTitleAt(book.getSelectedIndex(),
546                ((FilenamePatternPanel) book.getSelectedComponent()).getName());
547            }
548    
549            public int getSize(){
550                return size();
551            }
552    
553            public Object getElementAt(int index){
554                Iterator it = iterator();
555                for(int i = 0; i< index; i++){
556                    it.next();
557                }
558                return it.next();
559            }
560    
561            /* Event generation and listener management */
562            EventListenerList listenerList = new EventListenerList();
563            ListDataEvent event = null;
564    
565            public void addListDataListener(ListDataListener l) {
566                listenerList.add(ListDataListener.class, l);
567            }
568    
569            public void removeListDataListener(ListDataListener l) {
570                listenerList.remove(ListDataListener.class, l);
571            }
572    
573            /** Informs comboboxes that something has changed. */
574            protected void fireContentsChanged() {
575                Object[] listeners = listenerList.getListenerList();
576    
577                /* Process the listeners last to first, notifying
578                 * those that are interested in this event */
579                for (int i = listeners.length-2; i>=0; i-=2) {
580                    if (listeners[i] == ListDataListener.class) {
581                        event = new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize());
582                        ((ListDataListener) listeners[i+1]).contentsChanged(event);
583                    }//if
584                }//loop
585            }//method
586    
587            /** Listens for changes in the TabbedPane to update this sets contents
588             * when the selected tab changes or when a tab is added or removed.*/
589            public void stateChanged(ChangeEvent e){
590                FilenamePatternPanel oldPanel = currentPanel;
591                //System.out.println("oldPanel "+((oldPanel == null)?"null":oldPanel.getName()));
592                currentPanel = (FilenamePatternPanel) book.getSelectedComponent();
593                //System.out.println("currentPanel "+((currentPanel == null)?"null":currentPanel.getName()));
594                if(currentPanel != null){
595                    Field newField = currentPanel.getField();
596                    availableFields.add(newField);
597                    availableFields.setSelectedItem(newField);
598                }
599                if(oldPanel != null && oldPanel != currentPanel){
600                    Field oldField = oldPanel.getField();
601                    availableFields.remove(oldField);
602                }
603            }
604    
605        }//End of class SetComboBoxModel
606    
607    }//End of class FilenamePatternModule