JAL-1355
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import java.awt.FlowLayout;
24 import java.awt.Frame;
25 import java.awt.event.ActionEvent;
26 import java.awt.event.ActionListener;
27 import java.io.BufferedReader;
28 import java.io.File;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.io.OutputStreamWriter;
32 import java.io.PrintWriter;
33 import java.lang.reflect.Constructor;
34 import java.net.URI;
35 import java.net.URL;
36 import java.net.URLDecoder;
37 import java.security.AllPermission;
38 import java.security.CodeSource;
39 import java.security.PermissionCollection;
40 import java.security.Permissions;
41 import java.security.Policy;
42 import java.util.*;
43
44 import javax.swing.*;
45
46 import jalview.gui.*;
47 import jalview.util.MessageManager;
48 import jalview.util.Platform;
49
50 /**
51  * Main class for Jalview Application <br>
52  * <br>
53  * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
54  * 
55  * @author $author$
56  * @version $Revision$
57  */
58 public class Jalview
59 {
60   static
61   {
62     // grab all the rights we can the JVM
63     Policy.setPolicy(new Policy()
64     {
65       public PermissionCollection getPermissions(CodeSource codesource)
66       {
67         Permissions perms = new Permissions();
68         perms.add(new AllPermission());
69         return (perms);
70       }
71
72       public void refresh()
73       {
74       }
75     });
76   }
77
78   /**
79    * Put protein=true for get a protein example
80    */
81   private static boolean protein = false;
82
83   /**
84    * main class for Jalview application
85    * 
86    * @param args
87    *          open <em>filename</em>
88    */
89   public static void main(String[] args)
90   {
91     System.out.println("Java version: "
92             + System.getProperty("java.version"));
93     System.out.println(System.getProperty("os.arch") + " "
94             + System.getProperty("os.name") + " "
95             + System.getProperty("os.version"));
96     if (new Platform().isAMac())
97     {
98       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
99               "Jalview");
100       System.setProperty("apple.laf.useScreenMenuBar", "true");
101     }
102
103     ArgsParser aparser = new ArgsParser(args);
104     boolean headless = false;
105
106     if (aparser.contains("help") || aparser.contains("h"))
107     {
108       System.out
109               .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
110                       + "-nodisplay\tRun Jalview without User Interface.\n"
111                       + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
112                       + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
113                       + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
114                       + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
115                       + "-features FILE\tUse the given file to mark features on the alignment.\n"
116                       + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
117                       + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
118                       + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
119                       + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
120                       + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
121                       + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
122                       + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
123                       + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
124                       + "-png FILE\tCreate PNG image FILE from alignment.\n"
125                       + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
126                       + "-eps FILE\tCreate EPS file FILE from alignment.\n"
127                       + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
128                       + "-noquestionnaire\tTurn off questionnaire check.\n"
129                       + "-nousagestats\tTurn off google analytics tracking for this session.\n"
130                       + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
131                       // +
132                       // "-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)"
133                       + "-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"
134                       + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
135                       + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
136                       + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
137                       // +
138                       // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
139                       // + "-vses vamsas-session\tJoin session with given URN\n"
140                       + "-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"
141                       + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
142       System.exit(0);
143     }
144     if (aparser.contains("nodisplay") || aparser.contains("nogui")
145             || aparser.contains("headless"))
146     {
147       System.setProperty("java.awt.headless", "true");
148       headless = true;
149     }
150     Cache.loadProperties(aparser.getValue("props")); // must do this before
151     // anything else!
152     String defs = aparser.getValue("setprop");
153     while (defs != null)
154     {
155       int p = defs.indexOf('=');
156       if (p == -1)
157       {
158         System.err.println("Ignoring invalid setprop argument : " + defs);
159       }
160       else
161       {
162         System.out.println("Executing setprop argument: " + defs);
163         // DISABLED FOR SECURITY REASONS
164         // TODO: add a property to allow properties to be overriden by cli args
165         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
166       }
167       defs = aparser.getValue("setprop");
168     }
169     if (System.getProperty("java.awt.headless") != null
170             && System.getProperty("java.awt.headless").equals("true"))
171     {
172       headless = true;
173     }
174     System.setProperty("http.agent",
175             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
176     try
177     {
178       Cache.initLogger();
179     } catch (java.lang.NoClassDefFoundError error)
180     {
181       error.printStackTrace();
182       System.out
183               .println("\nEssential logging libraries not found."
184                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
185       System.exit(0);
186     }
187
188     Desktop desktop = null;
189
190     try
191     {
192       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
193     } catch (Exception ex)
194     {
195     }
196
197     if (!headless)
198     {
199       desktop = new Desktop();
200       desktop.setInBatchMode(true); // indicate we are starting up
201       desktop.setVisible(true);
202       desktop.startServiceDiscovery();
203       if (!aparser.contains("nousagestats"))
204       {
205         startUsageStats(desktop);
206       }
207       if (!aparser.contains("noquestionnaire"))
208       {
209         String url = aparser.getValue("questionnaire");
210         if (url != null)
211         {
212           // Start the desktop questionnaire prompter with the specified
213           // questionnaire
214           Cache.log.debug("Starting questionnaire url at " + url);
215           desktop.checkForQuestionnaire(url);
216         }
217         else
218         {
219           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
220           {
221             // Start the desktop questionnaire prompter with the specified
222             // questionnaire
223             // String defurl =
224             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
225             // //
226             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
227             Cache.log.debug("Starting questionnaire with default url: "
228                     + defurl);
229             desktop.checkForQuestionnaire(defurl);
230
231           }
232         }
233       }
234       desktop.checkForNews();
235     }
236
237     String file = null, protocol = null, format = null, data = null;
238     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
239     Vector getFeatures = null; // vector of das source nicknames to fetch
240     // features from
241     // loading is done.
242     String groovyscript = null; // script to execute after all loading is
243     // completed one way or another
244     // extract groovy argument and execute if necessary
245     groovyscript = aparser.getValue("groovy", true);
246     file = aparser.getValue("open", true);
247
248     if (file == null && desktop == null)
249     {
250       System.out.println("No files to open!");
251       System.exit(1);
252     }
253     String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
254             .getValue("vsess");
255     if (vamsasImport != null || vamsasSession != null)
256     {
257       if (desktop == null || headless)
258       {
259         System.out
260                 .println("Headless vamsas sessions not yet supported. Sorry.");
261         System.exit(1);
262       }
263       // if we have a file, start a new session and import it.
264       boolean inSession = false;
265       if (vamsasImport != null)
266       {
267         try
268         {
269           String viprotocol = jalview.io.AppletFormatAdapter
270                   .checkProtocol(vamsasImport);
271           if (viprotocol == jalview.io.FormatAdapter.FILE)
272           {
273             inSession = desktop.vamsasImport(new File(vamsasImport));
274           }
275           else if (viprotocol == jalview.io.FormatAdapter.URL)
276           {
277             inSession = desktop.vamsasImport(new URL(vamsasImport));
278           }
279
280         } catch (Exception e)
281         {
282           System.err.println("Exeption when importing " + vamsasImport
283                   + " as a vamsas document.");
284           e.printStackTrace();
285         }
286         if (!inSession)
287         {
288           System.err.println("Failed to import " + vamsasImport
289                   + " as a vamsas document.");
290         }
291         else
292         {
293           System.out.println("Imported Successfully into new session "
294                   + desktop.getVamsasApplication().getCurrentSession());
295         }
296       }
297       if (vamsasSession != null)
298       {
299         if (vamsasImport != null)
300         {
301           // close the newly imported session and import the Jalview specific
302           // remnants into the new session later on.
303           desktop.vamsasStop_actionPerformed(null);
304         }
305         // now join the new session
306         try
307         {
308           if (desktop.joinVamsasSession(vamsasSession))
309           {
310             System.out.println("Successfully joined vamsas session "
311                     + vamsasSession);
312           }
313           else
314           {
315             System.err.println("WARNING: Failed to join vamsas session "
316                     + vamsasSession);
317           }
318         } catch (Exception e)
319         {
320           System.err.println("ERROR: Failed to join vamsas session "
321                   + vamsasSession);
322           e.printStackTrace();
323         }
324         if (vamsasImport != null)
325         {
326           // the Jalview specific remnants can now be imported into the new
327           // session at the user's leisure.
328           Cache.log
329                   .info("Skipping Push for import of data into existing vamsas session."); // TODO:
330           // enable
331           // this
332           // when
333           // debugged
334           // desktop.getVamsasApplication().push_update();
335         }
336       }
337     }
338     long progress = -1;
339     // Finally, deal with the remaining input data.
340     if (file != null)
341     {
342       if (!headless)
343       {
344         desktop.setProgressBar(MessageManager.getString("status.processing_commandline_args"),
345                 progress = System.currentTimeMillis());
346       }
347       System.out.println("Opening file: " + file);
348
349       if (!file.startsWith("http://"))
350       {
351         if (!(new java.io.File(file)).exists())
352         {
353           System.out.println("Can't find " + file);
354           if (headless)
355           {
356             System.exit(1);
357           }
358         }
359       }
360
361       protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
362
363       format = new jalview.io.IdentifyFile().Identify(file, protocol);
364
365       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
366               format);
367       if (af == null)
368       {
369         System.out.println("error");
370       }
371       else
372       {
373
374         data = aparser.getValue("colour", true);
375         if (data != null)
376         {
377           data.replaceAll("%20", " ");
378
379           jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
380                   .getColour(af.getViewport().getAlignment(), data);
381
382           if (cs == null)
383           {
384             jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
385                     "white");
386             ucs.parseAppletParameter(data);
387             cs = ucs;
388           }
389
390           System.out.println("colour is " + data);
391           af.changeColour(cs);
392         }
393
394         // Must maintain ability to use the groups flag
395         data = aparser.getValue("groups", true);
396         if (data != null)
397         {
398           af.parseFeaturesFile(data,
399                   jalview.io.AppletFormatAdapter.checkProtocol(data));
400           System.out.println("Added " + data);
401         }
402         data = aparser.getValue("features", true);
403         if (data != null)
404         {
405           af.parseFeaturesFile(data,
406                   jalview.io.AppletFormatAdapter.checkProtocol(data));
407           System.out.println("Added " + data);
408         }
409
410         data = aparser.getValue("annotations", true);
411         if (data != null)
412         {
413           af.loadJalviewDataFile(data, null, null, null);
414           System.out.println("Added " + data);
415         }
416         // set or clear the sortbytree flag.
417         if (aparser.contains("sortbytree"))
418         {
419           af.getViewport().setSortByTree(true);
420         }
421         if (aparser.contains("nosortbytree"))
422         {
423           af.getViewport().setSortByTree(false);
424         }
425         data = aparser.getValue("tree", true);
426         if (data != null)
427         {
428           jalview.io.NewickFile fin = null;
429           try
430           {
431             fin = new jalview.io.NewickFile(data,
432                     jalview.io.AppletFormatAdapter.checkProtocol(data));
433             if (fin != null)
434             {
435               af.getViewport().setCurrentTree(
436                       af.ShowNewickTree(fin, data).getTree());
437               System.out.println("Added tree " + data);
438             }
439           } catch (IOException ex)
440           {
441             System.err.println("Couldn't add tree " + data);
442             ex.printStackTrace(System.err);
443           }
444         }
445         // TODO - load PDB structure(s) to alignment JAL-629
446         // (associate with identical sequence in alignment, or a specified
447         // sequence)
448
449         getFeatures = checkDasArguments(aparser);
450         if (af != null && getFeatures != null)
451         {
452           FeatureFetcher ff = startFeatureFetching(getFeatures);
453           if (ff != null)
454             while (!ff.allFinished() || af.operationInProgress())
455             {
456               // wait around until fetching is finished.
457               try
458               {
459                 Thread.sleep(100);
460               } catch (Exception e)
461               {
462
463               }
464             }
465           getFeatures = null; // have retrieved features - forget them now.
466         }
467         if (groovyscript != null)
468         {
469           // Execute the groovy script after we've done all the rendering stuff
470           // and before any images or figures are generated.
471           if (jalview.bin.Cache.groovyJarsPresent())
472           {
473             System.out.println("Executing script " + groovyscript);
474             executeGroovyScript(groovyscript, new Object[]
475             { desktop, af });
476           }
477           else
478           {
479             System.err
480                     .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
481                             + groovyscript);
482           }
483           groovyscript = null;
484         }
485         String imageName = "unnamed.png";
486         while (aparser.getSize() > 1)
487         {
488           format = aparser.nextValue();
489           file = aparser.nextValue();
490
491           if (format.equalsIgnoreCase("png"))
492           {
493             af.createPNG(new java.io.File(file));
494             imageName = (new java.io.File(file)).getName();
495             System.out.println("Creating PNG image: " + file);
496             continue;
497           }
498           else if (format.equalsIgnoreCase("imgMap"))
499           {
500             af.createImageMap(new java.io.File(file), imageName);
501             System.out.println("Creating image map: " + file);
502             continue;
503           }
504           else if (format.equalsIgnoreCase("eps"))
505           {
506             System.out.println("Creating EPS file: " + file);
507             af.createEPS(new java.io.File(file));
508             continue;
509           }
510
511           if (af.saveAlignment(file, format))
512           {
513             System.out.println("Written alignment in " + format
514                     + " format to " + file);
515           }
516           else
517           {
518             System.out.println("Error writing file " + file + " in "
519                     + format + " format!!");
520           }
521
522         }
523
524         while (aparser.getSize() > 0)
525         {
526           System.out.println("Unknown arg: " + aparser.nextValue());
527         }
528       }
529     }
530     AlignFrame startUpAlframe = null;
531     // We'll only open the default file if the desktop is visible.
532     // And the user
533     // ////////////////////
534
535     if (!headless && file == null && vamsasImport == null
536             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true)
537             && protein == true)
538     {
539       file = jalview.bin.Cache.getDefault(
540               "STARTUP_FILE",
541               jalview.bin.Cache.getDefault("www.jalview.org",
542                       "http://www.jalview.org")
543                       + "/examples/exampleFile_2_7.jar");
544       if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar"))
545       {
546         // hardwire upgrade of the startup file
547         file.replace("_2_3.jar", "_2_7.jar");
548         // and remove the stale setting
549         jalview.bin.Cache.removeProperty("STARTUP_FILE");
550       }
551
552       protocol = "File";
553
554       if (file.indexOf("http:") > -1)
555       {
556         protocol = "URL";
557       }
558
559       if (file.endsWith(".jar"))
560       {
561         format = "Jalview";
562       }
563       else
564       {
565         format = new jalview.io.IdentifyFile().Identify(file, protocol);
566       }
567
568       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
569               format);
570       getFeatures = checkDasArguments(aparser);
571       // extract groovy arguments before anything else.
572     }
573     // If the user has specified features to be retrieved,
574     // or a groovy script to be executed, do them if they
575     // haven't been done already
576     // fetch features for the default alignment
577     if (getFeatures != null)
578     {
579       if (startUpAlframe != null)
580       {
581         startFeatureFetching(getFeatures);
582       }
583     }
584     // Once all other stuff is done, execute any groovy scripts (in order)
585     if (groovyscript != null)
586     {
587       if (jalview.bin.Cache.groovyJarsPresent())
588       {
589         System.out.println("Executing script " + groovyscript);
590         executeGroovyScript(groovyscript, new Object[]
591         { desktop, startUpAlframe });
592       }
593       else
594       {
595         System.err
596                 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
597                         + groovyscript);
598       }
599     }
600     // and finally, turn off batch mode indicator - if the desktop still exists
601     if (desktop != null)
602     {
603       if (progress != -1)
604       {
605         desktop.setProgressBar(null, progress);
606       }
607       desktop.setInBatchMode(false);
608     }
609   }
610
611   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 {
925   public void actionPerformed(ActionEvent arg0)
926   {
927     System.out.println("Good idea ! ");
928
929   }
930 }
931
932 class pbuttonlistener implements ActionListener
933 {
934   public void actionPerformed(ActionEvent arg0)
935   {
936
937   }
938 }
939
940 class ArgsParser
941 {
942   Vector vargs = null;
943
944   public ArgsParser(String[] args)
945   {
946     vargs = new Vector();
947     for (int i = 0; i < args.length; i++)
948     {
949       String arg = args[i].trim();
950       if (arg.charAt(0) == '-')
951       {
952         arg = arg.substring(1);
953       }
954       vargs.addElement(arg);
955     }
956   }
957
958   /**
959    * check for and remove first occurence of arg+parameter in arglist.
960    * 
961    * @param arg
962    * @return return the argument following the given arg if arg was in list.
963    */
964   public String getValue(String arg)
965   {
966     return getValue(arg, false);
967   }
968
969   public String getValue(String arg, boolean utf8decode)
970   {
971     int index = vargs.indexOf(arg);
972     String dc = null, ret = null;
973     if (index != -1)
974     {
975       ret = vargs.elementAt(index + 1).toString();
976       vargs.removeElementAt(index);
977       vargs.removeElementAt(index);
978       if (utf8decode && ret != null)
979       {
980         try
981         {
982           dc = URLDecoder.decode(ret, "UTF-8");
983           ret = dc;
984         } catch (Exception e)
985         {
986           // TODO: log failure to decode
987         }
988       }
989     }
990     return ret;
991   }
992
993   /**
994    * check for and remove first occurence of arg in arglist.
995    * 
996    * @param arg
997    * @return true if arg was present in argslist.
998    */
999   public boolean contains(String arg)
1000   {
1001     if (vargs.contains(arg))
1002     {
1003       vargs.removeElement(arg);
1004       return true;
1005     }
1006     else
1007     {
1008       return false;
1009     }
1010   }
1011
1012   public String nextValue()
1013   {
1014     return vargs.remove(0).toString();
1015   }
1016
1017   public int getSize()
1018   {
1019     return vargs.size();
1020   }
1021
1022 }
1023
1024 /**
1025  * keep track of feature fetching tasks.
1026  * 
1027  * @author JimP
1028  * 
1029  */
1030 class FeatureFetcher
1031 {
1032   /*
1033    * TODO: generalise to track all jalview events to orchestrate batch
1034    * processing events.
1035    */
1036
1037   private int queued = 0;
1038
1039   private int running = 0;
1040
1041   public FeatureFetcher()
1042   {
1043
1044   }
1045
1046   public void addFetcher(final AlignFrame af, final Vector dasSources)
1047   {
1048     final long id = System.currentTimeMillis();
1049     queued++;
1050     final FeatureFetcher us = this;
1051     new Thread(new Runnable()
1052     {
1053
1054       public void run()
1055       {
1056         synchronized (us)
1057         {
1058           queued--;
1059           running++;
1060         }
1061
1062         af.setProgressBar(MessageManager.getString("status.das_features_being_retrived"), id);
1063         af.featureSettings_actionPerformed(null);
1064         af.featureSettings.fetchDasFeatures(dasSources, true);
1065         af.setProgressBar(null, id);
1066         synchronized (us)
1067         {
1068           running--;
1069         }
1070       }
1071     }).start();
1072   }
1073
1074   public synchronized boolean allFinished()
1075   {
1076     return queued == 0 && running == 0;
1077   }
1078
1079 };