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