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