001    package net.sourceforge.mp3dings.filter;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003-2004 Moritz Ringler
005     * $Id: BeanShellFilterCustomizer.java 69 2007-10-24 21:57:43Z ringler $
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.GridBagLayout;
023    import java.awt.GridBagConstraints;
024    import java.awt.Component;
025    import java.awt.Color;
026    import java.awt.Toolkit;
027    import java.awt.event.WindowEvent;
028    import java.beans.PropertyChangeEvent;
029    import java.beans.PropertyChangeListener;
030    import java.util.prefs.Preferences;
031    import java.util.logging.Logger;
032    import javax.swing.BorderFactory;
033    import javax.swing.JFrame;
034    import javax.swing.JComponent;
035    import javax.swing.InputVerifier;
036    import javax.swing.JLabel;
037    import javax.swing.JPanel;
038    import javax.swing.JScrollPane;
039    import javax.swing.JTextArea;
040    import javax.swing.Box;
041    import javax.swing.JOptionPane;
042    import net.sourceforge.mp3dings.Field;
043    import net.sourceforge.mp3dings.Globals;
044    import net.sourceforge.mp3dings.utils.AbstractBeanCustomizer;
045    import net.sourceforge.mp3dings.utils.Bean;
046    import bsh.EvalError;
047    import bsh.ParseException;
048    
049    /**
050     * The customizer class for bean shell filters.
051     * @author Moritz Ringler
052     * @version $Revision: 69 $ ($Date: 2007-10-24 23:57:43 +0200 (Mi, 24 Okt 2007) $)
053     * @see BeanShellFilter
054     */
055    public class BeanShellFilterCustomizer extends AbstractBeanCustomizer{
056        private static final Logger logger = Logger.getLogger(AbstractBeanCustomizer.class.getPackage().getName());
057        private static final String BLABLA =
058            "Sourced file: inline evaluation of: ``new " +
059            "net.sourceforge.mp3dings.filter.Filter(){public Object filter(Object a)" +
060            "{ Object r . . . ''";
061    
062        JPanel uui = new JPanel(new GridBagLayout());
063        JLabel error = new JLabel();
064        PropertyChangeListener errorUpdater =
065                new PropertyChangeListener(){
066                    public void propertyChange(PropertyChangeEvent evt){
067                        updateError();
068                    }
069                };
070    
071        public BeanShellFilterCustomizer(BeanShellFilter filter){
072            super(filter);
073            Component editor;
074    
075            GridBagConstraints gbc = new GridBagConstraints();
076            gbc.gridx = 0;
077            gbc.gridy = 0;
078            gbc.gridheight = 1;
079            gbc.gridwidth = 2;
080            gbc.weightx = 1;
081            gbc.weighty = 0;
082            gbc.fill = GridBagConstraints.BOTH;
083    
084            uui.add(new JLabel("<html><pre>" +
085            "public Object filter(Object a){<br>" +
086                "    Object result;</pre></html>"), gbc);
087    
088            gbc.gridy++;
089            gbc.weighty = 1;
090    
091            editor = getPropertyEditor("methodBody",
092                new Object[]{ Globals.asInteger(1), Globals.asInteger(1) });
093            editor.setFont(Globals.MONOSPACE_0_12);
094            ((JTextArea) editor).setTabSize(2);
095    
096            // /* input verifier does not prevent switching to another filter,
097               // therefore it is disabled completely. */
098             // ((JComponent) editor).setInputVerifier(new InputVerifier(){
099                 // public boolean verify(JComponent input){
100                     // return ((BeanShellFilter) getModel()).isSavable();
101                 // }
102                 // public boolean shouldYieldFocus(JComponent input) {
103                     // boolean inputOK = verify(input);
104                     // if (inputOK) {
105                         // return true;
106                     // }
107                     // /* Avoid possible focus-transfer problems when bringing up
108                      // * the dialog by temporarily removing the input verifier.
109                      // * This is a workaround for bug #4532517. */
110                     // input.setInputVerifier(null);
111                     // /* pop up the message dialog. */
112                     // JOptionPane.showMessageDialog(
113                         // BeanShellFilterCustomizer.this.getUI(),
114                         // "Bean shell script does not compile, or does not preserve input type (String, Double, Boolean).",
115                         // "Illegal Bean Shell Script", JOptionPane.WARNING_MESSAGE);
116                     // /* reinstall the input verifier. */
117                     // input.setInputVerifier(this);
118                     // /* beep and then tell whoever called us that we don't
119                      // * want to yield focus. */
120                     // Toolkit.getDefaultToolkit().beep();
121                     // return false;
122                 // }
123             // }
124             // );
125    
126            JScrollPane jsp = new JScrollPane(editor);
127            jsp.setBorder(BorderFactory.createEmptyBorder(0,22,0,0));
128            uui.add(jsp, gbc);
129    
130            gbc.weighty = 0;
131            gbc.gridy++;
132    
133            uui.add(new JLabel("<html><pre>    return result;<br>" +
134                "}</pre></html>"), gbc);
135    
136            gbc.gridy++;
137            /*
138            gbc.gridwidth = 1;
139            gbc.weightx = 0;
140    
141            editor = getPropertyEditor("savable", true, new Object[]{ "savable" });
142            editor.setEnabled(false);
143            uui.add(editor, gbc);
144    
145            /*gbc.gridx++;*/
146            gbc.weightx = 1;
147    
148            error.setForeground(Color.red);
149            uui.add(error, gbc);
150    
151            filter.addPropertyChangeListener("compileError", errorUpdater);
152            addPropertyChangeListener("model", errorUpdater);
153        }
154    
155    
156        public BeanShellFilterCustomizer(){
157            this(new BeanShellFilter());
158        }
159    
160        private void updateError(){
161            BeanShellFilter bsf = (BeanShellFilter) getModel();
162            Throwable newError = bsf.getCompileError();
163    
164            if(newError == null){
165    
166                /* clear error message */
167                error.setText("");
168    
169            } else {
170    
171                /* retrieve original cause and error message */
172                Throwable cause = newError.getCause();
173                while(cause != null){
174                    newError = cause;
175                    cause = newError.getCause();
176                }
177                String message = newError.getMessage();
178    
179                if(message == null){
180                    message = "<nunknown error>";
181                } else {
182                    /* normalize whitespace */
183                    message = message.replaceAll("\\s+", " ");
184                    message = message.trim();
185    
186                    /* remove leading garbage */
187                    if(message.startsWith(BLABLA)){
188                        message = message.substring(BLABLA.length()).trim();
189                    }
190                }
191    
192                /* prepend line number if possible and necessary*/
193                int line = -1;
194                if(newError instanceof EvalError){
195                    try{
196                        line = ((EvalError) newError).getErrorLineNumber();
197                    } catch (NullPointerException ex){
198                        logger.warning("Caught null pointer exception in bsh.ParseException.getErrorLineNumber().");
199                        logger.warning("You are using a buggy bsh.ParseException, see http://tinyurl.com/wc5ym");
200                        line = -1;
201                    }
202                }
203                String linestr = "line " + line;
204                if ( (line != -1) && (message.indexOf(linestr) == -1) ){
205                    message = linestr + ": " + message;
206                }
207                error.setText(message);
208            }
209        }
210    
211        public static void main (String[] argv){
212            final Preferences pref = Preferences.userNodeForPackage(BeanShellFilterCustomizer.class);
213            BeanShellFilter filter = (BeanShellFilter) BeanShellFilter.load(pref ,"test_bshf");
214            final BeanShellFilter xfilter = (filter == null)
215                ? new BeanShellFilter()
216                : filter ;
217                xfilter.addPropertyChangeListener("methodBody", new PropertyChangeListener(){
218                    public void propertyChange(PropertyChangeEvent evt){
219                        if (xfilter.isSavable()){
220                            System.out.println(xfilter.filter("abcdefg"));
221                        }
222                    }
223                });
224            JFrame frame = new JFrame(){
225                protected void processWindowEvent(WindowEvent e) {
226                    xfilter.save(pref, "test_bshf");
227                    super.processWindowEvent(e);
228                    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
229                        System.exit(0);
230                    }
231                }
232            };
233            frame.add((new BeanShellFilterCustomizer(xfilter)).getUI());
234            frame.pack();
235            frame.setVisible(true);
236        }
237    
238        public void setModel(Bean filter){
239            if(!(filter instanceof BeanShellFilter)){
240                throw new IllegalArgumentException("Model is not a BeanShellFilter.");
241            }
242            Bean oldModel = getModel();
243            super.setModel(filter);
244            Bean newModel = getModel();
245            if(newModel != oldModel){
246                oldModel.removePropertyChangeListener("compileError", errorUpdater);
247                newModel.addPropertyChangeListener("compileError", errorUpdater);
248            }
249        }
250    
251        public Component getUI(){
252            return uui;
253        }
254    }