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