JAL-3608 Added java builtin NimbusLookAndFeel option 'nimbus'
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import java.io.BufferedReader;
24 import java.io.File;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStreamReader;
28 import java.io.OutputStreamWriter;
29 import java.io.PrintWriter;
30 import java.net.MalformedURLException;
31 import java.net.URI;
32 import java.net.URISyntaxException;
33 import java.net.URL;
34 import java.security.AllPermission;
35 import java.security.CodeSource;
36 import java.security.PermissionCollection;
37 import java.security.Permissions;
38 import java.security.Policy;
39 import java.util.HashMap;
40 import java.util.Map;
41 import java.util.Vector;
42 import java.util.logging.ConsoleHandler;
43 import java.util.logging.Level;
44 import java.util.logging.Logger;
45
46 import javax.swing.LookAndFeel;
47 import javax.swing.UIManager;
48 import javax.swing.UIManager.LookAndFeelInfo;
49
50 import com.threerings.getdown.util.LaunchUtil;
51
52 import groovy.lang.Binding;
53 import groovy.util.GroovyScriptEngine;
54 import jalview.ext.so.SequenceOntology;
55 import jalview.gui.AlignFrame;
56 import jalview.gui.Desktop;
57 import jalview.gui.PromptUserConfig;
58 import jalview.io.AppletFormatAdapter;
59 import jalview.io.BioJsHTMLOutput;
60 import jalview.io.DataSourceType;
61 import jalview.io.FileFormat;
62 import jalview.io.FileFormatException;
63 import jalview.io.FileFormatI;
64 import jalview.io.FileLoader;
65 import jalview.io.HtmlSvgOutput;
66 import jalview.io.IdentifyFile;
67 import jalview.io.NewickFile;
68 import jalview.io.gff.SequenceOntologyFactory;
69 import jalview.schemes.ColourSchemeI;
70 import jalview.schemes.ColourSchemeProperty;
71 import jalview.util.MessageManager;
72 import jalview.util.Platform;
73 import jalview.ws.jws2.Jws2Discoverer;
74
75 /**
76  * Main class for Jalview Application <br>
77  * <br>
78  * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
79  * jalview.bin.Jalview
80  * 
81  * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
82  * jalview.bin.Jalview jalview.bin.Jalview
83  * 
84  * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
85  * embellish '*' to e.g. '*.jar')
86  * 
87  * @author $author$
88  * @version $Revision$
89  */
90 public class Jalview
91 {
92   static
93   {
94     Platform.getURLCommandArguments();
95   }
96
97   // singleton instance of this class
98
99   private static Jalview instance;
100
101   private Desktop desktop;
102
103   public static AlignFrame currentAlignFrame;
104
105   static
106   {
107     if (!Platform.isJS())
108     /**
109      * Java only
110      * 
111      * @j2sIgnore
112      */
113     {
114       // grab all the rights we can for the JVM
115       Policy.setPolicy(new Policy()
116       {
117         @Override
118         public PermissionCollection getPermissions(CodeSource codesource)
119         {
120           Permissions perms = new Permissions();
121           perms.add(new AllPermission());
122           return (perms);
123         }
124
125         @Override
126         public void refresh()
127         {
128         }
129       });
130     }
131   }
132
133   /**
134    * keep track of feature fetching tasks.
135    * 
136    * @author JimP
137    * 
138    */
139   class FeatureFetcher
140   {
141     /*
142      * TODO: generalise to track all jalview events to orchestrate batch processing
143      * events.
144      */
145
146     private int queued = 0;
147
148     private int running = 0;
149
150     public FeatureFetcher()
151     {
152
153     }
154
155     public void addFetcher(final AlignFrame af,
156             final Vector<String> dasSources)
157     {
158       final long id = System.currentTimeMillis();
159       queued++;
160       final FeatureFetcher us = this;
161       new Thread(new Runnable()
162       {
163
164         @Override
165         public void run()
166         {
167           synchronized (us)
168           {
169             queued--;
170             running++;
171           }
172
173           af.setProgressBar(MessageManager
174                   .getString("status.das_features_being_retrived"), id);
175           af.featureSettings_actionPerformed(null);
176           af.setProgressBar(null, id);
177           synchronized (us)
178           {
179             running--;
180           }
181         }
182       }).start();
183     }
184
185     public synchronized boolean allFinished()
186     {
187       return queued == 0 && running == 0;
188     }
189
190   }
191
192   public static Jalview getInstance()
193   {
194     return instance;
195   }
196
197   /**
198    * main class for Jalview application
199    * 
200    * @param args
201    *          open <em>filename</em>
202    */
203   public static void main(String[] args)
204   {
205     // setLogging(); // BH - for event debugging in JavaScript
206     instance = new Jalview();
207     instance.doMain(args);
208   }
209
210   private static void logClass(String name)
211   {
212     // BH - for event debugging in JavaScript
213     ConsoleHandler consoleHandler = new ConsoleHandler();
214     consoleHandler.setLevel(Level.ALL);
215     Logger logger = Logger.getLogger(name);
216     logger.setLevel(Level.ALL);
217     logger.addHandler(consoleHandler);
218   }
219
220   @SuppressWarnings("unused")
221   private static void setLogging()
222   {
223
224     /**
225      * @j2sIgnore
226      * 
227      */
228     {
229       System.out.println("not in js");
230     }
231
232     // BH - for event debugging in JavaScript (Java mode only)
233     if (!Platform.isJS())
234     /**
235      * Java only
236      * 
237      * @j2sIgnore
238      */
239     {
240       Logger.getLogger("").setLevel(Level.ALL);
241       logClass("java.awt.EventDispatchThread");
242       logClass("java.awt.EventQueue");
243       logClass("java.awt.Component");
244       logClass("java.awt.focus.Component");
245       logClass("java.awt.focus.DefaultKeyboardFocusManager");
246     }
247
248   }
249
250   /**
251    * @param args
252    */
253   void doMain(String[] args)
254   {
255
256     if (!Platform.isJS())
257     {
258       System.setSecurityManager(null);
259     }
260
261     System.out
262             .println("Java version: " + System.getProperty("java.version"));
263     System.out.println("Java Home: " + System.getProperty("java.home"));
264     System.out.println(System.getProperty("os.arch") + " "
265             + System.getProperty("os.name") + " "
266             + System.getProperty("os.version"));
267     String val = System.getProperty("sys.install4jVersion");
268     if (val != null)
269     {
270       System.out.println("Install4j version: " + val);
271     }
272     val = System.getProperty("installer_template_version");
273     if (val != null)
274     {
275       System.out.println("Install4j template version: " + val);
276     }
277     val = System.getProperty("launcher_version");
278     if (val != null)
279     {
280       System.out.println("Launcher version: " + val);
281     }
282
283     // report Jalview version
284     Cache.loadBuildProperties(true);
285
286     ArgsParser aparser = new ArgsParser(args);
287     boolean headless = false;
288
289     String usrPropsFile = aparser.getValue("props");
290     Cache.loadProperties(usrPropsFile); // must do this before
291     if (usrPropsFile != null)
292     {
293       System.out.println(
294               "CMD [-props " + usrPropsFile + "] executed successfully!");
295     }
296
297     if (!Platform.isJS())
298     /**
299      * Java only
300      * 
301      * @j2sIgnore
302      */
303     {
304       if (aparser.contains("help") || aparser.contains("h"))
305       {
306         showUsage();
307         System.exit(0);
308       }
309       if (aparser.contains("nodisplay") || aparser.contains("nogui")
310               || aparser.contains("headless"))
311       {
312         System.setProperty("java.awt.headless", "true");
313         headless = true;
314       }
315       // anything else!
316
317       final String jabawsUrl = aparser.getValue("jabaws");
318       if (jabawsUrl != null)
319       {
320         try
321         {
322           Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
323           System.out.println(
324                   "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
325         } catch (MalformedURLException e)
326         {
327           System.err.println(
328                   "Invalid jabaws parameter: " + jabawsUrl + " ignored");
329         }
330       }
331
332     }
333     String defs = aparser.getValue("setprop");
334     while (defs != null)
335     {
336       int p = defs.indexOf('=');
337       if (p == -1)
338       {
339         System.err.println("Ignoring invalid setprop argument : " + defs);
340       }
341       else
342       {
343         System.out.println("Executing setprop argument: " + defs);
344         if (Platform.isJS())
345         {
346           Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
347         }
348       }
349       defs = aparser.getValue("setprop");
350     }
351     if (System.getProperty("java.awt.headless") != null
352             && System.getProperty("java.awt.headless").equals("true"))
353     {
354       headless = true;
355     }
356     System.setProperty("http.agent",
357             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
358     try
359     {
360       Cache.initLogger();
361     } catch (NoClassDefFoundError error)
362     {
363       error.printStackTrace();
364       System.out.println("\nEssential logging libraries not found."
365               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
366       System.exit(0);
367     }
368
369     desktop = null;
370
371     // property laf = "crossplatform", "system", "gtk", "metal" or "mac"
372     // If not set (or chosen laf fails), use the normal SystemLaF and if on Mac,
373     // try Quaqua/Vaqua.
374     String laf = System.getProperty("laf", "none");
375     boolean lafSet = false;
376     switch (laf)
377     {
378     case "crossplatform":
379       lafSet = setCrossPlatformLookAndFeel();
380       if (!lafSet)
381       {
382         System.err.println("Could not set requested laf=" + laf);
383       }
384       break;
385     case "system":
386       lafSet = setSystemLookAndFeel();
387       if (!lafSet)
388       {
389         System.err.println("Could not set requested laf=" + laf);
390       }
391       break;
392     case "gtk":
393       lafSet = setGtkLookAndFeel();
394       {
395         System.err.println("Could not set requested laf=" + laf);
396       }
397       break;
398     case "metal":
399       lafSet = setMetalLookAndFeel();
400       {
401         System.err.println("Could not set requested laf=" + laf);
402       }
403       break;
404     case "nimbus":
405       lafSet = setNimbusLookAndFeel();
406       {
407         System.err.println("Could not set requested laf=" + laf);
408       }
409       break;
410     case "mac":
411       lafSet = setMacLookAndFeel();
412       if (!lafSet)
413       {
414         System.err.println("Could not set requested laf=" + laf);
415       }
416       break;
417     case "none":
418       break;
419     default:
420       System.err.println("Requested laf=" + laf + " not implemented");
421     }
422     if (!lafSet)
423     {
424       setSystemLookAndFeel();
425       if (Platform.isLinux() && ! Platform.isJS()) {
426         setMetalLookAndFeel();
427       }
428       if (Platform.isAMacAndNotJS())
429       {
430         setMacLookAndFeel();
431       }
432     }
433
434     /*
435      * configure 'full' SO model if preferences say to, else use the default (full SO)
436      * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
437      */
438     boolean soDefault = !Platform.isJS();
439     if (Cache.getDefault("USE_FULL_SO", soDefault))
440     {
441       SequenceOntologyFactory.setInstance(new SequenceOntology());
442     }
443
444     if (!headless)
445     {
446       desktop = new Desktop();
447       desktop.setInBatchMode(true); // indicate we are starting up
448
449       try
450       {
451         JalviewTaskbar.setTaskbar(this);
452       } catch (Throwable t)
453       {
454         System.out.println("Error setting Taskbar: " + t.getMessage());
455       }
456
457       desktop.setVisible(true);
458
459       if (!Platform.isJS())
460       /**
461        * Java only
462        * 
463        * @j2sIgnore
464        */
465       {
466         desktop.startServiceDiscovery();
467         if (!aparser.contains("nousagestats"))
468         {
469           startUsageStats(desktop);
470         }
471         else
472         {
473           System.err.println("CMD [-nousagestats] executed successfully!");
474         }
475
476         if (!aparser.contains("noquestionnaire"))
477         {
478           String url = aparser.getValue("questionnaire");
479           if (url != null)
480           {
481             // Start the desktop questionnaire prompter with the specified
482             // questionnaire
483             Cache.log.debug("Starting questionnaire url at " + url);
484             desktop.checkForQuestionnaire(url);
485             System.out.println("CMD questionnaire[-" + url
486                     + "] executed successfully!");
487           }
488           else
489           {
490             if (Cache.getProperty("NOQUESTIONNAIRES") == null)
491             {
492               // Start the desktop questionnaire prompter with the specified
493               // questionnaire
494               // String defurl =
495               // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
496               // //
497               String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
498               Cache.log.debug(
499                       "Starting questionnaire with default url: " + defurl);
500               desktop.checkForQuestionnaire(defurl);
501             }
502           }
503         }
504         else
505         {
506           System.err
507                   .println("CMD [-noquestionnaire] executed successfully!");
508         }
509
510         if (!aparser.contains("nonews"))
511         {
512           desktop.checkForNews();
513         }
514
515         BioJsHTMLOutput.updateBioJS();
516       }
517     }
518
519     // Move any new getdown-launcher-new.jar into place over old
520     // getdown-launcher.jar
521     String appdirString = System.getProperty("getdownappdir");
522     if (appdirString != null && appdirString.length() > 0)
523     {
524       final File appdir = new File(appdirString);
525       new Thread()
526       {
527         @Override
528         public void run()
529         {
530           LaunchUtil.upgradeGetdown(
531                   new File(appdir, "getdown-launcher-old.jar"),
532                   new File(appdir, "getdown-launcher.jar"),
533                   new File(appdir, "getdown-launcher-new.jar"));
534         }
535       }.start();
536     }
537
538     String file = null, data = null;
539     FileFormatI format = null;
540     DataSourceType protocol = null;
541     FileLoader fileLoader = new FileLoader(!headless);
542
543     String groovyscript = null; // script to execute after all loading is
544     // completed one way or another
545     // extract groovy argument and execute if necessary
546     groovyscript = aparser.getValue("groovy", true);
547     file = aparser.getValue("open", true);
548
549     if (file == null && desktop == null)
550     {
551       System.out.println("No files to open!");
552       System.exit(1);
553     }
554     long progress = -1;
555     // Finally, deal with the remaining input data.
556     if (file != null)
557     {
558       if (!headless)
559       {
560         desktop.setProgressBar(
561                 MessageManager
562                         .getString("status.processing_commandline_args"),
563                 progress = System.currentTimeMillis());
564       }
565       System.out.println("CMD [-open " + file + "] executed successfully!");
566
567       if (!Platform.isJS())
568       /**
569        * ignore in JavaScript -- can't just file existence - could load it?
570        * 
571        * @j2sIgnore
572        */
573       {
574         if (!file.startsWith("http://") && !file.startsWith("https://"))
575         // BH 2019 added https check for Java
576         {
577           if (!(new File(file)).exists())
578           {
579             System.out.println("Can't find " + file);
580             if (headless)
581             {
582               System.exit(1);
583             }
584           }
585         }
586       }
587
588       protocol = AppletFormatAdapter.checkProtocol(file);
589
590       try
591       {
592         format = new IdentifyFile().identify(file, protocol);
593       } catch (FileFormatException e1)
594       {
595         // TODO ?
596       }
597
598       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
599               format);
600       if (af == null)
601       {
602         System.out.println("error");
603       }
604       else
605       {
606         setCurrentAlignFrame(af);
607         data = aparser.getValue("colour", true);
608         if (data != null)
609         {
610           data.replaceAll("%20", " ");
611
612           ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
613                   af.getViewport(), af.getViewport().getAlignment(), data);
614
615           if (cs != null)
616           {
617             System.out.println(
618                     "CMD [-color " + data + "] executed successfully!");
619           }
620           af.changeColour(cs);
621         }
622
623         // Must maintain ability to use the groups flag
624         data = aparser.getValue("groups", true);
625         if (data != null)
626         {
627           af.parseFeaturesFile(data,
628                   AppletFormatAdapter.checkProtocol(data));
629           // System.out.println("Added " + data);
630           System.out.println(
631                   "CMD groups[-" + data + "]  executed successfully!");
632         }
633         data = aparser.getValue("features", true);
634         if (data != null)
635         {
636           af.parseFeaturesFile(data,
637                   AppletFormatAdapter.checkProtocol(data));
638           // System.out.println("Added " + data);
639           System.out.println(
640                   "CMD [-features " + data + "]  executed successfully!");
641         }
642
643         data = aparser.getValue("annotations", true);
644         if (data != null)
645         {
646           af.loadJalviewDataFile(data, null, null, null);
647           // System.out.println("Added " + data);
648           System.out.println(
649                   "CMD [-annotations " + data + "] executed successfully!");
650         }
651         // set or clear the sortbytree flag.
652         if (aparser.contains("sortbytree"))
653         {
654           af.getViewport().setSortByTree(true);
655           if (af.getViewport().getSortByTree())
656           {
657             System.out.println("CMD [-sortbytree] executed successfully!");
658           }
659         }
660         if (aparser.contains("no-annotation"))
661         {
662           af.getViewport().setShowAnnotation(false);
663           if (!af.getViewport().isShowAnnotation())
664           {
665             System.out.println("CMD no-annotation executed successfully!");
666           }
667         }
668         if (aparser.contains("nosortbytree"))
669         {
670           af.getViewport().setSortByTree(false);
671           if (!af.getViewport().getSortByTree())
672           {
673             System.out
674                     .println("CMD [-nosortbytree] executed successfully!");
675           }
676         }
677         data = aparser.getValue("tree", true);
678         if (data != null)
679         {
680           try
681           {
682             System.out.println(
683                     "CMD [-tree " + data + "] executed successfully!");
684             NewickFile nf = new NewickFile(data,
685                     AppletFormatAdapter.checkProtocol(data));
686             af.getViewport()
687                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
688           } catch (IOException ex)
689           {
690             System.err.println("Couldn't add tree " + data);
691             ex.printStackTrace(System.err);
692           }
693         }
694         // TODO - load PDB structure(s) to alignment JAL-629
695         // (associate with identical sequence in alignment, or a specified
696         // sequence)
697         if (groovyscript != null)
698         {
699           // Execute the groovy script after we've done all the rendering stuff
700           // and before any images or figures are generated.
701           System.out.println("Executing script " + groovyscript);
702           executeGroovyScript(groovyscript, af);
703           System.out.println("CMD groovy[" + groovyscript
704                   + "] executed successfully!");
705           groovyscript = null;
706         }
707         String imageName = "unnamed.png";
708         while (aparser.getSize() > 1)
709         {
710           String outputFormat = aparser.nextValue();
711           file = aparser.nextValue();
712
713           if (outputFormat.equalsIgnoreCase("png"))
714           {
715             af.createPNG(new File(file));
716             imageName = (new File(file)).getName();
717             System.out.println("Creating PNG image: " + file);
718             continue;
719           }
720           else if (outputFormat.equalsIgnoreCase("svg"))
721           {
722             File imageFile = new File(file);
723             imageName = imageFile.getName();
724             af.createSVG(imageFile);
725             System.out.println("Creating SVG image: " + file);
726             continue;
727           }
728           else if (outputFormat.equalsIgnoreCase("html"))
729           {
730             File imageFile = new File(file);
731             imageName = imageFile.getName();
732             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
733             htmlSVG.exportHTML(file);
734
735             System.out.println("Creating HTML image: " + file);
736             continue;
737           }
738           else if (outputFormat.equalsIgnoreCase("biojsmsa"))
739           {
740             if (file == null)
741             {
742               System.err.println("The output html file must not be null");
743               return;
744             }
745             try
746             {
747               BioJsHTMLOutput.refreshVersionInfo(
748                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
749             } catch (URISyntaxException e)
750             {
751               e.printStackTrace();
752             }
753             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
754             bjs.exportHTML(file);
755             System.out
756                     .println("Creating BioJS MSA Viwer HTML file: " + file);
757             continue;
758           }
759           else if (outputFormat.equalsIgnoreCase("imgMap"))
760           {
761             af.createImageMap(new File(file), imageName);
762             System.out.println("Creating image map: " + file);
763             continue;
764           }
765           else if (outputFormat.equalsIgnoreCase("eps"))
766           {
767             File outputFile = new File(file);
768             System.out.println(
769                     "Creating EPS file: " + outputFile.getAbsolutePath());
770             af.createEPS(outputFile);
771             continue;
772           }
773
774           af.saveAlignment(file, format);
775           if (af.isSaveAlignmentSuccessful())
776           {
777             System.out.println("Written alignment in " + format
778                     + " format to " + file);
779           }
780           else
781           {
782             System.out.println("Error writing file " + file + " in "
783                     + format + " format!!");
784           }
785
786         }
787
788         while (aparser.getSize() > 0)
789         {
790           System.out.println("Unknown arg: " + aparser.nextValue());
791         }
792       }
793     }
794     AlignFrame startUpAlframe = null;
795     // We'll only open the default file if the desktop is visible.
796     // And the user
797     // ////////////////////
798
799     if (!Platform.isJS() && !headless && file == null
800             && Cache.getDefault("SHOW_STARTUP_FILE", true))
801     /**
802      * Java only
803      * 
804      * @j2sIgnore
805      */
806     {
807       file = Cache.getDefault("STARTUP_FILE",
808               Cache.getDefault("www.jalview.org", "http://www.jalview.org")
809                       + "/examples/exampleFile_2_7.jar");
810       if (file.equals(
811               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
812       {
813         // hardwire upgrade of the startup file
814         file.replace("_2_3.jar", "_2_7.jar");
815         // and remove the stale setting
816         Cache.removeProperty("STARTUP_FILE");
817       }
818
819       protocol = DataSourceType.FILE;
820
821       if (file.indexOf("http:") > -1)
822       {
823         protocol = DataSourceType.URL;
824       }
825
826       if (file.endsWith(".jar"))
827       {
828         format = FileFormat.Jalview;
829       }
830       else
831       {
832         try
833         {
834           format = new IdentifyFile().identify(file, protocol);
835         } catch (FileFormatException e)
836         {
837           // TODO what?
838         }
839       }
840
841       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
842               format);
843       // extract groovy arguments before anything else.
844     }
845
846     // Once all other stuff is done, execute any groovy scripts (in order)
847     if (groovyscript != null)
848     {
849       if (Cache.groovyJarsPresent())
850       {
851         System.out.println("Executing script " + groovyscript);
852         executeGroovyScript(groovyscript, startUpAlframe);
853       }
854       else
855       {
856         System.err.println(
857                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
858                         + groovyscript);
859       }
860     }
861     // and finally, turn off batch mode indicator - if the desktop still exists
862     if (desktop != null)
863     {
864       if (progress != -1)
865       {
866         desktop.setProgressBar(null, progress);
867       }
868       desktop.setInBatchMode(false);
869     }
870   }
871
872   private static boolean setCrossPlatformLookAndFeel()
873   {
874     boolean set = false;
875     try
876     {
877       UIManager.setLookAndFeel(
878               UIManager.getCrossPlatformLookAndFeelClassName());
879       set = true;
880     } catch (Exception ex)
881     {
882       System.err.println("Unexpected Look and Feel Exception");
883       ex.printStackTrace();
884     }
885     return set;
886   }
887
888   private static boolean setSystemLookAndFeel()
889   {
890     boolean set = false;
891     try
892     {
893       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
894       set = true;
895     } catch (Exception ex)
896     {
897       System.err.println("Unexpected Look and Feel Exception");
898       ex.printStackTrace();
899     }
900     return set;
901   }
902
903   private static boolean setGtkLookAndFeel()
904   {
905     boolean set = false;
906     String laf = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
907     try
908     {
909       for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
910         if (info.getName() != null && info.getName().startsWith("Gtk")) {
911           laf = info.getClassName();
912           break;
913         }
914       }
915       UIManager.setLookAndFeel(laf);
916       set = true;
917     } catch (Exception ex)
918     {
919       System.err.println("Unexpected Look and Feel Exception");
920       ex.printStackTrace();
921     }
922     return set;
923   }
924
925   private static boolean setMetalLookAndFeel()
926   {
927     boolean set = false;
928     String laf = "javax.swing.plaf.metal.MetalLookAndFeel";
929     try
930     {
931       for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
932         if (info.getName() != null && info.getName().equals("Metal")) {
933           laf = info.getClassName();
934           break;
935         }
936       }
937       UIManager.setLookAndFeel(laf);
938       set = true;
939     } catch (Exception ex)
940     {
941       System.err.println("Unexpected Look and Feel Exception");
942       ex.printStackTrace();
943     }
944     return set;
945   }
946
947   private static boolean setNimbusLookAndFeel()
948   {
949     boolean set = false;
950     String laf = "javax.swing.plaf.nimbus.NimbusLookAndFeel";
951     try
952     {
953       for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
954         if (info.getName() != null && info.getName().equals("Nimbus")) {
955           laf = info.getClassName();
956           break;
957         }
958       }
959       UIManager.setLookAndFeel(laf);
960       set = true;
961     } catch (Exception ex)
962     {
963       System.err.println("Unexpected Look and Feel Exception");
964       ex.printStackTrace();
965     }
966     return set;
967   }
968
969   private static boolean setMacLookAndFeel()
970   {
971     boolean set = false;
972     LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
973             .getLookAndFeel();
974     System.setProperty("com.apple.mrj.application.apple.menu.about.name",
975             "Jalview");
976     System.setProperty("apple.laf.useScreenMenuBar", "true");
977     if (lookAndFeel != null)
978     {
979       try
980       {
981         UIManager.setLookAndFeel(lookAndFeel);
982         set = true;
983       } catch (Throwable e)
984       {
985         System.err.println(
986                 "Failed to set QuaQua look and feel: " + e.toString());
987       }
988     }
989     if (lookAndFeel == null
990             || !(lookAndFeel.getClass().isAssignableFrom(
991                     UIManager.getLookAndFeel().getClass()))
992             || !UIManager.getLookAndFeel().getClass().toString()
993                     .toLowerCase().contains("quaqua"))
994     {
995       try
996       {
997         System.err.println(
998                 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
999         UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
1000         set = true;
1001       } catch (Throwable e)
1002       {
1003         System.err
1004                 .println("Failed to reset look and feel: " + e.toString());
1005       }
1006     }
1007     return set;
1008   }
1009
1010   private static void showUsage()
1011   {
1012     System.out.println(
1013             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1014                     + "-nodisplay\tRun Jalview without User Interface.\n"
1015                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1016                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1017                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1018                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1019                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
1020                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1021                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1022                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1023                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1024                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1025                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1026                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1027                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1028                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1029                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
1030                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1031                     + "-html FILE\tCreate HTML file from alignment.\n"
1032                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1033                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1034                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1035                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1036                     + "-noquestionnaire\tTurn off questionnaire check.\n"
1037                     + "-nonews\tTurn off check for Jalview news.\n"
1038                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1039                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1040                     // +
1041                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1042                     // after all other properties files have been read\n\t
1043                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1044                     // passed in correctly)"
1045                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1046                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1047                     + "-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"
1048                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1049   }
1050
1051   private static void startUsageStats(final Desktop desktop)
1052   {
1053     /**
1054      * start a User Config prompt asking if we can log usage statistics.
1055      */
1056     PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
1057             "USAGESTATS", "Jalview Usage Statistics",
1058             "Do you want to help make Jalview better by enabling "
1059                     + "the collection of usage statistics with Google Analytics ?"
1060                     + "\n\n(you can enable or disable usage tracking in the preferences)",
1061             new Runnable()
1062             {
1063               @Override
1064               public void run()
1065               {
1066                 Cache.log.debug(
1067                         "Initialising googletracker for usage stats.");
1068                 Cache.initGoogleTracker();
1069                 Cache.log.debug("Tracking enabled.");
1070               }
1071             }, new Runnable()
1072             {
1073               @Override
1074               public void run()
1075               {
1076                 Cache.log.debug("Not enabling Google Tracking.");
1077               }
1078             }, null, true);
1079     desktop.addDialogThread(prompter);
1080   }
1081
1082   /**
1083    * Locate the given string as a file and pass it to the groovy interpreter.
1084    * 
1085    * @param groovyscript
1086    *          the script to execute
1087    * @param jalviewContext
1088    *          the Jalview Desktop object passed in to the groovy binding as the
1089    *          'Jalview' object.
1090    */
1091   private void executeGroovyScript(String groovyscript, AlignFrame af)
1092   {
1093     /**
1094      * for scripts contained in files
1095      */
1096     File tfile = null;
1097     /**
1098      * script's URI
1099      */
1100     URL sfile = null;
1101     if (groovyscript.trim().equals("STDIN"))
1102     {
1103       // read from stdin into a tempfile and execute it
1104       try
1105       {
1106         tfile = File.createTempFile("jalview", "groovy");
1107         PrintWriter outfile = new PrintWriter(
1108                 new OutputStreamWriter(new FileOutputStream(tfile)));
1109         BufferedReader br = new BufferedReader(
1110                 new InputStreamReader(System.in));
1111         String line = null;
1112         while ((line = br.readLine()) != null)
1113         {
1114           outfile.write(line + "\n");
1115         }
1116         br.close();
1117         outfile.flush();
1118         outfile.close();
1119
1120       } catch (Exception ex)
1121       {
1122         System.err.println("Failed to read from STDIN into tempfile "
1123                 + ((tfile == null) ? "(tempfile wasn't created)"
1124                         : tfile.toString()));
1125         ex.printStackTrace();
1126         return;
1127       }
1128       try
1129       {
1130         sfile = tfile.toURI().toURL();
1131       } catch (Exception x)
1132       {
1133         System.err.println(
1134                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1135                         + tfile.toURI());
1136         x.printStackTrace();
1137         return;
1138       }
1139     }
1140     else
1141     {
1142       try
1143       {
1144         sfile = new URI(groovyscript).toURL();
1145       } catch (Exception x)
1146       {
1147         tfile = new File(groovyscript);
1148         if (!tfile.exists())
1149         {
1150           System.err.println("File '" + groovyscript + "' does not exist.");
1151           return;
1152         }
1153         if (!tfile.canRead())
1154         {
1155           System.err.println("File '" + groovyscript + "' cannot be read.");
1156           return;
1157         }
1158         if (tfile.length() < 1)
1159         {
1160           System.err.println("File '" + groovyscript + "' is empty.");
1161           return;
1162         }
1163         try
1164         {
1165           sfile = tfile.getAbsoluteFile().toURI().toURL();
1166         } catch (Exception ex)
1167         {
1168           System.err.println("Failed to create a file URL for "
1169                   + tfile.getAbsoluteFile());
1170           return;
1171         }
1172       }
1173     }
1174     try
1175     {
1176       Map<String, java.lang.Object> vbinding = new HashMap<>();
1177       vbinding.put("Jalview", this);
1178       if (af != null)
1179       {
1180         vbinding.put("currentAlFrame", af);
1181       }
1182       Binding gbinding = new Binding(vbinding);
1183       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1184       gse.run(sfile.toString(), gbinding);
1185       if ("STDIN".equals(groovyscript))
1186       {
1187         // delete temp file that we made -
1188         // only if it was successfully executed
1189         tfile.delete();
1190       }
1191     } catch (Exception e)
1192     {
1193       System.err.println("Exception Whilst trying to execute file " + sfile
1194               + " as a groovy script.");
1195       e.printStackTrace(System.err);
1196
1197     }
1198   }
1199
1200   public static boolean isHeadlessMode()
1201   {
1202     String isheadless = System.getProperty("java.awt.headless");
1203     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1204     {
1205       return true;
1206     }
1207     return false;
1208   }
1209
1210   public AlignFrame[] getAlignFrames()
1211   {
1212     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1213             : Desktop.getAlignFrames();
1214
1215   }
1216
1217   /**
1218    * Quit method delegates to Desktop.quit - unless running in headless mode
1219    * when it just ends the JVM
1220    */
1221   public void quit()
1222   {
1223     if (desktop != null)
1224     {
1225       desktop.quit();
1226     }
1227     else
1228     {
1229       System.exit(0);
1230     }
1231   }
1232
1233   public static AlignFrame getCurrentAlignFrame()
1234   {
1235     return Jalview.currentAlignFrame;
1236   }
1237
1238   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1239   {
1240     Jalview.currentAlignFrame = currentAlignFrame;
1241   }
1242 }