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