JAL-3608 also look at user pref PREFERRED_LAF
[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 lafProp = System.getProperty("laf");
375     String lafSetting = Cache.getDefault("PREFERRED_LAF", null);
376     String laf = "none";
377     if (lafProp != null) {
378         laf = lafProp;
379     } else if (lafSetting != null) {
380         laf = lafSetting;
381     }
382     boolean lafSet = false;
383     switch (laf)
384     {
385     case "crossplatform":
386       lafSet = setCrossPlatformLookAndFeel();
387       if (!lafSet)
388       {
389         System.err.println("Could not set requested laf=" + laf);
390       }
391       break;
392     case "system":
393       lafSet = setSystemLookAndFeel();
394       if (!lafSet)
395       {
396         System.err.println("Could not set requested laf=" + laf);
397       }
398       break;
399     case "gtk":
400       lafSet = setGtkLookAndFeel();
401       {
402         System.err.println("Could not set requested laf=" + laf);
403       }
404       break;
405     case "metal":
406       lafSet = setMetalLookAndFeel();
407       {
408         System.err.println("Could not set requested laf=" + laf);
409       }
410       break;
411     case "nimbus":
412       lafSet = setNimbusLookAndFeel();
413       {
414         System.err.println("Could not set requested laf=" + laf);
415       }
416       break;
417     case "mac":
418       lafSet = setMacLookAndFeel();
419       if (!lafSet)
420       {
421         System.err.println("Could not set requested laf=" + laf);
422       }
423       break;
424     case "none":
425       break;
426     default:
427       System.err.println("Requested laf=" + laf + " not implemented");
428     }
429     if (!lafSet)
430     {
431       setSystemLookAndFeel();
432       if (Platform.isLinux() && ! Platform.isJS()) {
433         setMetalLookAndFeel();
434       }
435       if (Platform.isAMacAndNotJS())
436       {
437         setMacLookAndFeel();
438       }
439     }
440
441     /*
442      * configure 'full' SO model if preferences say to, else use the default (full SO)
443      * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
444      */
445     boolean soDefault = !Platform.isJS();
446     if (Cache.getDefault("USE_FULL_SO", soDefault))
447     {
448       SequenceOntologyFactory.setInstance(new SequenceOntology());
449     }
450
451     if (!headless)
452     {
453       desktop = new Desktop();
454       desktop.setInBatchMode(true); // indicate we are starting up
455
456       try
457       {
458         JalviewTaskbar.setTaskbar(this);
459       } catch (Throwable t)
460       {
461         System.out.println("Error setting Taskbar: " + t.getMessage());
462       }
463
464       desktop.setVisible(true);
465
466       if (!Platform.isJS())
467       /**
468        * Java only
469        * 
470        * @j2sIgnore
471        */
472       {
473         desktop.startServiceDiscovery();
474         if (!aparser.contains("nousagestats"))
475         {
476           startUsageStats(desktop);
477         }
478         else
479         {
480           System.err.println("CMD [-nousagestats] executed successfully!");
481         }
482
483         if (!aparser.contains("noquestionnaire"))
484         {
485           String url = aparser.getValue("questionnaire");
486           if (url != null)
487           {
488             // Start the desktop questionnaire prompter with the specified
489             // questionnaire
490             Cache.log.debug("Starting questionnaire url at " + url);
491             desktop.checkForQuestionnaire(url);
492             System.out.println("CMD questionnaire[-" + url
493                     + "] executed successfully!");
494           }
495           else
496           {
497             if (Cache.getProperty("NOQUESTIONNAIRES") == null)
498             {
499               // Start the desktop questionnaire prompter with the specified
500               // questionnaire
501               // String defurl =
502               // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
503               // //
504               String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
505               Cache.log.debug(
506                       "Starting questionnaire with default url: " + defurl);
507               desktop.checkForQuestionnaire(defurl);
508             }
509           }
510         }
511         else
512         {
513           System.err
514                   .println("CMD [-noquestionnaire] executed successfully!");
515         }
516
517         if (!aparser.contains("nonews"))
518         {
519           desktop.checkForNews();
520         }
521
522         BioJsHTMLOutput.updateBioJS();
523       }
524     }
525
526     // Move any new getdown-launcher-new.jar into place over old
527     // getdown-launcher.jar
528     String appdirString = System.getProperty("getdownappdir");
529     if (appdirString != null && appdirString.length() > 0)
530     {
531       final File appdir = new File(appdirString);
532       new Thread()
533       {
534         @Override
535         public void run()
536         {
537           LaunchUtil.upgradeGetdown(
538                   new File(appdir, "getdown-launcher-old.jar"),
539                   new File(appdir, "getdown-launcher.jar"),
540                   new File(appdir, "getdown-launcher-new.jar"));
541         }
542       }.start();
543     }
544
545     String file = null, data = null;
546     FileFormatI format = null;
547     DataSourceType protocol = null;
548     FileLoader fileLoader = new FileLoader(!headless);
549
550     String groovyscript = null; // script to execute after all loading is
551     // completed one way or another
552     // extract groovy argument and execute if necessary
553     groovyscript = aparser.getValue("groovy", true);
554     file = aparser.getValue("open", true);
555
556     if (file == null && desktop == null)
557     {
558       System.out.println("No files to open!");
559       System.exit(1);
560     }
561     long progress = -1;
562     // Finally, deal with the remaining input data.
563     if (file != null)
564     {
565       if (!headless)
566       {
567         desktop.setProgressBar(
568                 MessageManager
569                         .getString("status.processing_commandline_args"),
570                 progress = System.currentTimeMillis());
571       }
572       System.out.println("CMD [-open " + file + "] executed successfully!");
573
574       if (!Platform.isJS())
575       /**
576        * ignore in JavaScript -- can't just file existence - could load it?
577        * 
578        * @j2sIgnore
579        */
580       {
581         if (!file.startsWith("http://") && !file.startsWith("https://"))
582         // BH 2019 added https check for Java
583         {
584           if (!(new File(file)).exists())
585           {
586             System.out.println("Can't find " + file);
587             if (headless)
588             {
589               System.exit(1);
590             }
591           }
592         }
593       }
594
595       protocol = AppletFormatAdapter.checkProtocol(file);
596
597       try
598       {
599         format = new IdentifyFile().identify(file, protocol);
600       } catch (FileFormatException e1)
601       {
602         // TODO ?
603       }
604
605       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
606               format);
607       if (af == null)
608       {
609         System.out.println("error");
610       }
611       else
612       {
613         setCurrentAlignFrame(af);
614         data = aparser.getValue("colour", true);
615         if (data != null)
616         {
617           data.replaceAll("%20", " ");
618
619           ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
620                   af.getViewport(), af.getViewport().getAlignment(), data);
621
622           if (cs != null)
623           {
624             System.out.println(
625                     "CMD [-color " + data + "] executed successfully!");
626           }
627           af.changeColour(cs);
628         }
629
630         // Must maintain ability to use the groups flag
631         data = aparser.getValue("groups", true);
632         if (data != null)
633         {
634           af.parseFeaturesFile(data,
635                   AppletFormatAdapter.checkProtocol(data));
636           // System.out.println("Added " + data);
637           System.out.println(
638                   "CMD groups[-" + data + "]  executed successfully!");
639         }
640         data = aparser.getValue("features", true);
641         if (data != null)
642         {
643           af.parseFeaturesFile(data,
644                   AppletFormatAdapter.checkProtocol(data));
645           // System.out.println("Added " + data);
646           System.out.println(
647                   "CMD [-features " + data + "]  executed successfully!");
648         }
649
650         data = aparser.getValue("annotations", true);
651         if (data != null)
652         {
653           af.loadJalviewDataFile(data, null, null, null);
654           // System.out.println("Added " + data);
655           System.out.println(
656                   "CMD [-annotations " + data + "] executed successfully!");
657         }
658         // set or clear the sortbytree flag.
659         if (aparser.contains("sortbytree"))
660         {
661           af.getViewport().setSortByTree(true);
662           if (af.getViewport().getSortByTree())
663           {
664             System.out.println("CMD [-sortbytree] executed successfully!");
665           }
666         }
667         if (aparser.contains("no-annotation"))
668         {
669           af.getViewport().setShowAnnotation(false);
670           if (!af.getViewport().isShowAnnotation())
671           {
672             System.out.println("CMD no-annotation executed successfully!");
673           }
674         }
675         if (aparser.contains("nosortbytree"))
676         {
677           af.getViewport().setSortByTree(false);
678           if (!af.getViewport().getSortByTree())
679           {
680             System.out
681                     .println("CMD [-nosortbytree] executed successfully!");
682           }
683         }
684         data = aparser.getValue("tree", true);
685         if (data != null)
686         {
687           try
688           {
689             System.out.println(
690                     "CMD [-tree " + data + "] executed successfully!");
691             NewickFile nf = new NewickFile(data,
692                     AppletFormatAdapter.checkProtocol(data));
693             af.getViewport()
694                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
695           } catch (IOException ex)
696           {
697             System.err.println("Couldn't add tree " + data);
698             ex.printStackTrace(System.err);
699           }
700         }
701         // TODO - load PDB structure(s) to alignment JAL-629
702         // (associate with identical sequence in alignment, or a specified
703         // sequence)
704         if (groovyscript != null)
705         {
706           // Execute the groovy script after we've done all the rendering stuff
707           // and before any images or figures are generated.
708           System.out.println("Executing script " + groovyscript);
709           executeGroovyScript(groovyscript, af);
710           System.out.println("CMD groovy[" + groovyscript
711                   + "] executed successfully!");
712           groovyscript = null;
713         }
714         String imageName = "unnamed.png";
715         while (aparser.getSize() > 1)
716         {
717           String outputFormat = aparser.nextValue();
718           file = aparser.nextValue();
719
720           if (outputFormat.equalsIgnoreCase("png"))
721           {
722             af.createPNG(new File(file));
723             imageName = (new File(file)).getName();
724             System.out.println("Creating PNG image: " + file);
725             continue;
726           }
727           else if (outputFormat.equalsIgnoreCase("svg"))
728           {
729             File imageFile = new File(file);
730             imageName = imageFile.getName();
731             af.createSVG(imageFile);
732             System.out.println("Creating SVG image: " + file);
733             continue;
734           }
735           else if (outputFormat.equalsIgnoreCase("html"))
736           {
737             File imageFile = new File(file);
738             imageName = imageFile.getName();
739             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
740             htmlSVG.exportHTML(file);
741
742             System.out.println("Creating HTML image: " + file);
743             continue;
744           }
745           else if (outputFormat.equalsIgnoreCase("biojsmsa"))
746           {
747             if (file == null)
748             {
749               System.err.println("The output html file must not be null");
750               return;
751             }
752             try
753             {
754               BioJsHTMLOutput.refreshVersionInfo(
755                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
756             } catch (URISyntaxException e)
757             {
758               e.printStackTrace();
759             }
760             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
761             bjs.exportHTML(file);
762             System.out
763                     .println("Creating BioJS MSA Viwer HTML file: " + file);
764             continue;
765           }
766           else if (outputFormat.equalsIgnoreCase("imgMap"))
767           {
768             af.createImageMap(new File(file), imageName);
769             System.out.println("Creating image map: " + file);
770             continue;
771           }
772           else if (outputFormat.equalsIgnoreCase("eps"))
773           {
774             File outputFile = new File(file);
775             System.out.println(
776                     "Creating EPS file: " + outputFile.getAbsolutePath());
777             af.createEPS(outputFile);
778             continue;
779           }
780
781           af.saveAlignment(file, format);
782           if (af.isSaveAlignmentSuccessful())
783           {
784             System.out.println("Written alignment in " + format
785                     + " format to " + file);
786           }
787           else
788           {
789             System.out.println("Error writing file " + file + " in "
790                     + format + " format!!");
791           }
792
793         }
794
795         while (aparser.getSize() > 0)
796         {
797           System.out.println("Unknown arg: " + aparser.nextValue());
798         }
799       }
800     }
801     AlignFrame startUpAlframe = null;
802     // We'll only open the default file if the desktop is visible.
803     // And the user
804     // ////////////////////
805
806     if (!Platform.isJS() && !headless && file == null
807             && Cache.getDefault("SHOW_STARTUP_FILE", true))
808     /**
809      * Java only
810      * 
811      * @j2sIgnore
812      */
813     {
814       file = Cache.getDefault("STARTUP_FILE",
815               Cache.getDefault("www.jalview.org", "http://www.jalview.org")
816                       + "/examples/exampleFile_2_7.jar");
817       if (file.equals(
818               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
819       {
820         // hardwire upgrade of the startup file
821         file.replace("_2_3.jar", "_2_7.jar");
822         // and remove the stale setting
823         Cache.removeProperty("STARTUP_FILE");
824       }
825
826       protocol = DataSourceType.FILE;
827
828       if (file.indexOf("http:") > -1)
829       {
830         protocol = DataSourceType.URL;
831       }
832
833       if (file.endsWith(".jar"))
834       {
835         format = FileFormat.Jalview;
836       }
837       else
838       {
839         try
840         {
841           format = new IdentifyFile().identify(file, protocol);
842         } catch (FileFormatException e)
843         {
844           // TODO what?
845         }
846       }
847
848       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
849               format);
850       // extract groovy arguments before anything else.
851     }
852
853     // Once all other stuff is done, execute any groovy scripts (in order)
854     if (groovyscript != null)
855     {
856       if (Cache.groovyJarsPresent())
857       {
858         System.out.println("Executing script " + groovyscript);
859         executeGroovyScript(groovyscript, startUpAlframe);
860       }
861       else
862       {
863         System.err.println(
864                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
865                         + groovyscript);
866       }
867     }
868     // and finally, turn off batch mode indicator - if the desktop still exists
869     if (desktop != null)
870     {
871       if (progress != -1)
872       {
873         desktop.setProgressBar(null, progress);
874       }
875       desktop.setInBatchMode(false);
876     }
877   }
878
879   private static boolean setCrossPlatformLookAndFeel()
880   {
881     boolean set = false;
882     try
883     {
884       UIManager.setLookAndFeel(
885               UIManager.getCrossPlatformLookAndFeelClassName());
886       set = true;
887     } catch (Exception ex)
888     {
889       System.err.println("Unexpected Look and Feel Exception");
890       ex.printStackTrace();
891     }
892     return set;
893   }
894
895   private static boolean setSystemLookAndFeel()
896   {
897     boolean set = false;
898     try
899     {
900       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
901       set = true;
902     } catch (Exception ex)
903     {
904       System.err.println("Unexpected Look and Feel Exception");
905       ex.printStackTrace();
906     }
907     return set;
908   }
909
910   private static boolean setGtkLookAndFeel()
911   {
912     boolean set = false;
913     String laf = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
914     try
915     {
916       for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
917         if (info.getName() != null && info.getName().startsWith("Gtk")) {
918           laf = info.getClassName();
919           break;
920         }
921       }
922       UIManager.setLookAndFeel(laf);
923       set = true;
924     } catch (Exception ex)
925     {
926       System.err.println("Unexpected Look and Feel Exception");
927       ex.printStackTrace();
928     }
929     return set;
930   }
931
932   private static boolean setMetalLookAndFeel()
933   {
934     boolean set = false;
935     String laf = "javax.swing.plaf.metal.MetalLookAndFeel";
936     try
937     {
938       for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
939         if (info.getName() != null && info.getName().equals("Metal")) {
940           laf = info.getClassName();
941           break;
942         }
943       }
944       UIManager.setLookAndFeel(laf);
945       set = true;
946     } catch (Exception ex)
947     {
948       System.err.println("Unexpected Look and Feel Exception");
949       ex.printStackTrace();
950     }
951     return set;
952   }
953
954   private static boolean setNimbusLookAndFeel()
955   {
956     boolean set = false;
957     String laf = "javax.swing.plaf.nimbus.NimbusLookAndFeel";
958     try
959     {
960       for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
961         if (info.getName() != null && info.getName().equals("Nimbus")) {
962           laf = info.getClassName();
963           break;
964         }
965       }
966       UIManager.setLookAndFeel(laf);
967       set = true;
968     } catch (Exception ex)
969     {
970       System.err.println("Unexpected Look and Feel Exception");
971       ex.printStackTrace();
972     }
973     return set;
974   }
975
976   private static boolean setMacLookAndFeel()
977   {
978     boolean set = false;
979     LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
980             .getLookAndFeel();
981     System.setProperty("com.apple.mrj.application.apple.menu.about.name",
982             "Jalview");
983     System.setProperty("apple.laf.useScreenMenuBar", "true");
984     if (lookAndFeel != null)
985     {
986       try
987       {
988         UIManager.setLookAndFeel(lookAndFeel);
989         set = true;
990       } catch (Throwable e)
991       {
992         System.err.println(
993                 "Failed to set QuaQua look and feel: " + e.toString());
994       }
995     }
996     if (lookAndFeel == null
997             || !(lookAndFeel.getClass().isAssignableFrom(
998                     UIManager.getLookAndFeel().getClass()))
999             || !UIManager.getLookAndFeel().getClass().toString()
1000                     .toLowerCase().contains("quaqua"))
1001     {
1002       try
1003       {
1004         System.err.println(
1005                 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
1006         UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
1007         set = true;
1008       } catch (Throwable e)
1009       {
1010         System.err
1011                 .println("Failed to reset look and feel: " + e.toString());
1012       }
1013     }
1014     return set;
1015   }
1016
1017   private static void showUsage()
1018   {
1019     System.out.println(
1020             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1021                     + "-nodisplay\tRun Jalview without User Interface.\n"
1022                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1023                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1024                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1025                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1026                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
1027                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1028                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1029                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1030                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1031                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1032                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1033                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1034                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1035                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1036                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
1037                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1038                     + "-html FILE\tCreate HTML file from alignment.\n"
1039                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1040                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1041                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1042                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1043                     + "-noquestionnaire\tTurn off questionnaire check.\n"
1044                     + "-nonews\tTurn off check for Jalview news.\n"
1045                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1046                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1047                     // +
1048                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1049                     // after all other properties files have been read\n\t
1050                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1051                     // passed in correctly)"
1052                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1053                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1054                     + "-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"
1055                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1056   }
1057
1058   private static void startUsageStats(final Desktop desktop)
1059   {
1060     /**
1061      * start a User Config prompt asking if we can log usage statistics.
1062      */
1063     PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
1064             "USAGESTATS", "Jalview Usage Statistics",
1065             "Do you want to help make Jalview better by enabling "
1066                     + "the collection of usage statistics with Google Analytics ?"
1067                     + "\n\n(you can enable or disable usage tracking in the preferences)",
1068             new Runnable()
1069             {
1070               @Override
1071               public void run()
1072               {
1073                 Cache.log.debug(
1074                         "Initialising googletracker for usage stats.");
1075                 Cache.initGoogleTracker();
1076                 Cache.log.debug("Tracking enabled.");
1077               }
1078             }, new Runnable()
1079             {
1080               @Override
1081               public void run()
1082               {
1083                 Cache.log.debug("Not enabling Google Tracking.");
1084               }
1085             }, null, true);
1086     desktop.addDialogThread(prompter);
1087   }
1088
1089   /**
1090    * Locate the given string as a file and pass it to the groovy interpreter.
1091    * 
1092    * @param groovyscript
1093    *          the script to execute
1094    * @param jalviewContext
1095    *          the Jalview Desktop object passed in to the groovy binding as the
1096    *          'Jalview' object.
1097    */
1098   private void executeGroovyScript(String groovyscript, AlignFrame af)
1099   {
1100     /**
1101      * for scripts contained in files
1102      */
1103     File tfile = null;
1104     /**
1105      * script's URI
1106      */
1107     URL sfile = null;
1108     if (groovyscript.trim().equals("STDIN"))
1109     {
1110       // read from stdin into a tempfile and execute it
1111       try
1112       {
1113         tfile = File.createTempFile("jalview", "groovy");
1114         PrintWriter outfile = new PrintWriter(
1115                 new OutputStreamWriter(new FileOutputStream(tfile)));
1116         BufferedReader br = new BufferedReader(
1117                 new InputStreamReader(System.in));
1118         String line = null;
1119         while ((line = br.readLine()) != null)
1120         {
1121           outfile.write(line + "\n");
1122         }
1123         br.close();
1124         outfile.flush();
1125         outfile.close();
1126
1127       } catch (Exception ex)
1128       {
1129         System.err.println("Failed to read from STDIN into tempfile "
1130                 + ((tfile == null) ? "(tempfile wasn't created)"
1131                         : tfile.toString()));
1132         ex.printStackTrace();
1133         return;
1134       }
1135       try
1136       {
1137         sfile = tfile.toURI().toURL();
1138       } catch (Exception x)
1139       {
1140         System.err.println(
1141                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1142                         + tfile.toURI());
1143         x.printStackTrace();
1144         return;
1145       }
1146     }
1147     else
1148     {
1149       try
1150       {
1151         sfile = new URI(groovyscript).toURL();
1152       } catch (Exception x)
1153       {
1154         tfile = new File(groovyscript);
1155         if (!tfile.exists())
1156         {
1157           System.err.println("File '" + groovyscript + "' does not exist.");
1158           return;
1159         }
1160         if (!tfile.canRead())
1161         {
1162           System.err.println("File '" + groovyscript + "' cannot be read.");
1163           return;
1164         }
1165         if (tfile.length() < 1)
1166         {
1167           System.err.println("File '" + groovyscript + "' is empty.");
1168           return;
1169         }
1170         try
1171         {
1172           sfile = tfile.getAbsoluteFile().toURI().toURL();
1173         } catch (Exception ex)
1174         {
1175           System.err.println("Failed to create a file URL for "
1176                   + tfile.getAbsoluteFile());
1177           return;
1178         }
1179       }
1180     }
1181     try
1182     {
1183       Map<String, java.lang.Object> vbinding = new HashMap<>();
1184       vbinding.put("Jalview", this);
1185       if (af != null)
1186       {
1187         vbinding.put("currentAlFrame", af);
1188       }
1189       Binding gbinding = new Binding(vbinding);
1190       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1191       gse.run(sfile.toString(), gbinding);
1192       if ("STDIN".equals(groovyscript))
1193       {
1194         // delete temp file that we made -
1195         // only if it was successfully executed
1196         tfile.delete();
1197       }
1198     } catch (Exception e)
1199     {
1200       System.err.println("Exception Whilst trying to execute file " + sfile
1201               + " as a groovy script.");
1202       e.printStackTrace(System.err);
1203
1204     }
1205   }
1206
1207   public static boolean isHeadlessMode()
1208   {
1209     String isheadless = System.getProperty("java.awt.headless");
1210     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1211     {
1212       return true;
1213     }
1214     return false;
1215   }
1216
1217   public AlignFrame[] getAlignFrames()
1218   {
1219     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1220             : Desktop.getAlignFrames();
1221
1222   }
1223
1224   /**
1225    * Quit method delegates to Desktop.quit - unless running in headless mode
1226    * when it just ends the JVM
1227    */
1228   public void quit()
1229   {
1230     if (desktop != null)
1231     {
1232       desktop.quit();
1233     }
1234     else
1235     {
1236       System.exit(0);
1237     }
1238   }
1239
1240   public static AlignFrame getCurrentAlignFrame()
1241   {
1242     return Jalview.currentAlignFrame;
1243   }
1244
1245   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1246   {
1247     Jalview.currentAlignFrame = currentAlignFrame;
1248   }
1249 }