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