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