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