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