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