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