JAL-3848 add compbio and jalview to direct connection list for J2S
[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
190      * processing 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     /*
269      * @j2sNative J2S.db._DirectDatabaseCalls["compbio.dundee.ac.uk"]=null;
270      * @j2sNative J2S.db._DirectDatabaseCalls["jalview.org"]=null;
271      * 
272      */
273     System.out
274             .println("Java version: " + System.getProperty("java.version"));
275     System.out.println("Java Home: " + System.getProperty("java.home"));
276     System.out.println(System.getProperty("os.arch") + " "
277             + System.getProperty("os.name") + " "
278             + System.getProperty("os.version"));
279     String val = System.getProperty("sys.install4jVersion");
280     if (val != null)
281     {
282       System.out.println("Install4j version: " + val);
283     }
284     val = System.getProperty("installer_template_version");
285     if (val != null)
286     {
287       System.out.println("Install4j template version: " + val);
288     }
289     val = System.getProperty("launcher_version");
290     if (val != null)
291     {
292       System.out.println("Launcher version: " + val);
293     }
294
295     // report Jalview version
296     Cache.getInstance().loadBuildProperties(true);
297
298     ArgsParser aparser = new ArgsParser(args);
299     headless = false;
300
301     String usrPropsFile = aparser.getValue("props");
302
303     Cache.loadProperties(usrPropsFile); // must do this before
304
305     boolean allowServices = true;
306     
307     if (isJS)
308     {
309       j2sAppletID = Platform.getAppID(null);
310       Preferences.setAppletDefaults();
311       Cache.loadProperties(usrPropsFile); // again, because we
312       // might be changing defaults here?
313       appletResourcePath = (String) aparser.getAppletValue("resourcepath",
314               null, true);
315     }
316     else
317     /**
318      * Java only
319      * 
320      * @j2sIgnore
321      */
322     {
323
324       if (usrPropsFile != null)
325       {
326         System.out.println(
327                 "CMD [-props " + usrPropsFile + "] executed successfully!");
328       }
329       if (aparser.contains("help") || aparser.contains("h"))
330       {
331         showUsage();
332         System.exit(0);
333       }
334       // BH note: Only -nodisplay is official; others are deprecated?
335       if (aparser.contains("nodisplay") || aparser.contains("nogui")
336               || aparser.contains("headless")
337               || GraphicsEnvironment.isHeadless())
338       {
339         if (!isJS) {
340           // BH Definitely not a good idea in JavaScript; 
341           // probably should not be here for Java, either.  
342           System.setProperty("java.awt.headless", "true");
343         }
344         headless = true;
345       }
346
347       final String jabawsUrl = aparser.getValue(ArgsParser.JABAWS);
348       allowServices = !("none".equals(jabawsUrl));
349       if (allowServices && jabawsUrl != null)
350       {
351         try
352         {
353           Jws2Discoverer.getInstance().setPreferredUrl(jabawsUrl);
354           System.out.println(
355                   "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
356         } catch (MalformedURLException e)
357         {
358           System.err.println(
359                   "Invalid jabaws parameter: " + jabawsUrl + " ignored");
360         }
361       }
362
363     }
364     String defs = aparser.getValue(ArgsParser.SETPROP);
365     while (defs != null)
366     {
367       int p = defs.indexOf('=');
368       if (p == -1)
369       {
370         System.err.println("Ignoring invalid setprop argument : " + defs);
371       }
372       else
373       {
374         System.out.println("Executing setprop argument: " + defs);
375         if (isJS)
376         {
377           Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
378         }
379       }
380       defs = aparser.getValue("setprop");
381     }
382     System.setProperty("http.agent",
383             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
384     try
385     {
386       Cache.initLogger();
387     } catch (NoClassDefFoundError error)
388     {
389       error.printStackTrace();
390       System.out.println("\nEssential logging libraries not found."
391               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
392       System.exit(0);
393     }
394
395     if (!isJS)
396     /** @j2sIgnore */
397     {
398       try
399       {
400         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
401       } catch (Exception ex)
402       {
403         System.err.println("Unexpected Look and Feel Exception");
404         ex.printStackTrace();
405       }
406       if (Platform.isMac())
407       {
408
409         LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
410                 .getLookAndFeel();
411         System.setProperty(
412                 "com.apple.mrj.application.apple.menu.about.name",
413                 "Jalview");
414         System.setProperty("apple.laf.useScreenMenuBar", "true");
415         if (lookAndFeel != null)
416         {
417           try
418           {
419             UIManager.setLookAndFeel(lookAndFeel);
420           } catch (Throwable e)
421           {
422             System.err.println(
423                     "Failed to set QuaQua look and feel: " + e.toString());
424           }
425         }
426         if (lookAndFeel == null
427                 || !(lookAndFeel.getClass().isAssignableFrom(
428                         UIManager.getLookAndFeel().getClass()))
429                 || !UIManager.getLookAndFeel().getClass().toString()
430                         .toLowerCase().contains("quaqua"))
431         {
432           try
433           {
434             System.err.println(
435                     "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
436             UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
437           } catch (Throwable e)
438           {
439             System.err.println(
440                     "Failed to reset look and feel: " + e.toString());
441           }
442         }
443       }
444     }
445     /*
446      * configure 'full' SO model if preferences say to, else use the default (full SO)
447      * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
448      */
449     boolean soDefault = !isJS;
450     if (Cache.getDefault("USE_FULL_SO", soDefault))
451     {
452       SequenceOntologyFactory.setSequenceOntology(new SequenceOntology());
453     }
454
455
456     desktop = null;
457     if (!headless)
458     {
459       desktop = Desktop.getInstance();
460       desktop.setInBatchMode(true); // indicate we are starting up
461       try
462       {
463         JalviewTaskbar.setTaskbar(this);
464       } catch (Throwable t)
465       {
466         System.out.println("Error setting Taskbar: " + t.getMessage());
467       }
468       desktop.setVisible(true);
469       if (Platform.isJS())
470         Cache.setProperty("SHOW_JWS2_SERVICES", "false");
471       if (allowServices)
472       {
473         desktop.startServiceDiscovery();
474       }
475       if (!isJS)
476       /**
477        * Java only
478        * 
479        * @j2sIgnore
480        */
481       {
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       if (headless)
775       {
776         af.getViewport().getCalcManager().shutdown();
777       }
778     }
779     // extract groovy arguments before anything else.
780     // Once all other stuff is done, execute any groovy scripts (in order)
781     if (!isJS && groovyscript != null)
782     {
783       if (Cache.groovyJarsPresent())
784       {
785         System.out.println("Executing script " + groovyscript);
786         executeGroovyScript(groovyscript, af);
787       }
788       else
789       {
790         System.err.println(
791                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
792                         + groovyscript);
793       }
794     }
795
796     // and finally, turn off batch mode indicator - if the desktop still exists
797     if (desktop != null)
798     {
799       if (progress != -1)
800       {
801         desktop.setProgressBar(null, progress);
802       }
803       desktop.setInBatchMode(false);
804     }
805     
806     if (jsApp != null) {
807       jsApp.callInitCallback();
808     }
809   }
810   
811   /**
812    * Set general display parameters irrespective of file loading or headlessness.
813    * 
814    * @param aparser
815    */
816   private void setDisplayParameters(ArgsParser aparser)
817   {
818     if (aparser.contains(ArgsParser.NOMENUBAR))
819     {
820       noMenuBar = true;
821       System.out.println("CMD [nomenu] executed successfully!");
822     }
823
824     if (aparser.contains(ArgsParser.NOSTATUS))
825     {
826       noStatus = true;
827       System.out.println("CMD [nostatus] executed successfully!");
828     }
829
830     if (aparser.contains(ArgsParser.NOANNOTATION)
831             || aparser.contains(ArgsParser.NOANNOTATION2))
832     {
833       noAnnotation = true;
834       System.out.println("CMD no-annotation executed successfully!");
835     }
836     if (aparser.contains(ArgsParser.NOCALCULATION))
837     {
838       noCalculation = true;
839       System.out.println("CMD [nocalculation] executed successfully!");
840     }
841   }
842
843
844   private void setFrameDependentProperties(ArgsParser aparser,
845           AlignFrame af)
846   {
847     String data = aparser.getValue(ArgsParser.COLOUR, true);
848     if (data != null)
849     {
850       data.replaceAll("%20", " ");
851
852       ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
853               af.getViewport(), af.getViewport().getAlignment(), data);
854
855       if (cs != null)
856       {
857         System.out.println(
858                 "CMD [-color " + data + "] executed successfully!");
859       }
860       af.changeColour(cs);
861     }
862
863     // Must maintain ability to use the groups flag
864     data = aparser.getValue(ArgsParser.GROUPS, true);
865     if (data != null)
866     {
867       af.parseFeaturesFile(data,
868               AppletFormatAdapter.checkProtocol(data));
869       // System.out.println("Added " + data);
870       System.out.println(
871               "CMD groups[-" + data + "]  executed successfully!");
872     }
873     data = aparser.getValue(ArgsParser.FEATURES, true);
874     if (data != null)
875     {
876       af.parseFeaturesFile(data,
877               AppletFormatAdapter.checkProtocol(data));
878       // System.out.println("Added " + data);
879       System.out.println(
880               "CMD [-features " + data + "]  executed successfully!");
881     }
882     data = aparser.getValue(ArgsParser.ANNOTATIONS, true);
883     if (data != null)
884     {
885       af.loadJalviewDataFile(data, null, null, null);
886       // System.out.println("Added " + data);
887       System.out.println(
888               "CMD [-annotations " + data + "] executed successfully!");
889     }
890
891     // JavaScript feature
892
893     if (aparser.contains(ArgsParser.SHOWOVERVIEW))
894     {
895       af.overviewMenuItem_actionPerformed(null);
896       System.out.println("CMD [showoverview] executed successfully!");
897     }
898
899     // set or clear the sortbytree flag.
900     if (aparser.contains(ArgsParser.SORTBYTREE))
901     {
902       af.getViewport().setSortByTree(true);
903       if (af.getViewport().getSortByTree())
904       {
905         System.out.println("CMD [-sortbytree] executed successfully!");
906       }
907     }
908
909     boolean doUpdateAnnotation = false;
910     /**
911      * we do this earlier in JalviewJS because of a complication with
912      * SHOWOVERVIEW
913      * 
914      * For now, just fixing this in JalviewJS.
915      *
916      * 
917      * @j2sIgnore
918      * 
919      */
920     {
921       if (noAnnotation)
922       {
923         af.getViewport().setShowAnnotation(false);
924         if (!af.getViewport().isShowAnnotation())
925         {
926           doUpdateAnnotation = true;
927         }
928       }
929     }
930
931     if (aparser.contains(ArgsParser.NOSORTBYTREE))
932     {
933       af.getViewport().setSortByTree(false);
934       if (!af.getViewport().getSortByTree())
935       {
936         doUpdateAnnotation = true;
937         System.out
938                 .println("CMD [-nosortbytree] executed successfully!");
939       }
940     }
941     if (doUpdateAnnotation)
942     { // BH 2019.07.24
943       af.setMenusForViewport();
944       af.alignPanel.updateLayout();
945     }
946
947     data = aparser.getValue(ArgsParser.TREE, true);
948     if (data != null)
949     {
950       try
951       {
952         NewickFile nf = new NewickFile(data,
953                 AppletFormatAdapter.checkProtocol(data));
954         af.getViewport()
955                 .setCurrentTree(af.showNewickTree(nf, data).getTree());
956         System.out.println(
957                 "CMD [-tree " + data + "] executed successfully!");
958       } catch (IOException ex)
959       {
960         System.err.println("Couldn't add tree " + data);
961         ex.printStackTrace(System.err);
962       }
963     }
964     // TODO - load PDB structure(s) to alignment JAL-629
965     // (associate with identical sequence in alignment, or a specified
966     // sequence)
967
968   }
969
970   /**
971    * Writes an output file for each format (if any) specified in the
972    * command-line arguments. Supported formats are currently
973    * <ul>
974    * <li>png</li>
975    * <li>svg</li>
976    * <li>html</li>
977    * <li>biojsmsa</li>
978    * <li>imgMap</li>
979    * <li>eps</li>
980    * </ul>
981    * A format parameter should be followed by a parameter specifying the output
982    * file name. {@code imgMap} parameters should follow those for the
983    * corresponding alignment image output.
984    * 
985    * @param aparser
986    * @param format
987    */
988   private void createOutputFiles(ArgsParser aparser, FileFormatI format)
989   {
990     AlignFrame af = currentAlignFrame;
991     while (aparser.getSize() >= 2)
992     {
993       String outputFormat = aparser.nextValue();
994       File imageFile;
995       String fname;
996       switch (outputFormat.toLowerCase())
997       {
998       case "png":
999         imageFile = new File(aparser.nextValue());
1000         af.createPNG(imageFile);
1001         System.out.println(
1002                 "Creating PNG image: " + imageFile.getAbsolutePath());
1003         continue;
1004       case "svg":
1005         imageFile = new File(aparser.nextValue());
1006         af.createSVG(imageFile);
1007         System.out.println(
1008                 "Creating SVG image: " + imageFile.getAbsolutePath());
1009         continue;
1010       case "eps":
1011         imageFile = new File(aparser.nextValue());
1012         System.out.println(
1013                 "Creating EPS file: " + imageFile.getAbsolutePath());
1014         af.createEPS(imageFile);
1015         continue;
1016       case "biojsmsa":
1017         fname = new File(aparser.nextValue()).getAbsolutePath();
1018         try
1019         {
1020           BioJsHTMLOutput.refreshVersionInfo(
1021                   BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1022         } catch (URISyntaxException e)
1023         {
1024           e.printStackTrace();
1025         }
1026         BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1027         bjs.exportHTML(fname);
1028         System.out.println("Creating BioJS MSA Viwer HTML file: " + fname);
1029         continue;
1030       case "html":
1031         fname = new File(aparser.nextValue()).getAbsolutePath();
1032         HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1033         htmlSVG.exportHTML(fname);
1034         System.out.println("Creating HTML image: " + fname);
1035         continue;
1036       case "imgmap":
1037         imageFile = new File(aparser.nextValue());
1038         af.alignPanel.makePNGImageMap(imageFile, "unnamed.png");
1039         System.out.println(
1040                 "Creating image map: " + imageFile.getAbsolutePath());
1041         continue;
1042       default:
1043         // fall through - try to parse as an alignment data export format
1044         FileFormatI outFormat = null;
1045         try
1046         {
1047           outFormat = FileFormats.getInstance().forName(outputFormat);
1048         } catch (Exception formatP)
1049         {
1050         }
1051         if (outFormat == null)
1052         {
1053           System.out.println("Couldn't parse " + outputFormat
1054                   + " as a valid Jalview format string.");
1055           continue;
1056         }
1057         if (!outFormat.isWritable())
1058         {
1059           System.out.println(
1060                   "This version of Jalview does not support alignment export as "
1061                           + outputFormat);
1062           continue;
1063         }
1064         // record file as it was passed to Jalview so it is recognisable to the CLI
1065         // caller
1066         String file;
1067         fname = new File(file = aparser.nextValue()).getAbsolutePath();
1068         // JBPNote - yuck - really wish we did have a bean returned from this which gave
1069         // success/fail like before !
1070         af.saveAlignment(fname, outFormat);
1071         if (!af.isSaveAlignmentSuccessful())
1072         {
1073           System.out.println("Written alignment in " + outputFormat
1074                   + " format to " + file);
1075           continue;
1076         }
1077         else
1078         {
1079           System.out.println("Error writing file " + file + " in "
1080                   + outputFormat + " format!!");
1081         }
1082       }
1083     }
1084     // ??? Should report - 'ignoring' extra args here...
1085     while (aparser.getSize() > 0)
1086     {
1087       System.out.println("Ignoring extra argument: " + aparser.nextValue());
1088     }
1089   }
1090
1091   private static void showUsage()
1092   {
1093     System.out.println(
1094             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1095                     + "-nodisplay\tRun Jalview without User Interface.\n"
1096                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1097                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1098                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1099                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1100                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
1101                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1102                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1103                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1104                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1105                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1106                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1107                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1108                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1109                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1110                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
1111                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1112                     + "-html FILE\tCreate HTML file from alignment.\n"
1113                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1114                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1115                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1116                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1117                     + "-noquestionnaire\tTurn off questionnaire check.\n"
1118                     + "-nonews\tTurn off check for Jalview news.\n"
1119                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1120                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1121                     // +
1122                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1123                     // after all other properties files have been read\n\t
1124                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1125                     // passed in correctly)"
1126                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1127                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1128                     + "-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"
1129                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1130   }
1131
1132   private static void startUsageStats(final Desktop desktop)
1133   {
1134     /**
1135      * start a User Config prompt asking if we can log usage statistics.
1136      */
1137     PromptUserConfig prompter = new PromptUserConfig(Desktop.getDesktopPane(),
1138             "USAGESTATS", "Jalview Usage Statistics",
1139             "Do you want to help make Jalview better by enabling "
1140                     + "the collection of usage statistics with Google Analytics ?"
1141                     + "\n\n(you can enable or disable usage tracking in the preferences)",
1142             new Runnable()
1143             {
1144               @Override
1145               public void run()
1146               {
1147                 Cache.log.debug(
1148                         "Initialising googletracker for usage stats.");
1149                 Cache.initGoogleTracker();
1150                 Cache.log.debug("Tracking enabled.");
1151               }
1152             }, new Runnable()
1153             {
1154               @Override
1155               public void run()
1156               {
1157                 Cache.log.debug("Not enabling Google Tracking.");
1158               }
1159             }, null, true);
1160     desktop.addDialogThread(prompter);
1161   }
1162
1163   /**
1164    * Locate the given string as a file and pass it to the groovy interpreter.
1165    * 
1166    * @param groovyscript
1167    *          the script to execute
1168    * @param jalviewContext
1169    *          the Jalview Desktop object passed in to the groovy binding as the
1170    *          'Jalview' object.
1171    */
1172   private void executeGroovyScript(String groovyscript, AlignFrame af)
1173   {
1174     /**
1175      * for scripts contained in files
1176      */
1177     File tfile = null;
1178     /**
1179      * script's URI
1180      */
1181     URL sfile = null;
1182     if (groovyscript.trim().equals("STDIN"))
1183     {
1184       // read from stdin into a tempfile and execute it
1185       try
1186       {
1187         tfile = File.createTempFile("jalview", "groovy");
1188         PrintWriter outfile = new PrintWriter(
1189                 new OutputStreamWriter(new FileOutputStream(tfile)));
1190         BufferedReader br = new BufferedReader(
1191                 new InputStreamReader(System.in));
1192         String line = null;
1193         while ((line = br.readLine()) != null)
1194         {
1195           outfile.write(line + "\n");
1196         }
1197         br.close();
1198         outfile.flush();
1199         outfile.close();
1200
1201       } catch (Exception ex)
1202       {
1203         System.err.println("Failed to read from STDIN into tempfile "
1204                 + ((tfile == null) ? "(tempfile wasn't created)"
1205                         : tfile.toString()));
1206         ex.printStackTrace();
1207         return;
1208       }
1209       try
1210       {
1211         sfile = tfile.toURI().toURL();
1212       } catch (Exception x)
1213       {
1214         System.err.println(
1215                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1216                         + tfile.toURI());
1217         x.printStackTrace();
1218         return;
1219       }
1220     }
1221     else
1222     {
1223       try
1224       {
1225         sfile = new URI(groovyscript).toURL();
1226       } catch (Exception x)
1227       {
1228         tfile = new File(groovyscript);
1229         if (!tfile.exists())
1230         {
1231           System.err.println("File '" + groovyscript + "' does not exist.");
1232           return;
1233         }
1234         if (!tfile.canRead())
1235         {
1236           System.err.println("File '" + groovyscript + "' cannot be read.");
1237           return;
1238         }
1239         if (tfile.length() < 1)
1240         {
1241           System.err.println("File '" + groovyscript + "' is empty.");
1242           return;
1243         }
1244         try
1245         {
1246           sfile = tfile.getAbsoluteFile().toURI().toURL();
1247         } catch (Exception ex)
1248         {
1249           System.err.println("Failed to create a file URL for "
1250                   + tfile.getAbsoluteFile());
1251           return;
1252         }
1253       }
1254     }
1255     try
1256     {
1257       Map<String, java.lang.Object> vbinding = new HashMap<>();
1258       vbinding.put("Jalview", this);
1259       if (af != null)
1260       {
1261         vbinding.put("currentAlFrame", af);
1262       }
1263       Binding gbinding = new Binding(vbinding);
1264       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1265       gse.run(sfile.toString(), gbinding);
1266       if ("STDIN".equals(groovyscript))
1267       {
1268         // delete temp file that we made -
1269         // only if it was successfully executed
1270         tfile.delete();
1271       }
1272     } catch (Exception e)
1273     {
1274       System.err.println("Exception Whilst trying to execute file " + sfile
1275               + " as a groovy script.");
1276       e.printStackTrace(System.err);
1277
1278     }
1279   }
1280
1281   public static boolean isHeadlessMode()
1282   {
1283     String isheadless = System.getProperty("java.awt.headless");
1284     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1285     {
1286       return true;
1287     }
1288     return false;
1289   }
1290
1291   public AlignFrame[] getAlignFrames()
1292   {
1293     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1294             : Desktop.getAlignFrames();
1295
1296   }
1297
1298   /**
1299    * Quit method delegates to Desktop.quit - unless running in headless mode
1300    * when it just ends the JVM
1301    */
1302   public void quit()
1303   {
1304     if (desktop != null)
1305     {
1306       desktop.quit();
1307     }
1308     else
1309     {
1310       System.exit(0);
1311     }
1312   }
1313
1314   public static AlignFrame getCurrentAlignFrame()
1315   {
1316     return Jalview.getInstance().currentAlignFrame;
1317   }
1318
1319   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1320   {
1321     Jalview.getInstance().currentAlignFrame = currentAlignFrame;
1322   }
1323
1324   
1325   public void notifyWorker(AlignCalcWorkerI worker, String status)
1326   {
1327     // System.out.println("Jalview worker " + worker.getClass().getSimpleName()
1328     // + " " + status);
1329   }
1330
1331
1332   private static boolean isInteractive = true;
1333
1334   public static boolean isInteractive()
1335   {
1336     return isInteractive;
1337   }
1338
1339   public static void setInteractive(boolean tf)
1340   {
1341     isInteractive = tf;
1342   }
1343
1344 }