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