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