001    package net.sourceforge.mp3dings.preferences;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: FilenamePatternPanel.java,v 1.15 2007/01/18 09:42:06 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.Insets;
026    import java.awt.Toolkit;
027    import java.awt.event.ActionEvent;
028    import java.awt.event.ActionListener;
029    import java.util.regex.Pattern;
030    import java.util.regex.PatternSyntaxException;
031    import javax.swing.InputVerifier;
032    import javax.swing.JCheckBox;
033    import javax.swing.JComboBox;
034    import javax.swing.JComponent;
035    import javax.swing.JLabel;
036    import javax.swing.JList;
037    import javax.swing.JOptionPane;
038    import javax.swing.JPanel;
039    import javax.swing.JTextField;
040    import javax.swing.ListCellRenderer;
041    import javax.swing.plaf.basic.BasicComboBoxRenderer;
042    import net.sourceforge.mp3dings.Field;
043    import net.sourceforge.mp3dings.Globals;
044    
045    /**
046     * This Preference Field configures a regular expression with which
047     * meta information is extracted from filenames.
048     * @author Moritz Ringler
049     * @version $Revision: 1.15 $ ($Date: 2007/01/18 09:42:06 $)
050     */
051    public class FilenamePatternPanel extends PrefPanel{
052        JTextField pattern;
053        private JTextField cgString;
054        private JComboBox fields;
055        private JCheckBox useCapturingGroup;
056        private Field field;
057        private final static ListCellRenderer FIELD_SELECTOR_RENDERER =
058            new BasicComboBoxRenderer(){
059                public Component getListCellRendererComponent(JList list,
060                                                              Object value,
061                                                              int index,
062                                                              boolean isSelected,
063                                                              boolean cellHasFocus){
064                    Object val = value;
065                    if(value instanceof Field){
066                        val = ((Field) value).longname();
067                    }
068                    return super.getListCellRendererComponent(list, val, index,
069                            isSelected, cellHasFocus);
070                }
071    
072            };
073    
074        /** Constructs a new instance of this class.
075         * @param parent the FilenamePatternModule the manages this panel
076         * @param field the field that is initially associated with this PrefPanel
077         * @param p the initial regular expression for this PrefPanel
078         * @param cgs the initial capturing group string
079         * @throws IllegalArgumentException if field is not in availableFields.
080         * @throws PatternSyntaxException if p cannot be compiled as a
081         *         regular expression
082         **/
083        public FilenamePatternPanel(FilenamePatternModule parent,
084                Field field, String p, String cgs){
085            super(null, field.longname());
086            fields = new JComboBox(parent.getFieldSelector());
087            this.field = field;
088            init(!(cgs == null || cgs.equals("")));
089            setPattern(p);
090            /* Test whether p is valid regexp */
091            getPattern();
092            setCgString(cgs);
093            this.setVisible(true);
094        }
095    
096        /** Creates a new FilenamePatternPanel with the given title. **/
097        public FilenamePatternPanel(FilenamePatternModule parent,
098                Field field){
099            super(null, field.longname());
100            fields = new JComboBox(parent.getFieldSelector());
101            this.field = field;
102            init(false);
103        }
104    
105    
106        private void updateTitle(){
107            setName(getField().longname());
108        }
109    
110        /** Builds the GUI of a new FilenamePatternPanel.
111         * @param ugcEnabled whether to capturing groups are activated
112         **/
113        private void init(boolean ucgEnabled){
114            /* field selection */
115            JPanel row = new JPanel();
116            JLabel lDetermine = new JLabel(Globals.getString("PREF_FPATTERN_EXTRACT"));
117            JLabel lFromFilename = new JLabel(Globals.getString("PREF_FPATTERN_FROM"));
118            JLabel lFindRegExp = new JLabel(Globals.getString("PREF_FPATTERN_FINDRE"));
119            row.add(lDetermine);
120            fields.setRenderer(FIELD_SELECTOR_RENDERER);
121            row.add(fields);
122            row.add(lFromFilename);
123    
124            /* reg exp input */
125            pattern = new JTextField(10);
126            /* Input Verifier that checks whether the text in pattern
127             * is a valid regular expression */
128            pattern.setInputVerifier(new InputVerifier(){
129                public boolean verify(JComponent input){
130                    if(input == pattern){
131                        return isSavable();
132                    }
133                    return true;
134                }
135    
136                public boolean shouldYieldFocus(JComponent input) {
137                    boolean result = false;
138                    try{
139                        getPattern();
140                        result = true;
141                    } catch (PatternSyntaxException ex){
142                        /* Avoid possible focus-transfer problems when bringing up
143                         * the dialog by temporarily removing the input verifier.
144                         * This is a workaround for bug #4532517. */
145                        input.setInputVerifier(null);
146                        showErrorMessage(ex);
147                        /* reinstall the input verifier. */
148                        input.setInputVerifier(this);
149                        /* beep and then tell whoever called us that we don't
150                         * want to yield focus. */
151                        Toolkit.getDefaultToolkit().beep();
152                    }
153                    return result;
154                }
155            });
156    
157            /* activate capturing groups */
158            useCapturingGroup = new JCheckBox(
159                Globals.getString("PREF_FPATTERN_USECG"),
160                ucgEnabled
161            );
162    
163            /* replacement string */
164            final JLabel lReplacementLikeString =
165                    new JLabel(Globals.getString("PREF_FPATTERN_REPLWITH"));
166            cgString = new JTextField(16);
167    
168            lReplacementLikeString.setEnabled(ucgEnabled);
169            cgString.setEnabled(ucgEnabled);
170    
171            /* actionListener for useCapturingGroup */
172            ActionListener ucgl = new ActionListener(){
173                public void actionPerformed(ActionEvent e){
174                    Object src = e.getSource();
175                    if (src != useCapturingGroup){
176                        return;
177                    } else {
178                        boolean ucgEnabled = useCapturingGroup.isSelected();
179                        lReplacementLikeString.setEnabled(ucgEnabled);
180                        cgString.setEnabled(ucgEnabled);
181                    }
182                }
183            };
184            useCapturingGroup.addActionListener(ucgl);
185    
186            /* assembly */
187            /* Main Box */
188            setLayout(new GridBagLayout());
189            GridBagConstraints gbc = new GridBagConstraints();
190            Insets ins3 = new Insets(3,3,3,3);
191            Insets ins0 = new Insets(0,0,0,0);
192            Insets ins6333 = new Insets(6,3,3,3);
193            Insets ins10333 = new Insets(10,3,3,3);
194    
195            /* new row */
196            gbc.gridx  = 0;
197            gbc.gridy  = 0;
198            gbc.fill   = GridBagConstraints.NONE;
199            gbc.anchor = GridBagConstraints.WEST;
200            gbc.gridheight = 1;
201            gbc.gridwidth = 2;
202            gbc.weightx = 3;
203            gbc.weighty = 0;
204            gbc.insets = ins3;
205    
206            add(row, gbc);
207    
208            /* new row */
209            gbc.gridy = 1;
210            gbc.insets = ins10333;
211            add(lFindRegExp, gbc);
212    
213            /* new row */
214            gbc.gridy  = 2;
215            gbc.insets = ins3;
216            gbc.fill   = GridBagConstraints.HORIZONTAL;
217            gbc.ipadx  = 5;
218    
219            add(pattern, gbc);
220    
221            /* new row */
222            gbc.gridy = 3;
223            gbc.insets = ins10333;
224            gbc.gridheight = 1;
225            gbc.fill = GridBagConstraints.NONE;
226            gbc.ipadx = 0;
227    
228            add(useCapturingGroup,gbc);
229    
230            /* new row */
231            gbc.gridy  = 4;
232            gbc.insets = ins3;
233            gbc.gridwidth  = 1;
234            gbc.weightx    = 0;
235    
236            add(lReplacementLikeString, gbc);
237    
238            gbc.gridwidth = 1;
239            gbc.gridx     = 1;
240            gbc.weightx   = 2;
241            gbc.ipadx     = 5;
242            gbc.fill   = GridBagConstraints.HORIZONTAL;
243    
244            add(cgString, gbc);
245    
246            /* last row (glue)*/
247            gbc.gridy = 5;
248            gbc.gridx = 0;
249            gbc.weightx = 1;
250            gbc.weighty = 1;
251            gbc.ipadx = 0;
252            gbc.insets = ins0;
253            gbc.fill = GridBagConstraints.BOTH;
254            add(new JPanel(), gbc);
255        }
256    
257        void showErrorMessage(PatternSyntaxException ex){
258            StringBuffer sb = new StringBuffer("<html>");
259            sb.append(Globals.getString("PREF_FPATTERN_NORE"));
260            sb.append("<pre>");
261            sb.append(ex.getMessage());
262            sb.append("</pre></html>");
263            JLabel msg = new JLabel(sb.toString());
264    
265            /* pop up the message dialog. */
266            JOptionPane.showMessageDialog(
267                        FilenamePatternPanel.this,
268                        msg,
269                        Globals.getString("PREF_FPATTERN_INVALID"), //title
270                    JOptionPane.WARNING_MESSAGE);
271        }
272    
273        /** Returns the id of the currently selected field. **/
274        public Field getField(){
275            return field;
276        }
277    
278        /** Sets the current field in the GUI. **/
279        public void setField(Field field){
280            this.field = field;
281            updateTitle();
282        }
283    
284        /** Sets the current regular expression in the GUI. **/
285        public void setPattern(String p){
286            pattern.setText(p);
287        }
288    
289        /** Returns the current Regular Expression from the pattern field.
290        * @throws PatternSyntaxException if the String in the pattern field
291        * cannot be compiled as a regular expression **/
292        public String getPattern(){
293            Pattern.compile(pattern.getText());
294            return pattern.getText();
295        }
296    
297        public boolean isSavable(){
298            boolean result = false;
299            try{
300                getPattern();
301                result = true;
302            } catch (PatternSyntaxException ex){
303            }
304            return result;
305        }
306    
307        /** Returns a String representation of the current state of a
308         * FilenamePatternPanel. **/
309        public String toString(){
310            StringBuffer sb = new StringBuffer();
311            sb.append("Field: ").append(field);
312            sb.append("\nPattern:").append(getPattern());
313            sb.append("\nCgString:").append(getCgString());
314            return sb.toString();
315        }
316    
317        /** Sets the capturing group string in the GUI. **/
318        public void setCgString(String cgs){
319            if(cgs == null){
320                cgString.setText("");
321                useCapturingGroup.setSelected(false);
322            }
323            cgString.setText(cgs);
324        }
325    
326        /** Returns the current capturing group string in the GUI. **/
327        public String getCgString(){
328           if(useCapturingGroup.isSelected()){
329               return cgString.getText();
330           } else {
331               return null;
332           }
333        }
334    
335        /** Does nothing. FilenamePatternPanels are intended to be saved
336        * by a FilenamePatternModule. **/
337        public void save(){
338        }
339    }