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