001    package net.sourceforge.mp3dings.preferences;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2006 Moritz Ringler
005     * $Id: ExternalApplicationPanel.java,v 1.17 2006/07/11 16:59:55 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.BorderLayout;
023    import java.awt.Component;
024    import java.awt.FlowLayout;
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.prefs.Preferences;
030    import javax.swing.AbstractButton;
031    import javax.swing.BorderFactory;
032    import javax.swing.Box;
033    import javax.swing.BoxLayout;
034    import javax.swing.ButtonGroup;
035    import javax.swing.JButton;
036    import javax.swing.JDialog;
037    import javax.swing.JFileChooser;
038    import javax.swing.JLabel;
039    import javax.swing.JOptionPane;
040    import javax.swing.JPanel;
041    import javax.swing.JRadioButton;
042    import javax.swing.border.EmptyBorder;
043    import net.sourceforge.mp3dings.Globals;
044    import net.sourceforge.mp3dings.export.AbstractExporter;
045    import net.sourceforge.mp3dings.utils.ExternalApplication;
046    import de.mospace.swing.JBook;
047    import de.mospace.swing.PathInput;
048    
049    /**
050     * The Preference Field that configures the settings for mp3 playback
051     * with an external player.
052     * @author Moritz Ringler
053     * @version $Revision: 1.17 $ ($Date: 2006/07/11 16:59:55 $)
054     */
055    public class ExternalApplicationPanel extends PrefPanel{
056        ExternalApplication app;
057        JLabel description;
058        boolean deleteAllowed = true;
059    
060        /* executable path */
061        private PathInput exe;
062    
063        /* working directory */
064        private PathInput pwd;
065    
066        /* i/o tabs */
067        private IoTab stdout, stderr, stdin;
068        private JRadioButton consoleThread;
069    
070        /* identifier */
071        private int id;
072    
073        /* exporters */
074        private final static String[] EXPORTERS = AbstractExporter.getImplementations();
075        private final static String[] EXPNAMES = new String[EXPORTERS.length];
076        static {
077            Exception rx = null;
078            for (int i=0; i<EXPORTERS.length; i++){
079                try{
080                EXPNAMES[i] =
081                    ((AbstractExporter) Class.forName(EXPORTERS[i]).newInstance())
082                    .getName();
083                } catch (InstantiationException ex){
084                    rx = ex;
085                } catch (IllegalAccessException ex){
086                    rx = ex;
087                } catch (ClassNotFoundException ex){
088                    rx = ex;
089                }
090                if (rx != null){
091                   /* All the above exceptions are checked by RTSI.
092                   Therefore they should never arise here.
093                   If for some reason they do we raise a runtime exception
094                   that will stop program execution. */
095                    throw new RuntimeException(rx);
096                }
097            }
098        }
099    
100        private JBook advancedConfig = new JBook();
101    
102        /* testing function */
103        public static void main(String argv[]){
104            JDialog dialg = new JDialog();
105            dialg.add(new ExternalApplicationPanel(Preferences.userNodeForPackage(ExternalApplicationPanel.class), "Test", 0));
106            dialg.pack();
107            dialg.setVisible(true);
108        }
109    
110        public ExternalApplicationPanel(Preferences pref, int j){
111            this(pref, nameFromPref(pref, j), j);
112        }
113    
114        private static String nameFromPref(Preferences pref, int j){
115            ExternalApplication eapp = ExternalApplication.load(pref, j);
116            return (eapp == null)? "External Application" : eapp.getName();
117        }
118    
119        public ExternalApplicationPanel(Preferences pref,String name, int j){
120            this(pref, name, j, true, true);
121        }
122    
123        public ExternalApplicationPanel(Preferences pref,String name, int j, boolean deleteAllowed){
124            this(pref, name, j, deleteAllowed, true);
125        }
126    
127        public ExternalApplicationPanel(Preferences pref, String name, int j,
128                boolean deleteAllowed, boolean showAdvancedConfig){
129            super(pref,name);
130            id = j;
131            this.deleteAllowed = deleteAllowed;
132            init(showAdvancedConfig);
133        }
134    
135        private void init(boolean showAdvancedConfig){
136            app = ExternalApplication.load(getPrefs(), id);
137            if(app == null){
138                app = new ExternalApplication();
139                /* don't save app here,
140                 * the general contract of the mp3dings preferences is
141                 * that the preferences change ONLY when you hit the OK
142                 * button in the PreferenceDialogue
143                 */
144            }
145            Box content = Box.createVerticalBox();
146            content.add(buildBasicConfig());
147            Component advanced = buildAdvancedConfig();
148            if(showAdvancedConfig){
149                content.add(advanced);
150            }
151            add(content, BorderLayout.NORTH);
152        }
153    
154        public boolean isDeleteAllowed(){
155            return deleteAllowed;
156        }
157    
158    /*     public Dimension getPreferredSize(){
159            Dimension d = super.getPreferredSize();
160            d.height = (d.height > 200)? d.height : 200;
161            return d;
162        } */
163    
164    
165    
166        public void setDescription(String text){
167            description.setText(text);
168        }
169    
170        private Component buildBasicConfig(){
171            Box result = Box.createVerticalBox();
172            JPanel basicConfig = new JPanel(new BorderLayout());
173            description = new JLabel();
174            description.setText(Globals.getString("COMMAND_LINE_(USE_%F_FOR_FILE_ARGUMENT(S))"));
175            description.setBorder(BorderFactory.createEmptyBorder(2,0,5,0));
176            exe = new PathInput(app.getExePath());
177            basicConfig.add(description, BorderLayout.NORTH);
178            basicConfig.add(exe, BorderLayout.CENTER);
179            result.add(basicConfig);
180            return result;
181        }
182    
183        private final static Insets expandInsets = new Insets(0,0,0,0);
184    
185        private JPanel buildAdvancedConfig(){
186            JPanel self = new JPanel(new BorderLayout());
187    
188            advancedConfig = new JBook();
189            advancedConfig.add(buildCallModeTab(),
190                    Globals.getString("CALL_MODE"),
191                    Globals.getKeyObject("CALL_MODE_MNEMONIC"));
192            advancedConfig.add(buildWorkingDirectoryTab(),
193                    Globals.getString("WORKING_DIRECTORY"),
194                    Globals.getKeyObject("WORKING_DIRECTORY_MNEMONIC"));
195            advancedConfig.add(buildIoTabs(),
196                    Globals.getString("I/O"),
197                    Globals.getKeyObject("I/O_MNEMONIC"));
198            advancedConfig.add(buildThreadTab(),
199                    Globals.getString("THREADING"),
200                    Globals.getKeyObject("THREADING_MNEMONIC"));
201            advancedConfig.setVisible(false);
202            self.add(advancedConfig, BorderLayout.SOUTH);
203    
204            /* show/hide button */
205            AbstractButton b = new JButton(Globals.getString(">>"));
206            b.setMargin(expandInsets);
207            b.addActionListener(new ActionListener(){
208                public void actionPerformed(ActionEvent e){
209                    boolean visible = !advancedConfig.isVisible();
210                    ((JButton) e.getSource()).setText(visible? Globals.getString("<<") : Globals.getString(">>"));
211                    advancedConfig.setVisible(visible);
212                }
213            });
214            self.add(b, BorderLayout.NORTH);
215    
216    
217            /* link stdin->console and thread->console settings */
218            b = stdin.getButton(ExternalApplication.CONSOLE);
219            b.addActionListener(new ActionListener(){
220                public void actionPerformed(ActionEvent e){
221                    JRadioButton bb = (JRadioButton) e.getSource();
222                    if(app.getThread() != ExternalApplication.CONSOLE &&
223                       bb.isSelected()){
224                        int result = JOptionPane.showConfirmDialog(
225                            ExternalApplicationPanel.this,
226                            Globals.getString("CONSOLE_THREAD_MSG"),
227                            Globals.getString("RUN_IN_CONSOLE_THREAD"),
228                            JOptionPane.YES_NO_OPTION);
229                        if(result == JOptionPane.YES_OPTION){
230                            app.setThread(ExternalApplication.CONSOLE);
231                            consoleThread.setSelected(true);
232                        } else {
233                            stdin.getButton(stdin.getOption()).setSelected(true);
234                        }
235                    }
236                }
237            });
238    
239            return self;
240        }
241    
242        private Component buildThreadTab(){
243            final String mp3dings = String.valueOf(ExternalApplication.MP3DINGS);
244            final String console = String.valueOf(ExternalApplication.CONSOLE);
245            final String custom = String.valueOf(ExternalApplication.CUSTOM);
246    
247            /* re-usable handles */
248            ButtonGroup choice;
249            ActionListener listener;
250    
251            Box tab = Box.createVerticalBox();
252            tab.setBorder(BorderFactory.createEmptyBorder(2,5,2,5));
253            choice = new ButtonGroup();
254            listener = new ActionListener(){
255                public void actionPerformed(ActionEvent e){
256                    int newThread = Integer.parseInt(e.getActionCommand());
257                    if((app.getThread() == ExternalApplication.CONSOLE) &&
258                            (stdin.getOption() == ExternalApplication.CONSOLE) &&
259                            (newThread != ExternalApplication.CONSOLE) ){
260                        int result = JOptionPane.showConfirmDialog(
261                        ExternalApplicationPanel.this,
262                        Globals.getString("CONSOLE_INPUT_MSG"),
263                        Globals.getString("DISABLE_INPUT_FROM_CONSOLE"),
264                        JOptionPane.YES_NO_OPTION);
265                        if(result == JOptionPane.YES_OPTION){
266                            stdin.getButton(ExternalApplication.NONE).doClick();
267                            app.setThread(newThread);
268                        } else {
269                            consoleThread.doClick();
270                        }
271                    } else {
272                        app.setThread(newThread);
273                    }
274                }
275            };
276            tab.add(new JLabel(Globals.getString("RUN_PROGRAM_IN")));
277            tab.add(makeButton(
278                Globals.getString("BACKGROUND"),
279                custom,
280                choice,
281                listener,
282                app.getThread() == ExternalApplication.CUSTOM
283            ));
284            consoleThread = makeButton(
285                Globals.getString("CONSOLE_EXECUTION_THREAD"),
286                console,
287                choice,
288                listener,
289                app.getThread() == ExternalApplication.CONSOLE
290            );
291            tab.add(consoleThread);
292            tab.add(makeButton(
293                Globals.getString("MP3DINGS_EVENT_THREAD_DISCOURAGED"),
294                mp3dings,
295                choice,
296                listener,
297                app.getThread() == ExternalApplication.MP3DINGS
298            ));
299            // tab.setBackground(Color.white);
300            // tab.setOpaque(true);
301            return tab;
302        }
303    
304        private Component buildIoTabs(){
305            JBook io =  new JBook();
306            boolean[] show = new boolean[]{true,false,true,true};
307            stdin = new IoTab(Globals.getString("READ_INPUT_FROM"),
308                    app.getInput(),
309                    app.getInputPath(),
310                    show);
311            io.add(stdin,
312                    Globals.getString("INPUT"),
313                    Globals.getKeyObject("INPUT_MNEMONIC"));
314            show[1] = true;
315            stdout = new IoTab(Globals.getString("WRITE_OUTPUT_TO"),
316                    app.getOutput(),
317                    app.getOutputPath(),
318                    show);
319            io.add(stdout,
320                    Globals.getString("OUTPUT"),
321                    Globals.getKeyObject("OUTPUT_MNEMONIC"));
322            stderr = new IoTab(Globals.getString("WRITE_ERRORS_TO"),
323                    app.getErrorOutput(),
324                    app.getErrorOutputPath(),
325                    show);
326            io.add(stderr,
327                Globals.getString("ERRORS"),
328                Globals.getKeyObject("ERRORS_MNEMONIC"));
329            // io.setBackground(Color.white);
330            // io.setOpaque(true);
331            return io;
332        }
333    
334        private Component buildCallModeTab(){
335            final String mp3dings = String.valueOf(ExternalApplication.MP3DINGS);
336            final String console = String.valueOf(ExternalApplication.CONSOLE);
337            final String custom = String.valueOf(ExternalApplication.CUSTOM);
338    
339            /* re-usable handles */
340            ButtonGroup choice;
341            ActionListener listener;
342    
343            /* runMp3ButtonPane */
344            JPanel buttonPane = new JPanel();
345            choice = new ButtonGroup();
346            listener = new ActionListener(){
347                public void actionPerformed(ActionEvent e){
348                    int newCallMode = Integer.parseInt(e.getActionCommand());
349                    if(newCallMode != app.getCallMode() &&
350                            newCallMode == ExternalApplication.PLAYLIST){
351                        Object val = JOptionPane.showInputDialog(
352                            ExternalApplicationPanel.this,
353                            Globals.getString("PLEASE_SELECT_A_PLAYLIST_TYPE"),
354                            Globals.getString("PREFS_RUN_MP3_PLAYLIST"),
355                            JOptionPane.QUESTION_MESSAGE,
356                            null,
357                            EXPNAMES,
358                            EXPNAMES[app.getExporter()]);
359                        if (val != null){
360                            String str = val.toString();
361                            for (int i = 0; i< EXPNAMES.length; i++){
362                                if (str.equals(EXPNAMES[i])){
363                                    app.setExporter(i);
364                                    break;
365                                }
366                            }
367                        }
368                    }
369                    app.setCallMode(newCallMode);
370                }
371            };
372            buttonPane.setBorder(new EmptyBorder(5,0,0,0));
373            buttonPane.setLayout(new GridLayout(3,1));
374            //buttonPane.setOpaque(false);
375            buttonPane.setAlignmentX(Component.LEFT_ALIGNMENT);
376            buttonPane.add(makeButton(
377                Globals.getString("PREFS_RUN_MP3_SINGLE_FILE"),
378                String.valueOf(ExternalApplication.SINGLE_FILE),
379                choice,
380                listener,
381                app.getCallMode() == ExternalApplication.SINGLE_FILE
382            ));
383            buttonPane.add(makeButton(
384                Globals.getString("PREFS_RUN_MP3_FILE_LIST"),
385                String.valueOf(ExternalApplication.FILE_LIST),
386                choice,
387                listener,
388                app.getCallMode() == ExternalApplication.FILE_LIST
389            ));
390            buttonPane.add(makeButton(
391                Globals.getString("PREFS_RUN_MP3_LOOP"),
392                String.valueOf(ExternalApplication.LOOP),
393                choice,
394                listener,
395                app.getCallMode() == ExternalApplication.LOOP
396            ));
397            buttonPane.add(makeButton(
398                Globals.getString("PREFS_RUN_MP3_PLAYLIST"),
399                String.valueOf(ExternalApplication.PLAYLIST),
400                choice,
401                listener,
402                app.getCallMode() == ExternalApplication.PLAYLIST
403            ));
404            JPanel tmp = new JPanel(new FlowLayout(FlowLayout.LEFT));
405            // tmp.setBackground(Color.white);
406            // tmp.setOpaque(true);
407            tmp.setAlignmentX(Component.LEFT_ALIGNMENT);
408            tmp.add(buttonPane);
409            return tmp;
410        }
411    
412        private Component buildWorkingDirectoryTab(){
413            ButtonGroup choice;
414            ActionListener listener;
415            final String mp3dings = String.valueOf(ExternalApplication.MP3DINGS);
416            final String console = String.valueOf(ExternalApplication.CONSOLE);
417            final String custom = String.valueOf(ExternalApplication.CUSTOM);
418    
419            pwd = new PathInput(app.getWorkingDirectoryPath(), JFileChooser.DIRECTORIES_ONLY);
420            pwd.setAlignmentX(Component.LEFT_ALIGNMENT);
421            listener = new ActionListener(){
422                public void actionPerformed(ActionEvent e){
423                    app.setWorkingDirectory(Integer.parseInt(e.getActionCommand()));
424                    if(app.getWorkingDirectory() == ExternalApplication.CUSTOM){
425                        pwd.setEnabled(true);
426                    } else {
427                        pwd.setEnabled(false);
428                    }
429                }
430            };
431            Box tab = Box.createVerticalBox();
432            tab.setBorder(BorderFactory.createEmptyBorder(2,5,2,5));
433            tab.add(new JLabel(Globals.getString("SELECT_A_WORKING_DIRECTORY")));
434            choice = new ButtonGroup();
435            tab.add(makeButton(
436                Globals.getString("SAME_AS_MP3DINGS"),
437                mp3dings,
438                choice,
439                listener,
440                app.getWorkingDirectory() == ExternalApplication.MP3DINGS
441            ));
442            tab.add(makeButton(
443                Globals.getString("SAME_AS_CONSOLE"),
444                console,
445                choice,
446                listener,
447                app.getWorkingDirectory() == ExternalApplication.CONSOLE
448            ));
449            tab.add(makeButton(
450                Globals.getString("CUSTOM"),
451                custom,
452                choice,
453                listener,
454                app.getWorkingDirectory() == ExternalApplication.CUSTOM
455            ));
456            tab.add(pwd);
457            pwd.setEnabled(app.getWorkingDirectory() == ExternalApplication.CUSTOM);
458            // tab.setBackground(Color.white);
459            // tab.setOpaque(true);
460            return tab;
461        }
462    
463        public void save(){
464            if(!exe.getPath().equals("")){
465                getExternalApplication().save(getPrefs(),id);
466            }
467        }
468    
469        public ExternalApplication getExternalApplication(){
470            app.setName(getName());
471            app.setExePath(exe.getPath());
472            app.setWorkingDirectoryPath(pwd.getPath());
473            app.setOutput(stdout.getOption());
474            app.setOutputPath(stdout.getPath());
475            app.setInput(stdin.getOption());
476            app.setInputPath(stdin.getPath());
477            app.setErrorOutput(stderr.getOption());
478            app.setErrorOutputPath(stderr.getPath());
479            return new ExternalApplication(app);
480        }
481    
482        private static class IoTab extends Box{
483            private PathInput path;
484            private int option;
485    
486            public IoTab(String description, int opt, String path, boolean[] show){
487                super(BoxLayout.Y_AXIS);
488                final String mp3dings = String.valueOf(ExternalApplication.MP3DINGS);
489                final String console = String.valueOf(ExternalApplication.CONSOLE);
490                final String custom = String.valueOf(ExternalApplication.CUSTOM);
491                ButtonGroup choice = new ButtonGroup();
492                JRadioButton jrb;
493                option = opt;
494                //setOpaque(true);
495                //setBackground(Color.white);
496                setBorder(BorderFactory.createEmptyBorder(2,5,2,5));
497                ActionListener listener = new ActionListener(){
498                    public void actionPerformed(ActionEvent e){
499                        option = Integer.parseInt(e.getActionCommand());
500                        if(option == ExternalApplication.CUSTOM){
501                            IoTab.this.path.setEnabled(true);
502                        } else {
503                            IoTab.this.path.setEnabled(false);
504                        }
505                    }
506                };
507                if(description != null){
508                    add(new JLabel(description));
509                }
510                if(show[0]){
511                    add(makeButton(
512                        description.equals(Globals.getString("READ_INPUT_FROM"))
513                            ? Globals.getString("NO_INPUT")
514                            : Globals.getString("NULL_DEVICE"),
515                        String.valueOf(ExternalApplication.NONE),
516                        choice,
517                        listener,
518                        option == ExternalApplication.NONE));
519                }
520                if(show[1]){
521                    add(makeButton(
522                        Globals.getString("SYSTEM_IO"),
523                        String.valueOf(ExternalApplication.MP3DINGS),
524                        choice,
525                        listener,
526                        option == ExternalApplication.MP3DINGS));
527                }
528                if(show[2]){
529                    add(makeButton(
530                        Globals.getString("MP3DINGS_CONSOLE"),
531                        String.valueOf(ExternalApplication.CONSOLE),
532                        choice,
533                        listener,
534                        (option == ExternalApplication.CONSOLE)));
535                }
536                if(show[3]){
537                    add(makeButton(
538                        Globals.getString("FILE"),
539                        String.valueOf(ExternalApplication.CUSTOM),
540                        choice,
541                        listener,
542                        (option == ExternalApplication.CUSTOM)));
543                    this.path = new PathInput(path);
544                    this.path.setEnabled((option == ExternalApplication.CUSTOM));
545                    this.path.setAlignmentX(Component.LEFT_ALIGNMENT);
546                    add(this.path);
547    
548                }
549                add(Box.createVerticalGlue());
550            }
551    
552            public int getOption(){
553                return option;
554            }
555    
556            public String getPath(){
557                return path.getPath();
558            }
559    
560            public JRadioButton getButton(int option){
561                String sopt = String.valueOf(option);
562                Component[] children = getComponents();
563                JRadioButton b;
564                for(int i=0; i<children.length; i++){
565                    if(children[i] instanceof JRadioButton){
566                        b = (JRadioButton) children[i];
567                        if(b.getActionCommand().equals(sopt)){
568                            return b;
569                        }
570                    }
571                }
572                return null;
573            }
574        }
575    
576        private static JRadioButton makeButton(String title, String command, ButtonGroup g, ActionListener l, boolean selected){
577            JRadioButton jrb = new JRadioButton(title);
578            jrb.setActionCommand(command);
579            if(l != null){
580            jrb.addActionListener(l);
581            }
582            g.add(jrb);
583            jrb.setSelected(selected);
584            jrb.setAlignmentX(Component.LEFT_ALIGNMENT);
585            // jrb.setBackground(Color.white);
586            return jrb;
587        }
588    
589        protected PathInput getExeInput(){
590            return exe;
591        }
592    
593        private static JRadioButton makeButton(String title, String command, ButtonGroup g, ActionListener l){
594            return makeButton(title,command,g,l,false);
595        }
596    }