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