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