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