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