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