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