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