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