JAL-3662 simple fix for CLI not using right format for output 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 java.io.BufferedReader;
24 import java.io.File;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStreamReader;
28 import java.io.OutputStreamWriter;
29 import java.io.PrintWriter;
30 import java.net.MalformedURLException;
31 import java.net.URI;
32 import java.net.URISyntaxException;
33 import java.net.URL;
34 import java.security.AllPermission;
35 import java.security.CodeSource;
36 import java.security.PermissionCollection;
37 import java.security.Permissions;
38 import java.security.Policy;
39 import java.util.HashMap;
40 import java.util.Map;
41 import java.util.Vector;
42
43 import javax.swing.LookAndFeel;
44 import javax.swing.UIManager;
45
46 import com.threerings.getdown.util.LaunchUtil;
47
48 import groovy.lang.Binding;
49 import groovy.util.GroovyScriptEngine;
50 import jalview.api.AlignCalcWorkerI;
51 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
52 import jalview.ext.so.SequenceOntology;
53 import jalview.gui.AlignFrame;
54 import jalview.gui.AlignViewport;
55 import jalview.gui.Desktop;
56 import jalview.gui.Preferences;
57 import jalview.gui.PromptUserConfig;
58 import jalview.io.AppletFormatAdapter;
59 import jalview.io.BioJsHTMLOutput;
60 import jalview.io.DataSourceType;
61 import jalview.io.FileFormat;
62 import jalview.io.FileFormatException;
63 import jalview.io.FileFormatI;
64 import jalview.io.FileFormats;
65 import jalview.io.FileLoader;
66 import jalview.io.HtmlSvgOutput;
67 import jalview.io.IdentifyFile;
68 import jalview.io.NewickFile;
69 import jalview.io.gff.SequenceOntologyFactory;
70 import jalview.schemes.ColourSchemeI;
71 import jalview.schemes.ColourSchemeProperty;
72 import jalview.util.MessageManager;
73 import jalview.util.Platform;
74 import jalview.ws.jws2.Jws2Discoverer;
75 //import netscape.javascript.JSObject;
76
77 /**
78  * Main class for Jalview Application <br>
79  * <br>
80  * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
81  * jalview.bin.Jalview
82  * 
83  * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
84  * jalview.bin.Jalview jalview.bin.Jalview
85  * 
86  * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
87  * embellish '*' to e.g. '*.jar')
88  * 
89  * @author $author$
90  * @version $Revision$
91  */
92 public class Jalview implements ApplicationSingletonI
93 {
94
95   // for testing those nasty messages you cannot ever find.
96   // static
97   // {
98   // System.setOut(new PrintStream(new ByteArrayOutputStream())
99   // {
100   // @Override
101   // public void println(Object o)
102   // {
103   // if (o != null)
104   // {
105   // System.err.println(o);
106   // }
107   // }
108   //
109   // });
110   // }
111   public static Jalview getInstance()
112   {
113     System.out.println("Hello, MW!!!!!!!!!!!!");
114     return (Jalview) ApplicationSingletonProvider
115             .getInstance(Jalview.class);
116   }
117
118   private Jalview()
119   {
120   }
121
122   private boolean headless;
123
124   private Desktop desktop;
125
126   public AlignFrame currentAlignFrame;
127
128   public String appletResourcePath;
129
130   public String j2sAppletID;
131
132   private boolean noCalculation, noMenuBar, noStatus;
133
134   private boolean noAnnotation;
135
136   public boolean getStartCalculations()
137   {
138     return !noCalculation;
139   }
140
141   public boolean getAllowMenuBar()
142   {
143     return !noMenuBar;
144   }
145
146   public boolean getShowStatus()
147   {
148     return !noStatus;
149   }
150
151   public boolean getShowAnnotation()
152   {
153     return !noAnnotation;
154   }
155
156   static
157   {
158     if (Platform.isJS()) {
159         Platform.getURLCommandArguments();
160     } else /** @j2sIgnore */
161     {
162       // grab all the rights we can for the JVM
163       Policy.setPolicy(new Policy()
164       {
165         @Override
166         public PermissionCollection getPermissions(CodeSource codesource)
167         {
168           Permissions perms = new Permissions();
169           perms.add(new AllPermission());
170           return (perms);
171         }
172
173         @Override
174         public void refresh()
175         {
176         }
177       });
178     }
179   }
180
181   /**
182    * keep track of feature fetching tasks.
183    * 
184    * @author JimP
185    * 
186    */
187   class FeatureFetcher
188   {
189     /*
190      * TODO: generalise to track all jalview events to orchestrate batch processing
191      * events.
192      */
193
194     private int queued = 0;
195
196     private int running = 0;
197
198     public FeatureFetcher()
199     {
200
201     }
202
203     public void addFetcher(final AlignFrame af,
204             final Vector<String> dasSources)
205     {
206       final long id = System.currentTimeMillis();
207       queued++;
208       final FeatureFetcher us = this;
209       new Thread(new Runnable()
210       {
211
212         @Override
213         public void run()
214         {
215           synchronized (us)
216           {
217             queued--;
218             running++;
219           }
220
221           af.setProgressBar(MessageManager
222                   .getString("status.das_features_being_retrived"), id);
223           af.featureSettings_actionPerformed(null);
224           af.setProgressBar(null, id);
225           synchronized (us)
226           {
227             running--;
228           }
229         }
230       }).start();
231     }
232
233     public synchronized boolean allFinished()
234     {
235       return queued == 0 && running == 0;
236     }
237
238   }
239
240   private final static boolean doPlatformLogging = false;
241
242   /**
243    * main class for Jalview application
244    * 
245    * @param args
246    *          open <em>filename</em>
247    */
248   public static void main(String[] args)
249   {
250     if (doPlatformLogging)
251     {
252       Platform.startJavaLogging();
253     }
254     getInstance().doMain(args);
255   }
256
257   /**
258    * @param args
259    */
260   void doMain(String[] args)
261   {
262
263     boolean isJS = Platform.isJS();
264     if (!isJS)
265     {
266       System.setSecurityManager(null);
267     }
268
269     System.out
270             .println("Java version: " + System.getProperty("java.version"));
271     System.out.println("Java Home: " + System.getProperty("java.home"));
272     System.out.println(System.getProperty("os.arch") + " "
273             + System.getProperty("os.name") + " "
274             + System.getProperty("os.version"));
275     String val = System.getProperty("sys.install4jVersion");
276     if (val != null)
277     {
278       System.out.println("Install4j version: " + val);
279     }
280     val = System.getProperty("installer_template_version");
281     if (val != null)
282     {
283       System.out.println("Install4j template version: " + val);
284     }
285     val = System.getProperty("launcher_version");
286     if (val != null)
287     {
288       System.out.println("Launcher version: " + val);
289     }
290
291     // report Jalview version
292     Cache.getInstance().loadBuildProperties(true);
293
294     ArgsParser aparser = new ArgsParser(args);
295     headless = false;
296
297     String usrPropsFile = aparser.getValue("props");
298
299     Cache.loadProperties(usrPropsFile); // must do this before
300
301     boolean allowServices = true;
302     
303     if (isJS)
304     {
305       j2sAppletID = Platform.getAppID(null);
306       Preferences.setAppletDefaults();
307       Cache.loadProperties(usrPropsFile); // again, because we
308       // might be changing defaults here?
309       appletResourcePath = (String) aparser.getAppletValue("resourcepath",
310               null, true);
311     }
312     else
313     /**
314      * Java only
315      * 
316      * @j2sIgnore
317      */
318     {
319
320       if (usrPropsFile != null)
321       {
322         System.out.println(
323                 "CMD [-props " + usrPropsFile + "] executed successfully!");
324       }
325       if (aparser.contains("help") || aparser.contains("h"))
326       {
327         showUsage();
328         System.exit(0);
329       }
330       // ?>>
331       if (aparser.contains("nodisplay") || aparser.contains("nogui")
332               || aparser.contains("headless"))
333       {
334         // BH Is this necessary? Seems like a hack; was removed for applet branch 
335         System.setProperty("java.awt.headless", "true");
336         headless = true;
337       }
338       if ("true".equals(System.getProperty("java.awt.headless")))
339       {
340         headless = true;
341       }
342       // <<?
343
344       // anything else!
345
346       final String jabawsUrl = aparser.getValue(ArgsParser.JABAWS);
347       allowServices = !("none".equals(jabawsUrl));
348       if (allowServices && jabawsUrl != null)
349       {
350         try
351         {
352           Jws2Discoverer.getInstance().setPreferredUrl(jabawsUrl);
353           System.out.println(
354                   "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
355         } catch (MalformedURLException e)
356         {
357           System.err.println(
358                   "Invalid jabaws parameter: " + jabawsUrl + " ignored");
359         }
360       }
361
362     }
363     String defs = aparser.getValue(ArgsParser.SETPROP);
364     while (defs != null)
365     {
366       int p = defs.indexOf('=');
367       if (p == -1)
368       {
369         System.err.println("Ignoring invalid setprop argument : " + defs);
370       }
371       else
372       {
373         System.out.println("Executing setprop argument: " + defs);
374         if (isJS)
375         {
376           Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
377         }
378       }
379       defs = aparser.getValue("setprop");
380     }
381     System.setProperty("http.agent",
382             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
383     try
384     {
385       Cache.initLogger();
386     } catch (NoClassDefFoundError error)
387     {
388       error.printStackTrace();
389       System.out.println("\nEssential logging libraries not found."
390               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
391       System.exit(0);
392     }
393
394     if (!isJS)
395     /** @j2sIgnore */
396     {
397       try
398       {
399         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
400       } catch (Exception ex)
401       {
402         System.err.println("Unexpected Look and Feel Exception");
403         ex.printStackTrace();
404       }
405       if (Platform.isMac())
406       {
407
408         LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
409                 .getLookAndFeel();
410         System.setProperty(
411                 "com.apple.mrj.application.apple.menu.about.name",
412                 "Jalview");
413         System.setProperty("apple.laf.useScreenMenuBar", "true");
414         if (lookAndFeel != null)
415         {
416           try
417           {
418             UIManager.setLookAndFeel(lookAndFeel);
419           } catch (Throwable e)
420           {
421             System.err.println(
422                     "Failed to set QuaQua look and feel: " + e.toString());
423           }
424         }
425         if (lookAndFeel == null
426                 || !(lookAndFeel.getClass().isAssignableFrom(
427                         UIManager.getLookAndFeel().getClass()))
428                 || !UIManager.getLookAndFeel().getClass().toString()
429                         .toLowerCase().contains("quaqua"))
430         {
431           try
432           {
433             System.err.println(
434                     "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
435             UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
436           } catch (Throwable e)
437           {
438             System.err.println(
439                     "Failed to reset look and feel: " + e.toString());
440           }
441         }
442       }
443     }
444     /*
445      * configure 'full' SO model if preferences say to, else use the default (full SO)
446      * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
447      */
448     boolean soDefault = !isJS;
449     if (Cache.getDefault("USE_FULL_SO", soDefault))
450     {
451       SequenceOntologyFactory.setSequenceOntology(new SequenceOntology());
452     }
453
454
455     desktop = null;
456     if (!headless)
457     {
458       desktop = Desktop.getInstance();
459       desktop.setInBatchMode(true); // indicate we are starting up
460       try
461       {
462         JalviewTaskbar.setTaskbar(this);
463       } catch (Throwable t)
464       {
465         System.out.println("Error setting Taskbar: " + t.getMessage());
466       }
467       desktop.setVisible(true);
468
469       if (!isJS)
470       /**
471        * Java only
472        * 
473        * @j2sIgnore
474        */
475       {
476         if (allowServices)
477           desktop.startServiceDiscovery();
478         if (!aparser.contains("nousagestats"))
479         {
480           startUsageStats(desktop);
481         }
482         else
483         {
484           System.err.println("CMD [-nousagestats] executed successfully!");
485         }
486
487         if (!aparser.contains("noquestionnaire"))
488         {
489           String url = aparser.getValue("questionnaire");
490           if (url != null)
491           {
492             // Start the desktop questionnaire prompter with the specified
493             // questionnaire
494             Cache.log.debug("Starting questionnaire url at " + url);
495             desktop.checkForQuestionnaire(url);
496             System.out.println("CMD questionnaire[-" + url
497                     + "] executed successfully!");
498           }
499           else
500           {
501             if (Cache.getProperty("NOQUESTIONNAIRES") == null)
502             {
503               // Start the desktop questionnaire prompter with the specified
504               // questionnaire
505               // String defurl =
506               // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
507               // //
508               String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
509               Cache.log.debug(
510                       "Starting questionnaire with default url: " + defurl);
511               desktop.checkForQuestionnaire(defurl);
512             }
513           }
514         }
515         else
516         {
517           System.err
518                   .println("CMD [-noquestionnaire] executed successfully!");
519         }
520
521         if (!aparser.contains("nonews"))
522         {
523           desktop.checkForNews();
524         }
525
526         BioJsHTMLOutput.updateBioJS();
527       }
528     }
529     parseArguments(aparser, true);
530   }
531
532   /**
533    * Parse all command-line String[] arguments as well as all JavaScript-derived
534    * parameters from Info.
535    * 
536    * We allow for this method to be run from JavaScript. Basically allowing
537    * simple scripting.
538    * 
539    * @param aparser
540    * @param isStartup
541    */
542   public void parseArguments(ArgsParser aparser, boolean isStartup)
543   {
544
545     String groovyscript = null; // script to execute after all loading is
546     boolean isJS = Platform.isJS();
547     if (!isJS)
548     /** @j2sIgnore */
549     {
550       // Move any new getdown-launcher-new.jar into place over old
551       // getdown-launcher.jar
552       String appdirString = System.getProperty("getdownappdir");
553       if (appdirString != null && appdirString.length() > 0)
554       {
555         final File appdir = new File(appdirString);
556         new Thread()
557         {
558           @Override
559           public void run()
560           {
561             LaunchUtil.upgradeGetdown(
562                     new File(appdir, "getdown-launcher-old.jar"),
563                     new File(appdir, "getdown-launcher.jar"),
564                     new File(appdir, "getdown-launcher-new.jar"));
565           }
566         }.start();
567       }
568
569       // completed one way or another
570       // extract groovy argument and execute if necessary
571       groovyscript = aparser.getValue("groovy", true);
572
573     }
574
575     String file = aparser.getValue("open", true);
576
577     if (!isJS && file == null && desktop == null)
578     {
579       System.out.println("No files to open!");
580       System.exit(1);
581     }
582
583     setDisplayParameters(aparser);
584     
585     // time to open a file.
586
587     long progress = -1;
588     DataSourceType protocol = null;
589     FileLoader fileLoader = new FileLoader(!headless);
590     FileFormatI format = null;
591     // Finally, deal with the remaining input data.
592     AlignFrame af = null;
593
594     JalviewJSApp jsApp = (isJS ? new JalviewJSApp(this, aparser) : null);
595
596     if (file == null)
597     {
598       if (isJS)
599       {
600         // JalviewJS allows sequence1 sequence2 ....
601         
602       }
603       else if (!headless && Cache.getDefault("SHOW_STARTUP_FILE", true))
604       /**
605        * Java only
606        * 
607        * @j2sIgnore
608        */
609       {
610
611         // We'll only open the default file if the desktop is visible.
612         // And the user
613         // ////////////////////
614
615         file = Cache.getDefault("STARTUP_FILE",
616                 Cache.getDefault("www.jalview.org",
617                         "http://www.jalview.org")
618                         + "/examples/exampleFile_2_7.jar");
619         if (file.equals(
620                 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
621         {
622           // hardwire upgrade of the startup file
623           file.replace("_2_3.jar", "_2_7.jar");
624           // and remove the stale setting
625           Cache.removeProperty("STARTUP_FILE");
626         }
627
628         protocol = DataSourceType.FILE;
629
630         if (file.indexOf("http:") > -1)
631         {
632           protocol = DataSourceType.URL;
633         }
634
635         if (file.endsWith(".jar"))
636         {
637           format = FileFormat.Jalview;
638         }
639         else
640         {
641           try
642           {
643             format = new IdentifyFile().identify(file, protocol);
644           } catch (FileFormatException e)
645           {
646             // TODO what?
647           }
648         }
649         af = fileLoader.LoadFileWaitTillLoaded(file, protocol, format);
650       }
651     }
652     else
653     {
654       if (!headless)
655       {
656         desktop.setProgressBar(
657                 MessageManager
658                         .getString("status.processing_commandline_args"),
659                 progress = System.currentTimeMillis());
660       }
661       System.out.println("CMD [-open " + file + "] executed successfully!");
662
663       if (!Platform.isJS())
664       /**
665        * ignore in JavaScript -- can't just file existence - could load it?
666        * 
667        * @j2sIgnore
668        */
669       {
670         if (!file.startsWith("http://") && !file.startsWith("https://"))
671         // BH 2019 added https check for Java
672         {
673           if (!(new File(file)).exists())
674           {
675             System.out.println("Can't find " + file);
676             if (headless)
677             {
678               System.exit(1);
679             }
680           }
681         }
682       }
683       
684       String fileFormat = (isJS
685               ? (String) aparser.getAppletValue("format", null, true)
686               : null);
687       protocol = AppletFormatAdapter.checkProtocol(file);
688       try
689       {
690         format = (fileFormat != null
691                 ? FileFormats.getInstance().forName(fileFormat)
692                 : null);
693         if (format == null)
694         {
695           format = new IdentifyFile().identify(file, protocol);
696         }
697       } catch (FileFormatException e1)
698       {
699         // TODO ?
700       }
701
702       af = new FileLoader(!headless).LoadFileWaitTillLoaded(file, protocol,
703               format);
704       if (af == null)
705       {
706         System.out.println("jalview error - AlignFrame was not created");
707       }
708       else
709       {
710
711         // JalviewLite interface for JavaScript allows second file open
712         String file2 = aparser.getValue(ArgsParser.OPEN2, true);
713         if (file2 != null)
714         {
715           protocol = AppletFormatAdapter.checkProtocol(file2);
716           try
717           {
718             format = new IdentifyFile().identify(file2, protocol);
719           } catch (FileFormatException e1)
720           {
721             // TODO ?
722           }
723           AlignFrame af2 = new FileLoader(!headless)
724                   .LoadFileWaitTillLoaded(file2, protocol, format);
725           if (af2 == null)
726           {
727             System.out.println("error");
728           }
729           else
730           {
731             AlignViewport.openLinkedAlignmentAs(af,
732                     af.getViewport().getAlignment(),
733                     af2.getViewport().getAlignment(), "",
734                     AlignViewport.SPLIT_FRAME);
735             System.out.println(
736                     "CMD [-open2 " + file2 + "] executed successfully!");
737           }
738         }
739         setCurrentAlignFrame(af);
740
741         setFrameDependentProperties(aparser, af);
742         
743         if (isJS)
744         {
745           jsApp.initFromParams(af);
746         }
747         else
748         /**
749          * Java only
750          * 
751          * @j2sIgnore
752          */
753         {
754           if (groovyscript != null)
755           {
756             // Execute the groovy script after we've done all the rendering
757             // stuff
758             // and before any images or figures are generated.
759             System.out.println("Executing script " + groovyscript);
760             executeGroovyScript(groovyscript, af);
761             System.out.println("CMD groovy[" + groovyscript
762                     + "] executed successfully!");
763             groovyscript = null;
764           }
765         }
766         if (!isJS || !isStartup) {
767           createOutputFiles(aparser, format);
768         }
769       }
770     }
771     // extract groovy arguments before anything else.
772     // Once all other stuff is done, execute any groovy scripts (in order)
773     if (!isJS && groovyscript != null)
774     {
775       if (Cache.groovyJarsPresent())
776       {
777         System.out.println("Executing script " + groovyscript);
778         executeGroovyScript(groovyscript, af);
779       }
780       else
781       {
782         System.err.println(
783                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
784                         + groovyscript);
785       }
786     }
787
788     // and finally, turn off batch mode indicator - if the desktop still exists
789     if (desktop != null)
790     {
791       if (progress != -1)
792       {
793         desktop.setProgressBar(null, progress);
794       }
795       desktop.setInBatchMode(false);
796     }
797     
798     if (jsApp != null) {
799       jsApp.callInitCallback();
800     }
801   }
802   
803   /**
804    * Set general display parameters irrespective of file loading or headlessness.
805    * 
806    * @param aparser
807    */
808   private void setDisplayParameters(ArgsParser aparser)
809   {
810     if (aparser.contains(ArgsParser.NOMENUBAR))
811     {
812       noMenuBar = true;
813       System.out.println("CMD [nomenu] executed successfully!");
814     }
815
816     if (aparser.contains(ArgsParser.NOSTATUS))
817     {
818       noStatus = true;
819       System.out.println("CMD [nostatus] executed successfully!");
820     }
821
822     if (aparser.contains(ArgsParser.NOANNOTATION)
823             || aparser.contains(ArgsParser.NOANNOTATION2))
824     {
825       noAnnotation = true;
826       System.out.println("CMD no-annotation executed successfully!");
827     }
828     if (aparser.contains(ArgsParser.NOCALCULATION))
829     {
830       noCalculation = true;
831       System.out.println("CMD [nocalculation] executed successfully!");
832     }
833   }
834
835
836   private void setFrameDependentProperties(ArgsParser aparser,
837           AlignFrame af)
838   {
839     String data = aparser.getValue(ArgsParser.COLOUR, true);
840     if (data != null)
841     {
842       data.replaceAll("%20", " ");
843
844       ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
845               af.getViewport(), af.getViewport().getAlignment(), data);
846
847       if (cs != null)
848       {
849         System.out.println(
850                 "CMD [-color " + data + "] executed successfully!");
851       }
852       af.changeColour(cs);
853     }
854
855     // Must maintain ability to use the groups flag
856     data = aparser.getValue(ArgsParser.GROUPS, true);
857     if (data != null)
858     {
859       af.parseFeaturesFile(data,
860               AppletFormatAdapter.checkProtocol(data));
861       // System.out.println("Added " + data);
862       System.out.println(
863               "CMD groups[-" + data + "]  executed successfully!");
864     }
865     data = aparser.getValue(ArgsParser.FEATURES, true);
866     if (data != null)
867     {
868       af.parseFeaturesFile(data,
869               AppletFormatAdapter.checkProtocol(data));
870       // System.out.println("Added " + data);
871       System.out.println(
872               "CMD [-features " + data + "]  executed successfully!");
873     }
874     data = aparser.getValue(ArgsParser.ANNOTATIONS, true);
875     if (data != null)
876     {
877       af.loadJalviewDataFile(data, null, null, null);
878       // System.out.println("Added " + data);
879       System.out.println(
880               "CMD [-annotations " + data + "] executed successfully!");
881     }
882
883     // JavaScript feature
884
885     if (aparser.contains(ArgsParser.SHOWOVERVIEW))
886     {
887       af.overviewMenuItem_actionPerformed(null);
888       System.out.println("CMD [showoverview] executed successfully!");
889     }
890
891     // set or clear the sortbytree flag.
892     if (aparser.contains(ArgsParser.SORTBYTREE))
893     {
894       af.getViewport().setSortByTree(true);
895       if (af.getViewport().getSortByTree())
896       {
897         System.out.println("CMD [-sortbytree] executed successfully!");
898       }
899     }
900
901     boolean doUpdateAnnotation = false;
902     /**
903      * we do this earlier in JalviewJS because of a complication with
904      * SHOWOVERVIEW
905      * 
906      * For now, just fixing this in JalviewJS.
907      *
908      * 
909      * @j2sIgnore
910      * 
911      */
912     {
913       if (noAnnotation)
914       {
915         af.getViewport().setShowAnnotation(false);
916         if (!af.getViewport().isShowAnnotation())
917         {
918           doUpdateAnnotation = true;
919         }
920       }
921     }
922
923     if (aparser.contains(ArgsParser.NOSORTBYTREE))
924     {
925       af.getViewport().setSortByTree(false);
926       if (!af.getViewport().getSortByTree())
927       {
928         doUpdateAnnotation = true;
929         System.out
930                 .println("CMD [-nosortbytree] executed successfully!");
931       }
932     }
933     if (doUpdateAnnotation)
934     { // BH 2019.07.24
935       af.setMenusForViewport();
936       af.alignPanel.updateLayout();
937     }
938
939     data = aparser.getValue(ArgsParser.TREE, true);
940     if (data != null)
941     {
942       try
943       {
944         NewickFile nf = new NewickFile(data,
945                 AppletFormatAdapter.checkProtocol(data));
946         af.getViewport()
947                 .setCurrentTree(af.showNewickTree(nf, data).getTree());
948         System.out.println(
949                 "CMD [-tree " + data + "] executed successfully!");
950       } catch (IOException ex)
951       {
952         System.err.println("Couldn't add tree " + data);
953         ex.printStackTrace(System.err);
954       }
955     }
956     // TODO - load PDB structure(s) to alignment JAL-629
957     // (associate with identical sequence in alignment, or a specified
958     // sequence)
959
960   }
961
962   /**
963    * Writes an output file for each format (if any) specified in the
964    * command-line arguments. Supported formats are currently
965    * <ul>
966    * <li>png</li>
967    * <li>svg</li>
968    * <li>html</li>
969    * <li>biojsmsa</li>
970    * <li>imgMap</li>
971    * <li>eps</li>
972    * </ul>
973    * A format parameter should be followed by a parameter specifying the output
974    * file name. {@code imgMap} parameters should follow those for the
975    * corresponding alignment image output.
976    * 
977    * @param aparser
978    * @param format
979    */
980   private void createOutputFiles(ArgsParser aparser,
981           FileFormatI format)
982   {
983     AlignFrame af = currentAlignFrame;
984     while (aparser.getSize() >= 2)
985     {
986       String outputFormat = aparser.nextValue();
987       File imageFile;
988       String fname;
989       switch (outputFormat.toLowerCase())
990       {
991       case "png":
992         imageFile = new File(aparser.nextValue());
993         af.createPNG(imageFile);
994         System.out.println(
995                 "Creating PNG image: " + imageFile.getAbsolutePath());
996         continue;
997       case "svg":
998         imageFile = new File(aparser.nextValue());
999         af.createSVG(imageFile);
1000         System.out.println(
1001                 "Creating SVG image: " + imageFile.getAbsolutePath());
1002         continue;
1003       case "eps":
1004         imageFile = new File(aparser.nextValue());
1005         System.out.println(
1006                 "Creating EPS file: " + imageFile.getAbsolutePath());
1007         af.createEPS(imageFile);
1008         continue;
1009       case "biojsmsa":
1010         fname = new File(aparser.nextValue()).getAbsolutePath();
1011         try
1012         {
1013           BioJsHTMLOutput.refreshVersionInfo(
1014                   BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1015         } catch (URISyntaxException e)
1016         {
1017           e.printStackTrace();
1018         }
1019         BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1020         bjs.exportHTML(fname);
1021         System.out.println("Creating BioJS MSA Viwer HTML file: " + fname);
1022         continue;
1023       case "html":
1024         fname = new File(aparser.nextValue()).getAbsolutePath();
1025         HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1026         htmlSVG.exportHTML(fname);
1027         System.out.println("Creating HTML image: " + fname);
1028         continue;
1029       case "imgmap":
1030         imageFile = new File(aparser.nextValue());
1031         af.alignPanel.makePNGImageMap(imageFile, "unnamed.png");
1032         System.out.println(
1033                 "Creating image map: " + imageFile.getAbsolutePath());
1034         continue;
1035       default:
1036         format = FileFormats.getInstance().forName(outputFormat);
1037         if (format == null)
1038         {
1039           System.out.println("Invalid file format: " + outputFormat);
1040           break;
1041         }
1042         fname = new File(aparser.nextValue()).getAbsolutePath();
1043         af.saveAlignment(fname, format);
1044         if (!af.isSaveAlignmentSuccessful())
1045         {
1046           System.out.println("Error writing file " + fname + " in " + format
1047                   + " format!!");
1048           break;
1049         }
1050         continue;
1051       }
1052       System.out.println("Unknown arg: " + outputFormat);      
1053       break;
1054     }
1055     while (aparser.getSize() > 0)
1056     {
1057       System.out.println("Unknown arg: " + aparser.nextValue());
1058     }
1059   }
1060
1061   private static void showUsage()
1062   {
1063     System.out.println(
1064             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1065                     + "-nodisplay\tRun Jalview without User Interface.\n"
1066                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1067                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1068                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1069                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1070                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
1071                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1072                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1073                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1074                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1075                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1076                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1077                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1078                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1079                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1080                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
1081                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1082                     + "-html FILE\tCreate HTML file from alignment.\n"
1083                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1084                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1085                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1086                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1087                     + "-noquestionnaire\tTurn off questionnaire check.\n"
1088                     + "-nonews\tTurn off check for Jalview news.\n"
1089                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1090                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1091                     // +
1092                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1093                     // after all other properties files have been read\n\t
1094                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1095                     // passed in correctly)"
1096                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1097                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1098                     + "-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"
1099                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1100   }
1101
1102   private static void startUsageStats(final Desktop desktop)
1103   {
1104     /**
1105      * start a User Config prompt asking if we can log usage statistics.
1106      */
1107     PromptUserConfig prompter = new PromptUserConfig(Desktop.getDesktopPane(),
1108             "USAGESTATS", "Jalview Usage Statistics",
1109             "Do you want to help make Jalview better by enabling "
1110                     + "the collection of usage statistics with Google Analytics ?"
1111                     + "\n\n(you can enable or disable usage tracking in the preferences)",
1112             new Runnable()
1113             {
1114               @Override
1115               public void run()
1116               {
1117                 Cache.log.debug(
1118                         "Initialising googletracker for usage stats.");
1119                 Cache.initGoogleTracker();
1120                 Cache.log.debug("Tracking enabled.");
1121               }
1122             }, new Runnable()
1123             {
1124               @Override
1125               public void run()
1126               {
1127                 Cache.log.debug("Not enabling Google Tracking.");
1128               }
1129             }, null, true);
1130     desktop.addDialogThread(prompter);
1131   }
1132
1133   /**
1134    * Locate the given string as a file and pass it to the groovy interpreter.
1135    * 
1136    * @param groovyscript
1137    *          the script to execute
1138    * @param jalviewContext
1139    *          the Jalview Desktop object passed in to the groovy binding as the
1140    *          'Jalview' object.
1141    */
1142   private void executeGroovyScript(String groovyscript, AlignFrame af)
1143   {
1144     /**
1145      * for scripts contained in files
1146      */
1147     File tfile = null;
1148     /**
1149      * script's URI
1150      */
1151     URL sfile = null;
1152     if (groovyscript.trim().equals("STDIN"))
1153     {
1154       // read from stdin into a tempfile and execute it
1155       try
1156       {
1157         tfile = File.createTempFile("jalview", "groovy");
1158         PrintWriter outfile = new PrintWriter(
1159                 new OutputStreamWriter(new FileOutputStream(tfile)));
1160         BufferedReader br = new BufferedReader(
1161                 new InputStreamReader(System.in));
1162         String line = null;
1163         while ((line = br.readLine()) != null)
1164         {
1165           outfile.write(line + "\n");
1166         }
1167         br.close();
1168         outfile.flush();
1169         outfile.close();
1170
1171       } catch (Exception ex)
1172       {
1173         System.err.println("Failed to read from STDIN into tempfile "
1174                 + ((tfile == null) ? "(tempfile wasn't created)"
1175                         : tfile.toString()));
1176         ex.printStackTrace();
1177         return;
1178       }
1179       try
1180       {
1181         sfile = tfile.toURI().toURL();
1182       } catch (Exception x)
1183       {
1184         System.err.println(
1185                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1186                         + tfile.toURI());
1187         x.printStackTrace();
1188         return;
1189       }
1190     }
1191     else
1192     {
1193       try
1194       {
1195         sfile = new URI(groovyscript).toURL();
1196       } catch (Exception x)
1197       {
1198         tfile = new File(groovyscript);
1199         if (!tfile.exists())
1200         {
1201           System.err.println("File '" + groovyscript + "' does not exist.");
1202           return;
1203         }
1204         if (!tfile.canRead())
1205         {
1206           System.err.println("File '" + groovyscript + "' cannot be read.");
1207           return;
1208         }
1209         if (tfile.length() < 1)
1210         {
1211           System.err.println("File '" + groovyscript + "' is empty.");
1212           return;
1213         }
1214         try
1215         {
1216           sfile = tfile.getAbsoluteFile().toURI().toURL();
1217         } catch (Exception ex)
1218         {
1219           System.err.println("Failed to create a file URL for "
1220                   + tfile.getAbsoluteFile());
1221           return;
1222         }
1223       }
1224     }
1225     try
1226     {
1227       Map<String, java.lang.Object> vbinding = new HashMap<>();
1228       vbinding.put("Jalview", this);
1229       if (af != null)
1230       {
1231         vbinding.put("currentAlFrame", af);
1232       }
1233       Binding gbinding = new Binding(vbinding);
1234       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1235       gse.run(sfile.toString(), gbinding);
1236       if ("STDIN".equals(groovyscript))
1237       {
1238         // delete temp file that we made -
1239         // only if it was successfully executed
1240         tfile.delete();
1241       }
1242     } catch (Exception e)
1243     {
1244       System.err.println("Exception Whilst trying to execute file " + sfile
1245               + " as a groovy script.");
1246       e.printStackTrace(System.err);
1247
1248     }
1249   }
1250
1251   public static boolean isHeadlessMode()
1252   {
1253     String isheadless = System.getProperty("java.awt.headless");
1254     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1255     {
1256       return true;
1257     }
1258     return false;
1259   }
1260
1261   public AlignFrame[] getAlignFrames()
1262   {
1263     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1264             : Desktop.getAlignFrames();
1265
1266   }
1267
1268   /**
1269    * Quit method delegates to Desktop.quit - unless running in headless mode
1270    * when it just ends the JVM
1271    */
1272   public void quit()
1273   {
1274     if (desktop != null)
1275     {
1276       desktop.quit();
1277     }
1278     else
1279     {
1280       System.exit(0);
1281     }
1282   }
1283
1284   public static AlignFrame getCurrentAlignFrame()
1285   {
1286     return Jalview.getInstance().currentAlignFrame;
1287   }
1288
1289   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1290   {
1291     Jalview.getInstance().currentAlignFrame = currentAlignFrame;
1292   }
1293
1294   
1295   public void notifyWorker(AlignCalcWorkerI worker, String status)
1296   {
1297     // System.out.println("Jalview worker " + worker.getClass().getSimpleName()
1298     // + " " + status);
1299   }
1300
1301
1302   private static boolean isInteractive = true;
1303
1304   public static boolean isInteractive()
1305   {
1306     return isInteractive;
1307   }
1308
1309   public static void setInteractive(boolean tf)
1310   {
1311     isInteractive = tf;
1312   }
1313
1314 }