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