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