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