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