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