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