JAL-1605 added command line support for html export option
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import jalview.gui.AlignFrame;
24 import jalview.gui.Desktop;
25 import jalview.io.HtmlSvgOutput;
26 import jalview.util.MessageManager;
27 import jalview.util.Platform;
28 import jalview.ws.jws2.Jws2Discoverer;
29
30 import java.awt.event.ActionEvent;
31 import java.awt.event.ActionListener;
32 import java.io.BufferedReader;
33 import java.io.File;
34 import java.io.FileOutputStream;
35 import java.io.IOException;
36 import java.io.OutputStreamWriter;
37 import java.io.PrintWriter;
38 import java.lang.reflect.Constructor;
39 import java.net.MalformedURLException;
40 import java.net.URI;
41 import java.net.URL;
42 import java.net.URLDecoder;
43 import java.security.AllPermission;
44 import java.security.CodeSource;
45 import java.security.PermissionCollection;
46 import java.security.Permissions;
47 import java.security.Policy;
48 import java.util.Hashtable;
49 import java.util.Map;
50 import java.util.Vector;
51
52 import javax.swing.UIManager;
53
54 /**
55  * Main class for Jalview Application <br>
56  * <br>
57  * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
58  * 
59  * @author $author$
60  * @version $Revision$
61  */
62 public class Jalview
63 {
64   static
65   {
66     // grab all the rights we can the JVM
67     Policy.setPolicy(new Policy()
68     {
69       public PermissionCollection getPermissions(CodeSource codesource)
70       {
71         Permissions perms = new Permissions();
72         perms.add(new AllPermission());
73         return (perms);
74       }
75
76       public void refresh()
77       {
78       }
79     });
80   }
81
82   /**
83    * Put protein=true for get a protein example
84    */
85   private static boolean protein = false;
86
87   /**
88    * main class for Jalview application
89    * 
90    * @param args
91    *          open <em>filename</em>
92    */
93   public static void main(String[] args)
94   {
95     System.out.println("Java version: "
96             + System.getProperty("java.version"));
97     System.out.println(System.getProperty("os.arch") + " "
98             + System.getProperty("os.name") + " "
99             + System.getProperty("os.version"));
100     if (new Platform().isAMac())
101     {
102       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
103               "Jalview");
104       System.setProperty("apple.laf.useScreenMenuBar", "true");
105     }
106
107     ArgsParser aparser = new ArgsParser(args);
108     boolean headless = false;
109
110     if (aparser.contains("help") || aparser.contains("h"))
111     {
112       showUsage();
113       System.exit(0);
114     }
115     if (aparser.contains("nodisplay") || aparser.contains("nogui")
116             || aparser.contains("headless"))
117     {
118       System.setProperty("java.awt.headless", "true");
119       headless = true;
120     }
121     Cache.loadProperties(aparser.getValue("props")); // must do this before
122     // anything else!
123
124     final String jabawsUrl = aparser.getValue("jabaws");
125     if (jabawsUrl != null)
126     {
127       try
128       {
129         Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
130       } catch (MalformedURLException e)
131       {
132         System.err.println("Invalid jabaws parameter: " + jabawsUrl
133                 + " ignored");
134       }
135     }
136
137     String defs = aparser.getValue("setprop");
138     while (defs != null)
139     {
140       int p = defs.indexOf('=');
141       if (p == -1)
142       {
143         System.err.println("Ignoring invalid setprop argument : " + defs);
144       }
145       else
146       {
147         System.out.println("Executing setprop argument: " + defs);
148         // DISABLED FOR SECURITY REASONS
149         // TODO: add a property to allow properties to be overriden by cli args
150         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
151       }
152       defs = aparser.getValue("setprop");
153     }
154     if (System.getProperty("java.awt.headless") != null
155             && System.getProperty("java.awt.headless").equals("true"))
156     {
157       headless = true;
158     }
159     System.setProperty("http.agent",
160             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
161     try
162     {
163       Cache.initLogger();
164     } catch (java.lang.NoClassDefFoundError error)
165     {
166       error.printStackTrace();
167       System.out
168               .println("\nEssential logging libraries not found."
169                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
170       System.exit(0);
171     }
172
173     Desktop desktop = null;
174
175     try
176     {
177       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
178     } catch (Exception ex)
179     {
180     }
181
182     if (!headless)
183     {
184       desktop = new Desktop();
185       desktop.setInBatchMode(true); // indicate we are starting up
186       desktop.setVisible(true);
187       desktop.startServiceDiscovery();
188       if (!aparser.contains("nousagestats"))
189       {
190         startUsageStats(desktop);
191       }
192       if (!aparser.contains("noquestionnaire"))
193       {
194         String url = aparser.getValue("questionnaire");
195         if (url != null)
196         {
197           // Start the desktop questionnaire prompter with the specified
198           // questionnaire
199           Cache.log.debug("Starting questionnaire url at " + url);
200           desktop.checkForQuestionnaire(url);
201         }
202         else
203         {
204           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
205           {
206             // Start the desktop questionnaire prompter with the specified
207             // questionnaire
208             // String defurl =
209             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
210             // //
211             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
212             Cache.log.debug("Starting questionnaire with default url: "
213                     + defurl);
214             desktop.checkForQuestionnaire(defurl);
215
216           }
217         }
218       }
219       desktop.checkForNews();
220     }
221
222     String file = null, protocol = null, format = null, data = null;
223     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
224     Vector getFeatures = null; // vector of das source nicknames to fetch
225     // features from
226     // loading is done.
227     String groovyscript = null; // script to execute after all loading is
228     // completed one way or another
229     // extract groovy argument and execute if necessary
230     groovyscript = aparser.getValue("groovy", true);
231     file = aparser.getValue("open", true);
232
233     if (file == null && desktop == null)
234     {
235       System.out.println("No files to open!");
236       System.exit(1);
237     }
238     String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
239             .getValue("vsess");
240     if (vamsasImport != null || vamsasSession != null)
241     {
242       if (desktop == null || headless)
243       {
244         System.out
245                 .println("Headless vamsas sessions not yet supported. Sorry.");
246         System.exit(1);
247       }
248       // if we have a file, start a new session and import it.
249       boolean inSession = false;
250       if (vamsasImport != null)
251       {
252         try
253         {
254           String viprotocol = jalview.io.AppletFormatAdapter
255                   .checkProtocol(vamsasImport);
256           if (viprotocol == jalview.io.FormatAdapter.FILE)
257           {
258             inSession = desktop.vamsasImport(new File(vamsasImport));
259           }
260           else if (viprotocol == jalview.io.FormatAdapter.URL)
261           {
262             inSession = desktop.vamsasImport(new URL(vamsasImport));
263           }
264
265         } catch (Exception e)
266         {
267           System.err.println("Exeption when importing " + vamsasImport
268                   + " as a vamsas document.");
269           e.printStackTrace();
270         }
271         if (!inSession)
272         {
273           System.err.println("Failed to import " + vamsasImport
274                   + " as a vamsas document.");
275         }
276         else
277         {
278           System.out.println("Imported Successfully into new session "
279                   + desktop.getVamsasApplication().getCurrentSession());
280         }
281       }
282       if (vamsasSession != null)
283       {
284         if (vamsasImport != null)
285         {
286           // close the newly imported session and import the Jalview specific
287           // remnants into the new session later on.
288           desktop.vamsasStop_actionPerformed(null);
289         }
290         // now join the new session
291         try
292         {
293           if (desktop.joinVamsasSession(vamsasSession))
294           {
295             System.out.println("Successfully joined vamsas session "
296                     + vamsasSession);
297           }
298           else
299           {
300             System.err.println("WARNING: Failed to join vamsas session "
301                     + vamsasSession);
302           }
303         } catch (Exception e)
304         {
305           System.err.println("ERROR: Failed to join vamsas session "
306                   + vamsasSession);
307           e.printStackTrace();
308         }
309         if (vamsasImport != null)
310         {
311           // the Jalview specific remnants can now be imported into the new
312           // session at the user's leisure.
313           Cache.log
314                   .info("Skipping Push for import of data into existing vamsas session."); // TODO:
315           // enable
316           // this
317           // when
318           // debugged
319           // desktop.getVamsasApplication().push_update();
320         }
321       }
322     }
323     long progress = -1;
324     // Finally, deal with the remaining input data.
325     if (file != null)
326     {
327       if (!headless)
328       {
329         desktop.setProgressBar(MessageManager.getString("status.processing_commandline_args"),
330                 progress = System.currentTimeMillis());
331       }
332       System.out.println("Opening file: " + file);
333
334       if (!file.startsWith("http://"))
335       {
336         if (!(new java.io.File(file)).exists())
337         {
338           System.out.println("Can't find " + file);
339           if (headless)
340           {
341             System.exit(1);
342           }
343         }
344       }
345
346       protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
347
348       format = new jalview.io.IdentifyFile().Identify(file, protocol);
349
350       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
351               format);
352       if (af == null)
353       {
354         System.out.println("error");
355       }
356       else
357       {
358
359         data = aparser.getValue("colour", true);
360         if (data != null)
361         {
362           data.replaceAll("%20", " ");
363
364           jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
365                   .getColour(af.getViewport().getAlignment(), data);
366
367           if (cs == null)
368           {
369             jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
370                     "white");
371             ucs.parseAppletParameter(data);
372             cs = ucs;
373           }
374
375           System.out.println("colour is " + data);
376           af.changeColour(cs);
377         }
378
379         // Must maintain ability to use the groups flag
380         data = aparser.getValue("groups", true);
381         if (data != null)
382         {
383           af.parseFeaturesFile(data,
384                   jalview.io.AppletFormatAdapter.checkProtocol(data));
385           System.out.println("Added " + data);
386         }
387         data = aparser.getValue("features", true);
388         if (data != null)
389         {
390           af.parseFeaturesFile(data,
391                   jalview.io.AppletFormatAdapter.checkProtocol(data));
392           System.out.println("Added " + data);
393         }
394
395         data = aparser.getValue("annotations", true);
396         if (data != null)
397         {
398           af.loadJalviewDataFile(data, null, null, null);
399           System.out.println("Added " + data);
400         }
401         // set or clear the sortbytree flag.
402         if (aparser.contains("sortbytree"))
403         {
404           af.getViewport().setSortByTree(true);
405         }
406         if (aparser.contains("nosortbytree"))
407         {
408           af.getViewport().setSortByTree(false);
409         }
410         data = aparser.getValue("tree", true);
411         if (data != null)
412         {
413           jalview.io.NewickFile fin = null;
414           try
415           {
416             fin = new jalview.io.NewickFile(data,
417                     jalview.io.AppletFormatAdapter.checkProtocol(data));
418             if (fin != null)
419             {
420               af.getViewport().setCurrentTree(
421                       af.ShowNewickTree(fin, data).getTree());
422               System.out.println("Added tree " + data);
423             }
424           } catch (IOException ex)
425           {
426             System.err.println("Couldn't add tree " + data);
427             ex.printStackTrace(System.err);
428           }
429         }
430         // TODO - load PDB structure(s) to alignment JAL-629
431         // (associate with identical sequence in alignment, or a specified
432         // sequence)
433
434         getFeatures = checkDasArguments(aparser);
435         if (af != null && getFeatures != null)
436         {
437           FeatureFetcher ff = startFeatureFetching(getFeatures);
438           if (ff != null)
439           {
440             while (!ff.allFinished() || af.operationInProgress())
441             {
442               // wait around until fetching is finished.
443               try
444               {
445                 Thread.sleep(100);
446               } catch (Exception e)
447               {
448
449               }
450             }
451           }
452           getFeatures = null; // have retrieved features - forget them now.
453         }
454         if (groovyscript != null)
455         {
456           // Execute the groovy script after we've done all the rendering stuff
457           // and before any images or figures are generated.
458           if (jalview.bin.Cache.groovyJarsPresent())
459           {
460             System.out.println("Executing script " + groovyscript);
461             executeGroovyScript(groovyscript, new Object[]
462             { desktop, af });
463           }
464           else
465           {
466             System.err
467                     .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
468                             + groovyscript);
469           }
470           groovyscript = null;
471         }
472         String imageName = "unnamed.png";
473         while (aparser.getSize() > 1)
474         {
475           format = aparser.nextValue();
476           file = aparser.nextValue();
477
478           if (format.equalsIgnoreCase("png"))
479           {
480             af.createPNG(new java.io.File(file));
481             imageName = (new java.io.File(file)).getName();
482             System.out.println("Creating PNG image: " + file);
483             continue;
484           }
485           else if (format.equalsIgnoreCase("svg"))
486           {
487             File imageFile = new java.io.File(file);
488             imageName = imageFile.getName();
489             af.createSVG(imageFile);
490             System.out.println("Creating SVG image: " + file);
491             continue;
492           }
493           else if (format.equalsIgnoreCase("html"))
494           {
495             File imageFile = new java.io.File(file);
496             imageName = imageFile.getName();
497             new HtmlSvgOutput(new java.io.File(file), af.alignPanel);
498             System.out.println("Creating HTML image: " + file);
499             continue;
500           }
501           else if (format.equalsIgnoreCase("imgMap"))
502           {
503             af.createImageMap(new java.io.File(file), imageName);
504             System.out.println("Creating image map: " + file);
505             continue;
506           }
507           else if (format.equalsIgnoreCase("eps"))
508           {
509             System.out.println("Creating EPS file: " + file);
510             af.createEPS(new java.io.File(file));
511             continue;
512           }
513
514           if (af.saveAlignment(file, format))
515           {
516             System.out.println("Written alignment in " + format
517                     + " format to " + file);
518           }
519           else
520           {
521             System.out.println("Error writing file " + file + " in "
522                     + format + " format!!");
523           }
524
525         }
526
527         while (aparser.getSize() > 0)
528         {
529           System.out.println("Unknown arg: " + aparser.nextValue());
530         }
531       }
532     }
533     AlignFrame startUpAlframe = null;
534     // We'll only open the default file if the desktop is visible.
535     // And the user
536     // ////////////////////
537
538     if (!headless && file == null && vamsasImport == null
539             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true)
540             && protein == true)
541     {
542       file = jalview.bin.Cache.getDefault(
543               "STARTUP_FILE",
544               jalview.bin.Cache.getDefault("www.jalview.org",
545                       "http://www.jalview.org")
546                       + "/examples/exampleFile_2_7.jar");
547       if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar"))
548       {
549         // hardwire upgrade of the startup file
550         file.replace("_2_3.jar", "_2_7.jar");
551         // and remove the stale setting
552         jalview.bin.Cache.removeProperty("STARTUP_FILE");
553       }
554
555       protocol = "File";
556
557       if (file.indexOf("http:") > -1)
558       {
559         protocol = "URL";
560       }
561
562       if (file.endsWith(".jar"))
563       {
564         format = "Jalview";
565       }
566       else
567       {
568         format = new jalview.io.IdentifyFile().Identify(file, protocol);
569       }
570
571       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
572               format);
573       getFeatures = checkDasArguments(aparser);
574       // extract groovy arguments before anything else.
575     }
576     // If the user has specified features to be retrieved,
577     // or a groovy script to be executed, do them if they
578     // haven't been done already
579     // fetch features for the default alignment
580     if (getFeatures != null)
581     {
582       if (startUpAlframe != null)
583       {
584         startFeatureFetching(getFeatures);
585       }
586     }
587     // Once all other stuff is done, execute any groovy scripts (in order)
588     if (groovyscript != null)
589     {
590       if (jalview.bin.Cache.groovyJarsPresent())
591       {
592         System.out.println("Executing script " + groovyscript);
593         executeGroovyScript(groovyscript, new Object[]
594         { desktop, startUpAlframe });
595       }
596       else
597       {
598         System.err
599                 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
600                         + groovyscript);
601       }
602     }
603     // and finally, turn off batch mode indicator - if the desktop still exists
604     if (desktop != null)
605     {
606       if (progress != -1)
607       {
608         desktop.setProgressBar(null, progress);
609       }
610       desktop.setInBatchMode(false);
611     }
612   }
613
614   private static void showUsage()
615   {
616     System.out
617             .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
618                     + "-nodisplay\tRun Jalview without User Interface.\n"
619                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
620                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
621                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
622                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
623                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
624                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
625                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
626                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
627                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
628                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
629                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
630                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
631                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
632                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
633                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
634                     + "-html FILE\tCreate HTML file from alignment.\n"
635                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
636                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
637                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
638                     + "-noquestionnaire\tTurn off questionnaire check.\n"
639                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
640                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
641                     // +
642                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property, after all other properties files have been read\n\t (quote the 'PROPERTY=VALUE' pair to ensure spaces are passed in correctly)"
643                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
644                     + "-dasserver nickname=URL\tAdd and enable a das server with given nickname\n\t\t\t(alphanumeric or underscores only) for retrieval of features for all alignments.\n"
645                     + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
646                     + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
647                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
648                     // +
649                     // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
650                     // + "-vses vamsas-session\tJoin session with given URN\n"
651                     + "-groovy FILE\tExecute groovy script in FILE, after all other arguments have been processed (if FILE is the text 'STDIN' then the file will be read from STDIN)\n"
652                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
653   }
654
655   private static void startUsageStats(final Desktop desktop)
656   {
657     /**
658      * start a User Config prompt asking if we can log usage statistics.
659      */
660     jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
661             desktop.desktop,
662             "USAGESTATS",
663             "Jalview Usage Statistics",
664             "Do you want to help make Jalview better by enabling "
665                     + "the collection of usage statistics with Google Analytics ?"
666                     + "\n\n(you can enable or disable usage tracking in the preferences)",
667             new Runnable()
668             {
669               public void run()
670               {
671                 Cache.log
672                         .info("Initialising googletracker for usage stats.");
673                 Cache.initGoogleTracker();
674                 Cache.log.debug("Tracking enabled.");
675               }
676             }, new Runnable()
677             {
678               public void run()
679               {
680                 Cache.log.info("Not enabling Google Tracking.");
681               }
682             }, null, true);
683     desktop.addDialogThread(prompter);
684   }
685
686   /**
687    * Locate the given string as a file and pass it to the groovy interpreter.
688    * 
689    * @param groovyscript
690    *          the script to execute
691    * @param jalviewContext
692    *          the Jalview Desktop object passed in to the groovy binding as the
693    *          'Jalview' object.
694    */
695   private static void executeGroovyScript(String groovyscript,
696           Object[] jalviewContext)
697   {
698     if (jalviewContext == null)
699     {
700       System.err
701               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
702     }
703     /**
704      * for scripts contained in files
705      */
706     File tfile = null;
707     /**
708      * script's URI
709      */
710     URL sfile = null;
711     if (groovyscript.trim().equals("STDIN"))
712     {
713       // read from stdin into a tempfile and execute it
714       try
715       {
716         tfile = File.createTempFile("jalview", "groovy");
717         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
718                 new FileOutputStream(tfile)));
719         BufferedReader br = new BufferedReader(
720                 new java.io.InputStreamReader(System.in));
721         String line = null;
722         while ((line = br.readLine()) != null)
723         {
724           outfile.write(line + "\n");
725         }
726         br.close();
727         outfile.flush();
728         outfile.close();
729
730       } catch (Exception ex)
731       {
732         System.err.println("Failed to read from STDIN into tempfile "
733                 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
734                         .toString()));
735         ex.printStackTrace();
736         return;
737       }
738       try
739       {
740         sfile = tfile.toURI().toURL();
741       } catch (Exception x)
742       {
743         System.err
744                 .println("Unexpected Malformed URL Exception for temporary file created from STDIN: "
745                         + tfile.toURI());
746         x.printStackTrace();
747         return;
748       }
749     }
750     else
751     {
752       try
753       {
754         sfile = new URI(groovyscript).toURL();
755       } catch (Exception x)
756       {
757         tfile = new File(groovyscript);
758         if (!tfile.exists())
759         {
760           System.err.println("File '" + groovyscript + "' does not exist.");
761           return;
762         }
763         if (!tfile.canRead())
764         {
765           System.err.println("File '" + groovyscript + "' cannot be read.");
766           return;
767         }
768         if (tfile.length() < 1)
769         {
770           System.err.println("File '" + groovyscript + "' is empty.");
771           return;
772         }
773         try
774         {
775           sfile = tfile.getAbsoluteFile().toURI().toURL();
776         } catch (Exception ex)
777         {
778           System.err.println("Failed to create a file URL for "
779                   + tfile.getAbsoluteFile());
780           return;
781         }
782       }
783     }
784     boolean success = false;
785     try
786     {
787       /*
788        * The following code performs the GroovyScriptEngine invocation using
789        * reflection, and is equivalent to this fragment from the embedding
790        * groovy documentation on the groovy site: <code> import
791        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
792        * 
793        * String[] roots = new String[] { "/my/groovy/script/path" };
794        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
795        * = new Binding(); binding.setVariable("input", "world");
796        * gse.run("hello.groovy", binding); </code>
797        */
798       Class[] bspec;
799       Object[] binding;
800       int blen = ((jalviewContext[0] == null) ? 0 : 1)
801               + ((jalviewContext[1] == null) ? 0 : 1);
802       String cnames[] = new String[]
803       { "Jalview", "currentAlFrame" };
804       bspec = new Class[blen * 2];
805       binding = new Object[blen * 2];
806       blen = 0;
807       ClassLoader cl = null;
808       Map vbinding = new Hashtable();
809       for (int jc = 0; jc < jalviewContext.length; jc++)
810       {
811         if (jalviewContext[jc] != null)
812         {
813           if (cl == null)
814           {
815             cl = jalviewContext[jc].getClass().getClassLoader();
816           }
817           bspec[blen * 2] = String.class;
818           bspec[blen * 2 + 1] = Object.class;
819           binding[blen * 2] = cnames[jc];
820           binding[blen * 2 + 1] = jalviewContext[jc];
821           vbinding.put(cnames[jc], jalviewContext[jc]);
822           blen++;
823         }
824       }
825       Class gbindingc = cl.loadClass("groovy.lang.Binding");
826       Constructor gbcons;
827       Object gbinding;
828       try
829       {
830         gbcons = gbindingc.getConstructor(Map.class);
831         gbinding = gbcons.newInstance(vbinding);
832       } catch (NoSuchMethodException x)
833       {
834         // old style binding config - using series of string/object values to
835         // setVariable.
836         gbcons = gbindingc.getConstructor(null);
837         gbinding = gbcons.newInstance(null);
838         java.lang.reflect.Method setvar = gbindingc.getMethod(
839                 "setVariable", bspec);
840         setvar.invoke(gbinding, binding);
841       }
842       ;
843       Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
844       Constructor gseccons = gsec.getConstructor(new Class[]
845       { URL[].class }); // String[].class });
846       Object gse = gseccons.newInstance(new Object[]
847       { new URL[]
848       { sfile } }); // .toString() } });
849       java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
850       { String.class, gbindingc });
851       run.invoke(gse, new Object[]
852       { sfile.toString(), gbinding });
853       success = true;
854     } catch (Exception e)
855     {
856       System.err.println("Exception Whilst trying to execute file " + sfile
857               + " as a groovy script.");
858       e.printStackTrace(System.err);
859
860     }
861     if (success && groovyscript.equals("STDIN"))
862     {
863       // delete temp file that we made - but only if it was successfully
864       // executed
865       tfile.delete();
866     }
867   }
868
869   /**
870    * Check commandline for any das server definitions or any fetchfrom switches
871    * 
872    * @return vector of DAS source nicknames to retrieve from
873    */
874   private static Vector checkDasArguments(ArgsParser aparser)
875   {
876     Vector source = null;
877     String data;
878     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
879     while ((data = aparser.getValue("dasserver", true)) != null)
880     {
881       String nickname = null;
882       String url = null;
883       boolean seq = false, feat = true;
884       int pos = data.indexOf('=');
885       // determine capabilities
886       if (pos > 0)
887       {
888         nickname = data.substring(0, pos);
889       }
890       url = data.substring(pos + 1);
891       if (url != null
892               && (url.startsWith("http:") || url
893                       .startsWith("sequence:http:")))
894       {
895         if (nickname == null)
896         {
897           nickname = url;
898         }
899         if (locsources == null)
900         {
901           locsources = "";
902         }
903         else
904         {
905           locsources += "\t";
906         }
907         locsources = locsources + nickname + "|" + url;
908         System.err
909                 .println("NOTE! dasserver parameter not yet really supported (got args of "
910                         + nickname + "|" + url);
911         if (source == null)
912         {
913           source = new Vector();
914         }
915         source.addElement(nickname);
916       }
917     } // loop until no more server entries are found.
918     if (locsources != null && locsources.indexOf('|') > -1)
919     {
920       Cache.log.debug("Setting local source list in properties file to:\n"
921               + locsources);
922       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
923     }
924     while ((data = aparser.getValue("fetchfrom", true)) != null)
925     {
926       System.out.println("adding source '" + data + "'");
927       if (source == null)
928       {
929         source = new Vector();
930       }
931       source.addElement(data);
932     }
933     return source;
934   }
935
936   /**
937    * start a feature fetcher for every alignment frame
938    * 
939    * @param dasSources
940    */
941   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
942   {
943     FeatureFetcher ff = new FeatureFetcher();
944     AlignFrame afs[] = Desktop.getAlignframes();
945     if (afs == null || afs.length == 0)
946     {
947       return null;
948     }
949     for (int i = 0; i < afs.length; i++)
950     {
951       ff.addFetcher(afs[i], dasSources);
952     }
953     return ff;
954   }
955 }
956
957 /**
958  * Notes: this argParser does not distinguish between parameter switches,
959  * parameter values and argument text. If an argument happens to be identical to
960  * a parameter, it will be taken as such (even though it didn't have a '-'
961  * prefixing it).
962  * 
963  * @author Andrew Waterhouse and JBP documented.
964  * 
965  */
966
967 class rnabuttonlistener implements ActionListener
968 {
969   public void actionPerformed(ActionEvent arg0)
970   {
971     System.out.println("Good idea ! ");
972
973   }
974 }
975
976 class pbuttonlistener implements ActionListener
977 {
978   public void actionPerformed(ActionEvent arg0)
979   {
980
981   }
982 }
983
984 class ArgsParser
985 {
986   Vector vargs = null;
987
988   public ArgsParser(String[] args)
989   {
990     vargs = new Vector();
991     for (int i = 0; i < args.length; i++)
992     {
993       String arg = args[i].trim();
994       if (arg.charAt(0) == '-')
995       {
996         arg = arg.substring(1);
997       }
998       vargs.addElement(arg);
999     }
1000   }
1001
1002   /**
1003    * check for and remove first occurence of arg+parameter in arglist.
1004    * 
1005    * @param arg
1006    * @return return the argument following the given arg if arg was in list.
1007    */
1008   public String getValue(String arg)
1009   {
1010     return getValue(arg, false);
1011   }
1012
1013   public String getValue(String arg, boolean utf8decode)
1014   {
1015     int index = vargs.indexOf(arg);
1016     String dc = null, ret = null;
1017     if (index != -1)
1018     {
1019       ret = vargs.elementAt(index + 1).toString();
1020       vargs.removeElementAt(index);
1021       vargs.removeElementAt(index);
1022       if (utf8decode && ret != null)
1023       {
1024         try
1025         {
1026           dc = URLDecoder.decode(ret, "UTF-8");
1027           ret = dc;
1028         } catch (Exception e)
1029         {
1030           // TODO: log failure to decode
1031         }
1032       }
1033     }
1034     return ret;
1035   }
1036
1037   /**
1038    * check for and remove first occurence of arg in arglist.
1039    * 
1040    * @param arg
1041    * @return true if arg was present in argslist.
1042    */
1043   public boolean contains(String arg)
1044   {
1045     if (vargs.contains(arg))
1046     {
1047       vargs.removeElement(arg);
1048       return true;
1049     }
1050     else
1051     {
1052       return false;
1053     }
1054   }
1055
1056   public String nextValue()
1057   {
1058     return vargs.remove(0).toString();
1059   }
1060
1061   public int getSize()
1062   {
1063     return vargs.size();
1064   }
1065
1066 }
1067
1068 /**
1069  * keep track of feature fetching tasks.
1070  * 
1071  * @author JimP
1072  * 
1073  */
1074 class FeatureFetcher
1075 {
1076   /*
1077    * TODO: generalise to track all jalview events to orchestrate batch
1078    * processing events.
1079    */
1080
1081   private int queued = 0;
1082
1083   private int running = 0;
1084
1085   public FeatureFetcher()
1086   {
1087
1088   }
1089
1090   public void addFetcher(final AlignFrame af, final Vector dasSources)
1091   {
1092     final long id = System.currentTimeMillis();
1093     queued++;
1094     final FeatureFetcher us = this;
1095     new Thread(new Runnable()
1096     {
1097
1098       public void run()
1099       {
1100         synchronized (us)
1101         {
1102           queued--;
1103           running++;
1104         }
1105
1106         af.setProgressBar(MessageManager.getString("status.das_features_being_retrived"), id);
1107         af.featureSettings_actionPerformed(null);
1108         af.featureSettings.fetchDasFeatures(dasSources, true);
1109         af.setProgressBar(null, id);
1110         synchronized (us)
1111         {
1112           running--;
1113         }
1114       }
1115     }).start();
1116   }
1117
1118   public synchronized boolean allFinished()
1119   {
1120     return queued == 0 && running == 0;
1121   }
1122
1123 };