001    package net.sourceforge.mp3dings.utils;
002    
003    /* Mp3dings - manage mp3 meta-information
004     * Copyright (C) 2003 Moritz Ringler
005     * $Id: ExternalApplication.java,v 1.18 2006/10/12 11:41:42 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.EventQueue;
023    import java.io.File;
024    import java.io.FileNotFoundException;
025    import java.io.InputStream;
026    import java.io.OutputStream;
027    import java.io.Serializable;
028    import java.lang.reflect.InvocationTargetException;
029    import java.util.prefs.Preferences;
030    import javax.swing.SwingUtilities;
031    import de.mospace.lang.ExceptionHandler;
032    import de.mospace.lang.ProcessRunnable;
033    import de.mospace.lang.RunnableQueue;
034    import net.sourceforge.mp3dings.Globals;
035    import de.mospace.swing.ProcessIOPane;
036    import java.util.logging.*;
037    
038    /**
039     */
040    public class ExternalApplication extends Bean implements Serializable{
041        private final static Logger logger = Logger.getLogger(ExternalApplication.class.getPackage().getName());
042    
043        public final static int PLAY = 0;
044        public final static int ENQUEUE = 1;
045        public final static int SYSTEM_SHELL = 2;
046        public final static int MP3DINGS = 1;
047        public final static int CONSOLE = 2;
048        public final static int CUSTOM = 3;
049        public final static int NONE = 0;
050        public final static int SINGLE_FILE = 0;
051        public final static int FILE_LIST = 1;
052        public final static int LOOP = 2;
053        public final static int PLAYLIST = 3;
054        //private final static String[] EXPORTERS = AbstractExporter.getImplementations();
055    
056        private String name = "";
057        private String sexe = "";
058        private String spwd = "";
059        private String sout = "";
060        private String serr = "";
061        private String sinp = "";
062        private int ipwd = MP3DINGS;
063        private int imode = FILE_LIST;
064        private int iexp = 0;
065        private int iout = NONE;
066        private int ierr = NONE;
067        private int iinp = NONE;
068        private int ithread = CUSTOM;
069    
070        public final static String PROPERTY_EXE_PATH = "exePath";
071        public final static String PROPERTY_WORKING_DIRECTORY = "workingDirectory";
072        public final static String PROPERTY_WORKING_DIRECTORY_PATH = "workingDirectoryPath";
073        public final static String PROPERTY_CALL_MODE = "callMode";
074        public final static String PROPERTY_EXPORTER = "exporter";
075        public final static String PROPERTY_OUTPUT = "output";
076        public final static String PROPERTY_OUTPUT_PATH = "outputPath";
077        public final static String PROPERTY_INPUT = "input";
078        public final static String PROPERTY_INPUT_PATH = "inputPath";
079        public final static String PROPERTY_ERROR_OUTPUT = "errorOutput";
080        public final static String PROPERTY_ERROR_OUTPUT_PATH = "errorOutputPath";
081        public final static String PROPERTY_THREAD = "thread";
082    
083        private final static String NEWLINE = "\n";
084        private final static String FILE_PLACEHOLDER = "%f";
085    
086        private final static ExceptionHandler defaultExceptionHandler =
087                new ExceptionHandler(){
088                    public void handleException(Throwable ex){
089                        logger.warning("Error invoking external application:");
090                        Globals.logStackTrace(logger, ex);
091                    }
092                };
093    
094    
095    
096        public ExternalApplication(){
097        }
098    
099        public ExternalApplication(ExternalApplication app){
100            setName(app.getName());
101            setExePath(app.getExePath());
102            setWorkingDirectory(app.getWorkingDirectory());
103            setWorkingDirectoryPath(app.getWorkingDirectoryPath());
104            setCallMode(app.getCallMode());
105            setExporter(app.getExporter());
106            setOutput(app.getOutput());
107            setOutputPath(app.getOutputPath());
108            setInput(app.getInput());
109            setInputPath(app.getInputPath());
110            setErrorOutput(app.getErrorOutput());
111            setErrorOutputPath(app.getErrorOutputPath());
112            setThread(app.getThread());
113        }
114    
115        public void setName(String s){
116            String oldname = name;
117            name = s;
118            firePropertyChange(PROPERTY_NAME, oldname, name);
119        }
120    
121        public String getName(){
122            return name;
123        }
124    
125        public void setExePath(String path){
126            String olds = sexe;
127            sexe = path;
128            firePropertyChange(PROPERTY_EXE_PATH, olds, name);
129        }
130    
131        public String getExePath(){
132            return sexe;
133        }
134    
135        public void setWorkingDirectory(int workingDirectory){
136            int old = ipwd;
137            ipwd = workingDirectory;
138            firePropertyChange(PROPERTY_WORKING_DIRECTORY, old, ipwd);
139        }
140    
141        public int getWorkingDirectory(){
142            return ipwd;
143        }
144    
145        public void setWorkingDirectoryPath(String pwd){
146            String old = spwd;
147            spwd = pwd;
148            firePropertyChange(PROPERTY_WORKING_DIRECTORY_PATH, old, spwd);
149        }
150    
151        public String getWorkingDirectoryPath(){
152            return spwd;
153        }
154    
155        public void setCallMode(int callMode){
156            int old = imode;
157            imode = callMode;
158            firePropertyChange(PROPERTY_CALL_MODE, old, imode);
159        }
160    
161        public int getCallMode(){
162            return imode;
163        }
164    
165        public void setExporter(int selectedExporter){
166            int old = iexp;
167            iexp = selectedExporter;
168            firePropertyChange(PROPERTY_EXPORTER, old, iexp);
169        }
170    
171        public int getExporter(){
172            return iexp;
173        }
174    
175        public void setOutput(int out){
176            int old = iout;
177            iout = out;
178            firePropertyChange(PROPERTY_OUTPUT, old, iout);
179        }
180    
181        public int getOutput(){
182            return iout;
183        }
184    
185        public void setOutputPath(String out){
186            String old = sout;
187            sout = out;
188            firePropertyChange(PROPERTY_OUTPUT_PATH, old, sout);
189        }
190    
191        public String getOutputPath(){
192            return sout;
193        }
194    
195        public void setInput(int in){
196            int old = iinp;
197            iinp = in;
198            firePropertyChange(PROPERTY_INPUT, old, iinp);
199        }
200    
201        public int getInput(){
202            return iinp;
203        }
204    
205        public void setInputPath(String in){
206            String old = sinp;
207            sinp = in;
208            firePropertyChange(PROPERTY_INPUT_PATH, old, sinp);
209        }
210    
211        public String getInputPath(){
212            return sinp;
213        }
214    
215        public void setErrorOutput(int err){
216            int old = ierr;
217            ierr = err;
218            firePropertyChange(PROPERTY_ERROR_OUTPUT, old, ierr);
219        }
220    
221        public int getErrorOutput(){
222            return ierr;
223        }
224    
225        public void setErrorOutputPath(String err){
226            String old = serr;
227            serr = err;
228            firePropertyChange(PROPERTY_ERROR_OUTPUT_PATH, old, serr);
229        }
230    
231        public String getErrorOutputPath(){
232            return serr;
233        }
234    
235        public boolean needsMp3dingsConsole(){
236            return (ierr == CONSOLE || iout == CONSOLE || iinp == CONSOLE);
237        }
238    
239        public void setThread(int thread){
240            int old = ithread;
241            ithread = thread;
242            firePropertyChange(PROPERTY_THREAD, old, ithread);
243        }
244    
245        public int getThread(){
246            return ithread;
247        }
248    
249        public String toString(){
250            StringBuffer sb = new StringBuffer(128);
251            sb.append(name).append(NEWLINE);
252            sb.append(ipwd).append(NEWLINE);
253            sb.append(imode).append(NEWLINE);
254            sb.append(iexp).append(NEWLINE);
255            sb.append(iout).append(NEWLINE);
256            sb.append(ierr).append(NEWLINE);
257            sb.append(iinp).append(NEWLINE);
258            sb.append(ithread).append(NEWLINE);
259            sb.append(sexe).append(NEWLINE);
260            sb.append(spwd).append(NEWLINE);
261            sb.append(sout).append(NEWLINE);
262            sb.append(serr).append(NEWLINE);
263            sb.append(sinp);
264            return sb.toString();
265        }
266    
267        private static ExternalApplication parseString(String str){
268            if (str == null){
269                return null;
270            }
271            String[] tokens = str.split(NEWLINE,-1);
272            if (tokens.length != 13){
273                return null;
274            }
275            int i = 0;
276            ExternalApplication app = new ExternalApplication();
277            try{
278            app.setName(tokens[i++]);
279            app.setWorkingDirectory(Integer.parseInt(tokens[i++]));
280            app.setCallMode(Integer.parseInt(tokens[i++]));
281            app.setExporter(Integer.parseInt(tokens[i++]));
282            app.setOutput(Integer.parseInt(tokens[i++]));
283            app.setErrorOutput(Integer.parseInt(tokens[i++]));
284            app.setInput(Integer.parseInt(tokens[i++]));
285            app.setThread(Integer.parseInt(tokens[i++]));
286            } catch (NumberFormatException ex){
287                logger.severe("Error initializing external application " + str);
288                logger.severe(ex.toString());
289                return null;
290            }
291            app.setExePath(tokens[i++]);
292            app.setWorkingDirectoryPath(tokens[i++]);
293            app.setOutputPath(tokens[i++]);
294            app.setErrorOutputPath(tokens[i++]);
295            app.setInputPath(tokens[i++]);
296            return app;
297        }
298    
299        public static ExternalApplication load(Preferences prefs, int id){
300            return parseString(prefs.get(String.valueOf(id), null));
301        }
302    
303        public static ExternalApplication load(int id){
304            return load(getPrefNode(), id);
305        }
306    
307        public void save(int id){
308            save(getPrefNode(), id);
309        }
310    
311        public void save(Preferences prefs, int id){
312            prefs.put(String.valueOf(id), toString());
313        }
314    
315        public static int getUnusedId(){
316            int id;
317            for(id=0; getPrefNode().get(String.valueOf(id), null) != null; id++);
318            return id;
319        }
320    
321        public boolean equals(Object o){
322            if (this == o){
323                return true;
324            }
325            if(!(o instanceof ExternalApplication)){
326                return false;
327            }
328            ExternalApplication app = (ExternalApplication) o;
329            return
330                ipwd == app.getWorkingDirectory() &&
331                imode == app.getCallMode() &&
332                iexp == app.getExporter() &&
333                iout == app.getOutput() &&
334                ierr == app.getErrorOutput() &&
335                iinp == app.getInput() &&
336                ithread == app.getThread() &&
337                (sexe== null ? app.getExePath() == null : sexe.equals(app.getExePath())) &&
338                (spwd== null ? app.getWorkingDirectoryPath() == null : spwd.equals(app.getWorkingDirectoryPath())) &&
339                (sout== null ? app.getOutputPath() == null : sout.equals(app.getOutputPath())) &&
340                (serr== null ? app.getErrorOutputPath() == null : serr.equals(app.getErrorOutputPath())) &&
341                (sinp== null)? app.getInputPath() == null : sinp.equals(app.getInputPath());
342        }
343    
344        public static Preferences getPrefNode(){
345            return Globals.getPrefNode().node("ExternalApplications");
346        }
347    
348        public int hashCode(){
349            int result = 19;
350            result = 37 * result + ipwd;
351            result = 37 * result + imode;
352            result = 37 * result + iexp;
353            result = 37 * result + iout;
354            result = 37 * result + ierr;
355            result = 37 * result + iinp;
356            result = 37 * result + ithread;
357            result = 37 * result + ((sexe == null)? 0 : sexe.hashCode());
358            result = 37 * result + ((spwd == null)? 0 : spwd.hashCode());
359            result = 37 * result + ((sout == null)? 0 : sout.hashCode());
360            result = 37 * result + ((serr == null)? 0 : serr.hashCode());
361            result = 37 * result + ((sinp == null)? 0 : sinp.hashCode());
362            return result;
363        }
364    
365        public void execute(File[] files, ProcessIOPane console) throws FileNotFoundException{
366            execute(files, console, defaultExceptionHandler);
367        }
368    
369        public void execute(File[] files, ProcessIOPane console,
370            ExceptionHandler exceptionHandler)
371            throws FileNotFoundException{
372                execute(files, console, exceptionHandler, null);
373        }
374    
375        /**
376         * @param runWhenDone is executed (in a new thread) when the external application terminates
377        **/
378        public void execute(File[] files, ProcessIOPane console,
379            ExceptionHandler exceptionHandler, Runnable runWhenDone)
380        throws FileNotFoundException{
381            int fileCount = 0;
382            int n = files.length;
383            int mode = (n==0)? SINGLE_FILE : getCallMode();
384            // if( n == 0){
385                // return;
386            // }
387            //Preferences prefs = Globals.getPrefNode();
388            String cmd = getExePath();
389            /* append "%f" if necessary */
390            //if( cmd.indexOf("%f") == -1){
391                //cmd += " %f";
392            //}
393            if( cmd.indexOf(FILE_PLACEHOLDER) == -1){
394                files = new File[0];
395                n = 0;
396                mode = SINGLE_FILE;
397            }
398            /* parse the command (hard-coded as we don't want
399             * to split a filename containing blanks into separate tokens)
400             */
401            String[] commandTokens = cmd.split(" ");
402            String[][] commands = new String[][]{{""}};
403            int nCommandTokens = commandTokens.length;
404            /* find the command token containing FILE_PLACEHOLDER */
405            int iFileToken;
406            for (iFileToken = 0; iFileToken < nCommandTokens; iFileToken++){
407                if(commandTokens[iFileToken].indexOf(FILE_PLACEHOLDER) != -1){
408                    break;
409                }
410            }
411            switch (mode) {
412            case FILE_LIST: /* call once with list of selected files */
413            /* create an array of file tokens with %f replaced by the
414                     * actual filenames */
415                    String ff[] = new String[n];
416                    for(int i = 0; i<files.length; i++){
417                        ff[i] = replFirst(commandTokens[iFileToken],
418                                         FILE_PLACEHOLDER, getCanPath(files[i]));
419                        fileCount++;
420                    }
421    
422                    /* create an array of the commandTokens with %f replaced
423                     * by the list of filenames in commands[0]*/
424                    commands[0] = new String[nCommandTokens-1+ff.length];
425    
426                    /* copy first part of command unchanged */
427                    System.arraycopy(commandTokens, 0,
428                                     commands[0], 0,
429                                     iFileToken);
430    
431                    /* copy file tokens */
432                    System.arraycopy(ff, 0,
433                                     commands[0], iFileToken,
434                                     ff.length);
435    
436                    /* copy last part of command unchanged */
437                    System.arraycopy(commandTokens, iFileToken+1,
438                                     commands[0], iFileToken+ff.length,
439                                     nCommandTokens-(iFileToken+1));
440                    break;
441    
442            case LOOP: /* call with each selected file */
443                    commands = new String[n][nCommandTokens];
444                    /* create array of commands with %f replaced by the file name,
445                     * one command for each file */
446                    for(int i = 0; i<n; i++){
447                        System.arraycopy(commandTokens, 0, commands[i], 0,
448                                         nCommandTokens);
449                        commands[i][iFileToken] = replFirst(commands[i][iFileToken],
450                                FILE_PLACEHOLDER, getCanPath(files[i]));
451                        fileCount++;
452                    }
453                    break;
454    
455            default: /* call with tmp playlist or with first selected file */
456                 String f = (n==0)? "": getCanPath(files[0]);
457                /* call with just one file */
458                 commands[0] = new String[nCommandTokens];
459                 System.arraycopy(commandTokens, 0, commands[0], 0, nCommandTokens);
460                 if(iFileToken < commands[0].length){
461                     commands[0][iFileToken] = replFirst(commands[0][iFileToken],
462                     FILE_PLACEHOLDER, f);
463                 }
464                 fileCount++;
465                 break;
466            }
467    
468            /* execute commands */
469    
470            /* Creates new ProcessRunnables from the command strings. */
471            ProcessRunnable[] jobs = new ProcessRunnable[commands.length];
472            for(int i = 0; i<commands.length; i++){
473                jobs[i] = new ProcessRunnable(commands[i]);
474                configureJob(jobs[i], console);
475            }
476    
477            /* run in correct thread */
478            if(getThread() == CONSOLE){
479                RunnableQueue rq = console.getRunnableQueue();
480                for(int i=0; i<jobs.length;i++){
481                    rq.enqueue(jobs[i]);
482                } if (!rq.isRunning()){
483                    rq.start();
484                }
485            } else {
486                final RunnableQueue rq = new RunnableQueue();
487                for(int i=0; i<jobs.length;i++){
488                    rq.enqueue(jobs[i]);
489                }
490                rq.registerExceptionHandler(exceptionHandler);
491                if(getThread() == MP3DINGS){
492                    if (EventQueue.isDispatchThread()) {
493                        rq.run();
494                    } else {
495                        try{
496                        SwingUtilities.invokeAndWait(new Runnable() {
497                            public void run() {
498                                rq.run();
499                            }
500                        });
501                        } catch (InterruptedException ex){
502                            logger.warning("Interrupted");
503                            exceptionHandler.handleException(ex);
504                        } catch (InvocationTargetException ex){
505                            logger.warning("InvocationTarget");
506                            exceptionHandler.handleException(ex);
507                        }
508                    }
509                } else if (getThread() == CUSTOM){
510                    rq.start();
511                } else {
512                    exceptionHandler.handleException(
513                    new IllegalArgumentException("Unknown or illegal value for thread ("+
514                        getThread()+")!"));
515                    return;
516                }
517            }
518    
519            if(runWhenDone != null){
520                (new RunWhenDoneThread(runWhenDone, jobs[commands.length-1])).start();
521            }
522        }
523    
524        private void configureJob(ProcessRunnable job, ProcessIOPane console)
525            throws FileNotFoundException{
526            /* set Working Directory */
527            String strvar = null;
528            switch(getWorkingDirectory()){
529                case MP3DINGS:
530                    strvar = null;
531                    break;
532                case CONSOLE:
533                    strvar = console.getWorkingDirectory();
534                    break;
535                case CUSTOM:
536                    strvar = getWorkingDirectoryPath();
537                    break;
538                default:
539                    strvar = null;
540            }
541            job.setWorkingDirectory((strvar == null)? null : new File(strvar));
542    
543            /* set Output */
544            switch(getOutput()){
545                case MP3DINGS:
546                    job.redirectOutputTo(System.out);
547                    break;
548                case NONE:
549                    job.redirectOutputTo((OutputStream) null);
550                    break;
551                case CONSOLE:
552                    job.redirectOutputTo(console.getOutputStream());
553                    break;
554                case CUSTOM:
555                    job.redirectOutputTo(new File(getOutputPath()));
556                    break;
557                default:
558                    job.redirectOutputTo((OutputStream) null);
559            }
560    
561            /* set ErrorStream */
562            switch(getErrorOutput()){
563                case MP3DINGS:
564                    job.redirectErrorsTo(System.out);
565                    break;
566                case NONE:
567                    job.redirectErrorsTo((OutputStream) null);
568                    break;
569                case CONSOLE:
570                    job.redirectErrorsTo(console.getOutputStream());
571                    break;
572                case CUSTOM:
573                    job.redirectErrorsTo(new File(getErrorOutputPath()));
574                    break;
575                default:
576                    job.redirectErrorsTo((OutputStream) null);
577            }
578    
579            /* set Input */
580            switch(getInput()){
581                case NONE:
582                    job.readInputFrom((InputStream) null);
583                    break;
584                case CONSOLE:
585                    job.clearInput(); /* console will provide input */
586                    break;
587                case CUSTOM:
588                    job.readInputFrom(new File(getInputPath()));
589                    break;
590                default:;
591            }
592        }
593    
594        /** Returns the canonical path of the File f or the empty string
595        * in case of an IOException in f.getCanonicalPath(). **/
596        private static String getCanPath(File f){
597            String s;
598            try {
599                s = f.getCanonicalPath();
600            } catch (java.io.IOException ex){
601                s = "";
602            }
603            return s;
604        }
605    
606        /** Custom-made replaceFirst function
607         * String's replaceFirst doesn't work as it
608         * messes up the backslashes in the replacement
609         * string
610         */
611        private static String replFirst(String str, String regexp, String repl){
612            String[] s = str.split(regexp,2);
613            s[0] += repl;
614            if (s.length == 2){
615                s[0] += s[1];
616            }
617            return s[0];
618        }
619    
620        private static class RunWhenDoneThread extends Thread{
621            private Runnable rwd;
622            private ProcessRunnable pr;
623    
624            /** This thread waits for the ProcessRunnable pr to finish its job
625             * to run the Runnable rwd.
626             **/
627            public RunWhenDoneThread(Runnable rwd, ProcessRunnable pr){
628                super();
629                this.rwd = rwd;
630                this.pr = pr;
631            }
632    
633            public void run(){
634                try{
635                    pr.waitFor();
636                    rwd.run();
637                } catch (Exception ex){
638                    logger.warning("Exception in RunWhenDoneThread:");
639                    Globals.logStackTrace(logger, ex);
640                }
641            }
642        }
643    }