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