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