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