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