JAL-3111 report build type and commit in stdout from command line and in About/Splash...
[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
128      * processing 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     String appdirString = System.getProperty("getdownappdir");
209     if (appdirString != null && appdirString.length() > 0)
210     {
211       final File appdir = new File(appdirString);
212       new Thread()
213       {
214         @Override
215         public void run()
216         {
217           LaunchUtil.upgradeGetdown(
218                   new File(appdir, "getdown-launcher-old.jar"),
219                   new File(appdir, "getdown-launcher.jar"),
220                   new File(appdir, "getdown-launcher-new.jar"));
221         }
222       }.start();
223
224     }
225     ArgsParser aparser = new ArgsParser(args);
226     boolean headless = false;
227
228     if (aparser.contains("help") || aparser.contains("h"))
229     {
230       showUsage();
231       System.exit(0);
232     }
233     if (aparser.contains("nodisplay") || aparser.contains("nogui")
234             || aparser.contains("headless"))
235     {
236       System.setProperty("java.awt.headless", "true");
237       headless = true;
238     }
239     String usrPropsFile = aparser.getValue("props");
240     Cache.loadProperties(usrPropsFile); // must do this before
241     if (usrPropsFile != null)
242     {
243       System.out.println(
244               "CMD [-props " + usrPropsFile + "] executed successfully!");
245     }
246
247     // anything else!
248
249     final String jabawsUrl = aparser.getValue("jabaws");
250     if (jabawsUrl != null)
251     {
252       try
253       {
254         Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
255         System.out.println(
256                 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
257       } catch (MalformedURLException e)
258       {
259         System.err.println(
260                 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
261       }
262     }
263
264     String defs = aparser.getValue("setprop");
265     while (defs != null)
266     {
267       int p = defs.indexOf('=');
268       if (p == -1)
269       {
270         System.err.println("Ignoring invalid setprop argument : " + defs);
271       }
272       else
273       {
274         System.out.println("Executing setprop argument: " + defs);
275         // DISABLED FOR SECURITY REASONS
276         // TODO: add a property to allow properties to be overriden by cli args
277         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
278       }
279       defs = aparser.getValue("setprop");
280     }
281     if (System.getProperty("java.awt.headless") != null
282             && System.getProperty("java.awt.headless").equals("true"))
283     {
284       headless = true;
285     }
286     System.setProperty("http.agent",
287             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
288     try
289     {
290       Cache.initLogger();
291     } catch (NoClassDefFoundError error)
292     {
293       error.printStackTrace();
294       System.out.println("\nEssential logging libraries not found."
295               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
296       System.exit(0);
297     }
298
299     desktop = null;
300
301     try
302     {
303       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
304     } catch (Exception ex)
305     {
306       System.err.println("Unexpected Look and Feel Exception");
307       ex.printStackTrace();
308     }
309     if (Platform.isAMac())
310     {
311
312       LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
313               .getLookAndFeel();
314       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
315               "Jalview");
316       System.setProperty("apple.laf.useScreenMenuBar", "true");
317       if (lookAndFeel != null)
318       {
319         try
320         {
321           UIManager.setLookAndFeel(lookAndFeel);
322         } catch (Throwable e)
323         {
324           System.err.println(
325                   "Failed to set QuaQua look and feel: " + e.toString());
326         }
327       }
328       if (lookAndFeel == null || !(lookAndFeel.getClass()
329               .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
330               || !UIManager.getLookAndFeel().getClass().toString()
331                       .toLowerCase().contains("quaqua"))
332       {
333         try
334         {
335           System.err.println(
336                   "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
337           UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
338         } catch (Throwable e)
339         {
340           System.err.println(
341                   "Failed to reset look and feel: " + e.toString());
342         }
343       }
344     }
345
346     /*
347      * configure 'full' SO model if preferences say to, 
348      * else use the default (SO Lite)
349      */
350     if (Cache.getDefault("USE_FULL_SO", false))
351     {
352       SequenceOntologyFactory.setInstance(new SequenceOntology());
353     }
354
355     if (!headless)
356     {
357       desktop = new Desktop();
358       desktop.setInBatchMode(true); // indicate we are starting up
359
360       try
361       {
362         JalviewTaskbar.setTaskbar(this);
363       } catch (Exception e)
364       {
365         System.out.println("Cannot set Taskbar");
366         // e.printStackTrace();
367       } catch (Throwable t)
368       {
369         System.out.println("Cannot set Taskbar");
370         // t.printStackTrace();
371       }
372
373       desktop.setVisible(true);
374       desktop.startServiceDiscovery();
375       if (!aparser.contains("nousagestats"))
376       {
377         startUsageStats(desktop);
378       }
379       else
380       {
381         System.err.println("CMD [-nousagestats] executed successfully!");
382       }
383
384       if (!aparser.contains("noquestionnaire"))
385       {
386         String url = aparser.getValue("questionnaire");
387         if (url != null)
388         {
389           // Start the desktop questionnaire prompter with the specified
390           // questionnaire
391           Cache.log.debug("Starting questionnaire url at " + url);
392           desktop.checkForQuestionnaire(url);
393           System.out.println(
394                   "CMD questionnaire[-" + url + "] executed successfully!");
395         }
396         else
397         {
398           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
399           {
400             // Start the desktop questionnaire prompter with the specified
401             // questionnaire
402             // String defurl =
403             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
404             // //
405             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
406             Cache.log.debug(
407                     "Starting questionnaire with default url: " + defurl);
408             desktop.checkForQuestionnaire(defurl);
409           }
410         }
411       }
412       else
413       {
414         System.err.println("CMD [-noquestionnaire] executed successfully!");
415       }
416
417       if (!aparser.contains("nonews"))
418       {
419         desktop.checkForNews();
420       }
421
422       BioJsHTMLOutput.updateBioJS();
423     }
424
425     String file = null, data = null;
426     FileFormatI format = null;
427     DataSourceType protocol = null;
428     FileLoader fileLoader = new FileLoader(!headless);
429
430     String groovyscript = null; // script to execute after all loading is
431     // completed one way or another
432     // extract groovy argument and execute if necessary
433     groovyscript = aparser.getValue("groovy", true);
434     file = aparser.getValue("open", true);
435
436     if (file == null && desktop == null)
437     {
438       System.out.println("No files to open!");
439       System.exit(1);
440     }
441     String vamsasImport = aparser.getValue("vdoc");
442     String vamsasSession = aparser.getValue("vsess");
443     if (vamsasImport != null || vamsasSession != null)
444     {
445       if (desktop == null || headless)
446       {
447         System.out.println(
448                 "Headless vamsas sessions not yet supported. Sorry.");
449         System.exit(1);
450       }
451       // if we have a file, start a new session and import it.
452       boolean inSession = false;
453       if (vamsasImport != null)
454       {
455         try
456         {
457           DataSourceType viprotocol = AppletFormatAdapter
458                   .checkProtocol(vamsasImport);
459           if (viprotocol == DataSourceType.FILE)
460           {
461             inSession = desktop.vamsasImport(new File(vamsasImport));
462           }
463           else if (viprotocol == DataSourceType.URL)
464           {
465             inSession = desktop.vamsasImport(new URL(vamsasImport));
466           }
467
468         } catch (Exception e)
469         {
470           System.err.println("Exeption when importing " + vamsasImport
471                   + " as a vamsas document.");
472           e.printStackTrace();
473         }
474         if (!inSession)
475         {
476           System.err.println("Failed to import " + vamsasImport
477                   + " as a vamsas document.");
478         }
479         else
480         {
481           System.out.println("Imported Successfully into new session "
482                   + desktop.getVamsasApplication().getCurrentSession());
483         }
484       }
485       if (vamsasSession != null)
486       {
487         if (vamsasImport != null)
488         {
489           // close the newly imported session and import the Jalview specific
490           // remnants into the new session later on.
491           desktop.vamsasStop_actionPerformed(null);
492         }
493         // now join the new session
494         try
495         {
496           if (desktop.joinVamsasSession(vamsasSession))
497           {
498             System.out.println(
499                     "Successfully joined vamsas session " + vamsasSession);
500           }
501           else
502           {
503             System.err.println("WARNING: Failed to join vamsas session "
504                     + vamsasSession);
505           }
506         } catch (Exception e)
507         {
508           System.err.println(
509                   "ERROR: Failed to join vamsas session " + vamsasSession);
510           e.printStackTrace();
511         }
512         if (vamsasImport != null)
513         {
514           // the Jalview specific remnants can now be imported into the new
515           // session at the user's leisure.
516           Cache.log.info(
517                   "Skipping Push for import of data into existing vamsas session."); // TODO:
518           // enable
519           // this
520           // when
521           // debugged
522           // desktop.getVamsasApplication().push_update();
523         }
524       }
525     }
526     long progress = -1;
527     // Finally, deal with the remaining input data.
528     if (file != null)
529     {
530       if (!headless)
531       {
532         desktop.setProgressBar(
533                 MessageManager
534                         .getString("status.processing_commandline_args"),
535                 progress = System.currentTimeMillis());
536       }
537       System.out.println("CMD [-open " + file + "] executed successfully!");
538
539       if (!file.startsWith("http://"))
540       {
541         if (!(new File(file)).exists())
542         {
543           System.out.println("Can't find " + file);
544           if (headless)
545           {
546             System.exit(1);
547           }
548         }
549       }
550
551       protocol = AppletFormatAdapter.checkProtocol(file);
552
553       try
554       {
555         format = new IdentifyFile().identify(file, protocol);
556       } catch (FileFormatException e1)
557       {
558         // TODO ?
559       }
560
561       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
562               format);
563       if (af == null)
564       {
565         System.out.println("error");
566       }
567       else
568       {
569         setCurrentAlignFrame(af);
570         data = aparser.getValue("colour", true);
571         if (data != null)
572         {
573           data.replaceAll("%20", " ");
574
575           ColourSchemeI cs = ColourSchemeProperty
576                   .getColourScheme(af.getViewport(),
577                           af.getViewport().getAlignment(), data);
578
579           if (cs != null)
580           {
581             System.out.println(
582                     "CMD [-color " + data + "] executed successfully!");
583           }
584           af.changeColour(cs);
585         }
586
587         // Must maintain ability to use the groups flag
588         data = aparser.getValue("groups", true);
589         if (data != null)
590         {
591           af.parseFeaturesFile(data,
592                   AppletFormatAdapter.checkProtocol(data));
593           // System.out.println("Added " + data);
594           System.out.println(
595                   "CMD groups[-" + data + "]  executed successfully!");
596         }
597         data = aparser.getValue("features", true);
598         if (data != null)
599         {
600           af.parseFeaturesFile(data,
601                   AppletFormatAdapter.checkProtocol(data));
602           // System.out.println("Added " + data);
603           System.out.println(
604                   "CMD [-features " + data + "]  executed successfully!");
605         }
606
607         data = aparser.getValue("annotations", true);
608         if (data != null)
609         {
610           af.loadJalviewDataFile(data, null, null, null);
611           // System.out.println("Added " + data);
612           System.out.println(
613                   "CMD [-annotations " + data + "] executed successfully!");
614         }
615         // set or clear the sortbytree flag.
616         if (aparser.contains("sortbytree"))
617         {
618           af.getViewport().setSortByTree(true);
619           if (af.getViewport().getSortByTree())
620           {
621             System.out.println("CMD [-sortbytree] executed successfully!");
622           }
623         }
624         if (aparser.contains("no-annotation"))
625         {
626           af.getViewport().setShowAnnotation(false);
627           if (!af.getViewport().isShowAnnotation())
628           {
629             System.out.println("CMD no-annotation executed successfully!");
630           }
631         }
632         if (aparser.contains("nosortbytree"))
633         {
634           af.getViewport().setSortByTree(false);
635           if (!af.getViewport().getSortByTree())
636           {
637             System.out
638                     .println("CMD [-nosortbytree] executed successfully!");
639           }
640         }
641         data = aparser.getValue("tree", true);
642         if (data != null)
643         {
644           try
645           {
646             System.out.println(
647                     "CMD [-tree " + data + "] executed successfully!");
648             NewickFile nf = new NewickFile(data,
649                     AppletFormatAdapter.checkProtocol(data));
650             af.getViewport()
651                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
652           } catch (IOException ex)
653           {
654             System.err.println("Couldn't add tree " + data);
655             ex.printStackTrace(System.err);
656           }
657         }
658         // TODO - load PDB structure(s) to alignment JAL-629
659         // (associate with identical sequence in alignment, or a specified
660         // sequence)
661         if (groovyscript != null)
662         {
663           // Execute the groovy script after we've done all the rendering stuff
664           // and before any images or figures are generated.
665           System.out.println("Executing script " + groovyscript);
666           executeGroovyScript(groovyscript, af);
667           System.out.println("CMD groovy[" + groovyscript
668                   + "] executed successfully!");
669           groovyscript = null;
670         }
671         String imageName = "unnamed.png";
672         while (aparser.getSize() > 1)
673         {
674           String outputFormat = aparser.nextValue();
675           file = aparser.nextValue();
676
677           if (outputFormat.equalsIgnoreCase("png"))
678           {
679             af.createPNG(new File(file));
680             imageName = (new File(file)).getName();
681             System.out.println("Creating PNG image: " + file);
682             continue;
683           }
684           else if (outputFormat.equalsIgnoreCase("svg"))
685           {
686             File imageFile = new File(file);
687             imageName = imageFile.getName();
688             af.createSVG(imageFile);
689             System.out.println("Creating SVG image: " + file);
690             continue;
691           }
692           else if (outputFormat.equalsIgnoreCase("html"))
693           {
694             File imageFile = new File(file);
695             imageName = imageFile.getName();
696             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
697             htmlSVG.exportHTML(file);
698
699             System.out.println("Creating HTML image: " + file);
700             continue;
701           }
702           else if (outputFormat.equalsIgnoreCase("biojsmsa"))
703           {
704             if (file == null)
705             {
706               System.err.println("The output html file must not be null");
707               return;
708             }
709             try
710             {
711               BioJsHTMLOutput.refreshVersionInfo(
712                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
713             } catch (URISyntaxException e)
714             {
715               e.printStackTrace();
716             }
717             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
718             bjs.exportHTML(file);
719             System.out
720                     .println("Creating BioJS MSA Viwer HTML file: " + file);
721             continue;
722           }
723           else if (outputFormat.equalsIgnoreCase("imgMap"))
724           {
725             af.createImageMap(new File(file), imageName);
726             System.out.println("Creating image map: " + file);
727             continue;
728           }
729           else if (outputFormat.equalsIgnoreCase("eps"))
730           {
731             File outputFile = new File(file);
732             System.out.println(
733                     "Creating EPS file: " + outputFile.getAbsolutePath());
734             af.createEPS(outputFile);
735             continue;
736           }
737
738           if (af.saveAlignment(file, format))
739           {
740             System.out.println("Written alignment in " + format
741                     + " format to " + file);
742           }
743           else
744           {
745             System.out.println("Error writing file " + file + " in "
746                     + format + " format!!");
747           }
748
749         }
750
751         while (aparser.getSize() > 0)
752         {
753           System.out.println("Unknown arg: " + aparser.nextValue());
754         }
755       }
756     }
757     AlignFrame startUpAlframe = null;
758     // We'll only open the default file if the desktop is visible.
759     // And the user
760     // ////////////////////
761
762     if (!headless && file == null && vamsasImport == null
763             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
764     {
765       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
766               jalview.bin.Cache.getDefault("www.jalview.org",
767                       "http://www.jalview.org")
768                       + "/examples/exampleFile_2_7.jar");
769       if (file.equals(
770               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
771       {
772         // hardwire upgrade of the startup file
773         file.replace("_2_3.jar", "_2_7.jar");
774         // and remove the stale setting
775         jalview.bin.Cache.removeProperty("STARTUP_FILE");
776       }
777
778       protocol = DataSourceType.FILE;
779
780       if (file.indexOf("http:") > -1)
781       {
782         protocol = DataSourceType.URL;
783       }
784
785       if (file.endsWith(".jar"))
786       {
787         format = FileFormat.Jalview;
788       }
789       else
790       {
791         try
792         {
793           format = new IdentifyFile().identify(file, protocol);
794         } catch (FileFormatException e)
795         {
796           // TODO what?
797         }
798       }
799
800       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
801               format);
802       // extract groovy arguments before anything else.
803     }
804
805     // Once all other stuff is done, execute any groovy scripts (in order)
806     if (groovyscript != null)
807     {
808       if (Cache.groovyJarsPresent())
809       {
810         System.out.println("Executing script " + groovyscript);
811         executeGroovyScript(groovyscript, startUpAlframe);
812       }
813       else
814       {
815         System.err.println(
816                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
817                         + groovyscript);
818       }
819     }
820     // and finally, turn off batch mode indicator - if the desktop still exists
821     if (desktop != null)
822     {
823       if (progress != -1)
824       {
825         desktop.setProgressBar(null, progress);
826       }
827       desktop.setInBatchMode(false);
828     }
829   }
830
831   private static void showUsage()
832   {
833     System.out.println(
834             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
835                     + "-nodisplay\tRun Jalview without User Interface.\n"
836                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
837                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
838                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
839                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
840                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
841                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
842                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
843                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
844                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
845                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
846                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
847                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
848                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
849                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
850                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
851                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
852                     + "-html FILE\tCreate HTML file from alignment.\n"
853                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
854                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
855                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
856                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
857                     + "-noquestionnaire\tTurn off questionnaire check.\n"
858                     + "-nonews\tTurn off check for Jalview news.\n"
859                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
860                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
861                     // +
862                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
863                     // after all other properties files have been read\n\t
864                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
865                     // passed in correctly)"
866                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
867                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
868                     // +
869                     // "-vdoc vamsas-document\tImport vamsas document into new
870                     // session or join existing session with same URN\n"
871                     // + "-vses vamsas-session\tJoin session with given URN\n"
872                     + "-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"
873                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
874   }
875
876   private static void startUsageStats(final Desktop desktop)
877   {
878     /**
879      * start a User Config prompt asking if we can log usage statistics.
880      */
881     PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
882             "USAGESTATS", "Jalview Usage Statistics",
883             "Do you want to help make Jalview better by enabling "
884                     + "the collection of usage statistics with Google Analytics ?"
885                     + "\n\n(you can enable or disable usage tracking in the preferences)",
886             new Runnable()
887             {
888               @Override
889               public void run()
890               {
891                 Cache.log.debug(
892                         "Initialising googletracker for usage stats.");
893                 Cache.initGoogleTracker();
894                 Cache.log.debug("Tracking enabled.");
895               }
896             }, new Runnable()
897             {
898               @Override
899               public void run()
900               {
901                 Cache.log.debug("Not enabling Google Tracking.");
902               }
903             }, null, true);
904     desktop.addDialogThread(prompter);
905   }
906
907   /**
908    * Locate the given string as a file and pass it to the groovy interpreter.
909    * 
910    * @param groovyscript
911    *          the script to execute
912    * @param jalviewContext
913    *          the Jalview Desktop object passed in to the groovy binding as the
914    *          'Jalview' object.
915    */
916   private void executeGroovyScript(String groovyscript, AlignFrame af)
917   {
918     /**
919      * for scripts contained in files
920      */
921     File tfile = null;
922     /**
923      * script's URI
924      */
925     URL sfile = null;
926     if (groovyscript.trim().equals("STDIN"))
927     {
928       // read from stdin into a tempfile and execute it
929       try
930       {
931         tfile = File.createTempFile("jalview", "groovy");
932         PrintWriter outfile = new PrintWriter(
933                 new OutputStreamWriter(new FileOutputStream(tfile)));
934         BufferedReader br = new BufferedReader(
935                 new InputStreamReader(System.in));
936         String line = null;
937         while ((line = br.readLine()) != null)
938         {
939           outfile.write(line + "\n");
940         }
941         br.close();
942         outfile.flush();
943         outfile.close();
944
945       } catch (Exception ex)
946       {
947         System.err.println("Failed to read from STDIN into tempfile "
948                 + ((tfile == null) ? "(tempfile wasn't created)"
949                         : tfile.toString()));
950         ex.printStackTrace();
951         return;
952       }
953       try
954       {
955         sfile = tfile.toURI().toURL();
956       } catch (Exception x)
957       {
958         System.err.println(
959                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
960                         + tfile.toURI());
961         x.printStackTrace();
962         return;
963       }
964     }
965     else
966     {
967       try
968       {
969         sfile = new URI(groovyscript).toURL();
970       } catch (Exception x)
971       {
972         tfile = new File(groovyscript);
973         if (!tfile.exists())
974         {
975           System.err.println("File '" + groovyscript + "' does not exist.");
976           return;
977         }
978         if (!tfile.canRead())
979         {
980           System.err.println("File '" + groovyscript + "' cannot be read.");
981           return;
982         }
983         if (tfile.length() < 1)
984         {
985           System.err.println("File '" + groovyscript + "' is empty.");
986           return;
987         }
988         try
989         {
990           sfile = tfile.getAbsoluteFile().toURI().toURL();
991         } catch (Exception ex)
992         {
993           System.err.println("Failed to create a file URL for "
994                   + tfile.getAbsoluteFile());
995           return;
996         }
997       }
998     }
999     try
1000     {
1001       Map<String, java.lang.Object> vbinding = new HashMap<>();
1002       vbinding.put("Jalview", this);
1003       if (af != null)
1004       {
1005         vbinding.put("currentAlFrame", af);
1006       }
1007       Binding gbinding = new Binding(vbinding);
1008       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1009       gse.run(sfile.toString(), gbinding);
1010       if ("STDIN".equals(groovyscript))
1011       {
1012         // delete temp file that we made -
1013         // only if it was successfully executed
1014         tfile.delete();
1015       }
1016     } catch (Exception e)
1017     {
1018       System.err.println("Exception Whilst trying to execute file " + sfile
1019               + " as a groovy script.");
1020       e.printStackTrace(System.err);
1021
1022     }
1023   }
1024
1025   public static boolean isHeadlessMode()
1026   {
1027     String isheadless = System.getProperty("java.awt.headless");
1028     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1029     {
1030       return true;
1031     }
1032     return false;
1033   }
1034
1035   public AlignFrame[] getAlignFrames()
1036   {
1037     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1038             : Desktop.getAlignFrames();
1039
1040   }
1041
1042   /**
1043    * Quit method delegates to Desktop.quit - unless running in headless mode
1044    * when it just ends the JVM
1045    */
1046   public void quit()
1047   {
1048     if (desktop != null)
1049     {
1050       desktop.quit();
1051     }
1052     else
1053     {
1054       System.exit(0);
1055     }
1056   }
1057
1058   public static AlignFrame getCurrentAlignFrame()
1059   {
1060     return Jalview.currentAlignFrame;
1061   }
1062
1063   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1064   {
1065     Jalview.currentAlignFrame = currentAlignFrame;
1066   }
1067 }