Merge branch 'merge/JAL-3285_mchmmer_with_211_develop' into alpha/JAL-3362_Jalview_21...
[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 jalview.ext.so.SequenceOntology;
24 import jalview.gui.AlignFrame;
25 import jalview.gui.Desktop;
26 import jalview.gui.PromptUserConfig;
27 import jalview.io.AppletFormatAdapter;
28 import jalview.io.BioJsHTMLOutput;
29 import jalview.io.DataSourceType;
30 import jalview.io.FileFormat;
31 import jalview.io.FileFormatException;
32 import jalview.io.FileFormatI;
33 import jalview.io.FileLoader;
34 import jalview.io.HtmlSvgOutput;
35 import jalview.io.IdentifyFile;
36 import jalview.io.NewickFile;
37 import jalview.io.gff.SequenceOntologyFactory;
38 import jalview.schemes.ColourSchemeI;
39 import jalview.schemes.ColourSchemeProperty;
40 import jalview.util.MessageManager;
41 import jalview.util.Platform;
42 import jalview.ws.jws2.Jws2Discoverer;
43
44 import java.io.BufferedReader;
45 import java.io.File;
46 import java.io.FileOutputStream;
47 import java.io.IOException;
48 import java.io.InputStreamReader;
49 import java.io.OutputStreamWriter;
50 import java.io.PrintWriter;
51 import java.net.MalformedURLException;
52 import java.net.URI;
53 import java.net.URISyntaxException;
54 import java.net.URL;
55 import java.security.AllPermission;
56 import java.security.CodeSource;
57 import java.security.PermissionCollection;
58 import java.security.Permissions;
59 import java.security.Policy;
60 import java.util.HashMap;
61 import java.util.Map;
62 import java.util.Vector;
63
64 import javax.swing.LookAndFeel;
65 import javax.swing.UIManager;
66
67 import com.threerings.getdown.util.LaunchUtil;
68
69 import groovy.lang.Binding;
70 import groovy.util.GroovyScriptEngine;
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
128      * processing 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(System.getProperty("os.arch") + " "
203             + System.getProperty("os.name") + " "
204             + System.getProperty("os.version"));
205
206     ArgsParser aparser = new ArgsParser(args);
207     boolean headless = false;
208
209     if (aparser.contains("help") || aparser.contains("h"))
210     {
211       showUsage();
212       System.exit(0);
213     }
214     if (aparser.contains("nodisplay") || aparser.contains("nogui")
215             || aparser.contains("headless"))
216     {
217       System.setProperty("java.awt.headless", "true");
218       headless = true;
219     }
220     String usrPropsFile = aparser.getValue("props");
221     Cache.loadProperties(usrPropsFile); // must do this before
222     if (usrPropsFile != null)
223     {
224       System.out.println(
225               "CMD [-props " + usrPropsFile + "] executed successfully!");
226     }
227
228     // anything else!
229
230     final String jabawsUrl = aparser.getValue("jabaws");
231     if (jabawsUrl != null)
232     {
233       try
234       {
235         Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
236         System.out.println(
237                 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
238       } catch (MalformedURLException e)
239       {
240         System.err.println(
241                 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
242       }
243     }
244
245     String defs = aparser.getValue("setprop");
246     while (defs != null)
247     {
248       int p = defs.indexOf('=');
249       if (p == -1)
250       {
251         System.err.println("Ignoring invalid setprop argument : " + defs);
252       }
253       else
254       {
255         System.out.println("Executing setprop argument: " + defs);
256         // DISABLED FOR SECURITY REASONS
257         // TODO: add a property to allow properties to be overriden by cli args
258         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
259       }
260       defs = aparser.getValue("setprop");
261     }
262     if (System.getProperty("java.awt.headless") != null
263             && System.getProperty("java.awt.headless").equals("true"))
264     {
265       headless = true;
266     }
267     System.setProperty("http.agent",
268             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
269     try
270     {
271       Cache.initLogger();
272     } catch (NoClassDefFoundError error)
273     {
274       error.printStackTrace();
275       System.out.println("\nEssential logging libraries not found."
276               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
277       System.exit(0);
278     }
279
280     desktop = null;
281
282     try
283     {
284       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
285     } catch (Exception ex)
286     {
287       System.err.println("Unexpected Look and Feel Exception");
288       ex.printStackTrace();
289     }
290     if (Platform.isAMac())
291     {
292
293       LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
294               .getLookAndFeel();
295       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
296               "Jalview");
297       System.setProperty("apple.laf.useScreenMenuBar", "true");
298       if (lookAndFeel != null)
299       {
300         try
301         {
302           UIManager.setLookAndFeel(lookAndFeel);
303         } catch (Throwable e)
304         {
305           System.err.println(
306                   "Failed to set QuaQua look and feel: " + e.toString());
307         }
308       }
309       if (lookAndFeel == null
310               || !(lookAndFeel.getClass().isAssignableFrom(
311                       UIManager.getLookAndFeel().getClass()))
312               || !UIManager.getLookAndFeel().getClass().toString()
313                       .toLowerCase().contains("quaqua"))
314       {
315         try
316         {
317           System.err.println(
318                   "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
319           UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
320         } catch (Throwable e)
321         {
322           System.err.println(
323                   "Failed to reset look and feel: " + e.toString());
324         }
325       }
326     }
327
328     /*
329      * configure 'full' SO model 
330      */
331     if (Cache.getDefault("USE_FULL_SO", true))
332     {
333       SequenceOntologyFactory.setInstance(new SequenceOntology());
334     }
335
336     if (!headless)
337     {
338       desktop = new Desktop();
339       desktop.setInBatchMode(true); // indicate we are starting up
340
341       try
342       {
343         JalviewTaskbar.setTaskbar(this);
344       } catch (Exception e)
345       {
346         System.out.println("Cannot set Taskbar");
347         // e.printStackTrace();
348       } catch (Throwable t)
349       {
350         System.out.println("Cannot set Taskbar");
351         // t.printStackTrace();
352       }
353
354       desktop.setVisible(true);
355       desktop.startServiceDiscovery();
356       if (!aparser.contains("nousagestats"))
357       {
358         startUsageStats(desktop);
359       }
360       else
361       {
362         System.err.println("CMD [-nousagestats] executed successfully!");
363       }
364
365       if (!aparser.contains("noquestionnaire"))
366       {
367         String url = aparser.getValue("questionnaire");
368         if (url != null)
369         {
370           // Start the desktop questionnaire prompter with the specified
371           // questionnaire
372           Cache.log.debug("Starting questionnaire url at " + url);
373           desktop.checkForQuestionnaire(url);
374           System.out.println(
375                   "CMD questionnaire[-" + url + "] executed successfully!");
376         }
377         else
378         {
379           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
380           {
381             // Start the desktop questionnaire prompter with the specified
382             // questionnaire
383             // String defurl =
384             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
385             // //
386             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
387             Cache.log.debug(
388                     "Starting questionnaire with default url: " + defurl);
389             desktop.checkForQuestionnaire(defurl);
390           }
391         }
392       }
393       else
394       {
395         System.err.println("CMD [-noquestionnaire] executed successfully!");
396       }
397
398       if (!aparser.contains("nonews"))
399       {
400         desktop.checkForNews();
401       }
402
403       BioJsHTMLOutput.updateBioJS();
404     }
405
406     // Move any new getdown-launcher-new.jar into place over old
407     // getdown-launcher.jar
408     String appdirString = System.getProperty("getdownappdir");
409     if (appdirString != null && appdirString.length() > 0)
410     {
411       final File appdir = new File(appdirString);
412       new Thread()
413       {
414         @Override
415         public void run()
416         {
417           LaunchUtil.upgradeGetdown(
418                   new File(appdir, "getdown-launcher-old.jar"),
419                   new File(appdir, "getdown-launcher.jar"),
420                   new File(appdir, "getdown-launcher-new.jar"));
421         }
422       }.start();
423     }
424
425     String file = null, data = null;
426     FileFormatI format = null;
427     DataSourceType protocol = null;
428     FileLoader fileLoader = new FileLoader(!headless);
429
430     String groovyscript = null; // script to execute after all loading is
431     // completed one way or another
432     // extract groovy argument and execute if necessary
433     groovyscript = aparser.getValue("groovy", true);
434     file = aparser.getValue("open", true);
435
436     if (file == null && desktop == null)
437     {
438       System.out.println("No files to open!");
439       System.exit(1);
440     }
441     long progress = -1;
442     // Finally, deal with the remaining input data.
443     if (file != null)
444     {
445       if (!headless)
446       {
447         desktop.setProgressBar(
448                 MessageManager
449                         .getString("status.processing_commandline_args"),
450                 progress = System.currentTimeMillis());
451       }
452       System.out.println("CMD [-open " + file + "] executed successfully!");
453
454       if (!file.startsWith("http://"))
455       {
456         if (!(new File(file)).exists())
457         {
458           System.out.println("Can't find " + file);
459           if (headless)
460           {
461             System.exit(1);
462           }
463         }
464       }
465
466       protocol = AppletFormatAdapter.checkProtocol(file);
467
468       try
469       {
470         format = new IdentifyFile().identify(file, protocol);
471       } catch (FileFormatException e1)
472       {
473         // TODO ?
474       }
475
476       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
477               format);
478       if (af == null)
479       {
480         System.out.println("error");
481       }
482       else
483       {
484         setCurrentAlignFrame(af);
485         data = aparser.getValue("colour", true);
486         if (data != null)
487         {
488           data.replaceAll("%20", " ");
489
490           ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
491                   af.getViewport(), af.getViewport().getAlignment(), data);
492
493           if (cs != null)
494           {
495             System.out.println(
496                     "CMD [-color " + data + "] executed successfully!");
497           }
498           af.changeColour(cs);
499         }
500
501         // Must maintain ability to use the groups flag
502         data = aparser.getValue("groups", true);
503         if (data != null)
504         {
505           af.parseFeaturesFile(data,
506                   AppletFormatAdapter.checkProtocol(data));
507           // System.out.println("Added " + data);
508           System.out.println(
509                   "CMD groups[-" + data + "]  executed successfully!");
510         }
511         data = aparser.getValue("features", true);
512         if (data != null)
513         {
514           af.parseFeaturesFile(data,
515                   AppletFormatAdapter.checkProtocol(data));
516           // System.out.println("Added " + data);
517           System.out.println(
518                   "CMD [-features " + data + "]  executed successfully!");
519         }
520
521         data = aparser.getValue("annotations", true);
522         if (data != null)
523         {
524           af.loadJalviewDataFile(data, null, null, null);
525           // System.out.println("Added " + data);
526           System.out.println(
527                   "CMD [-annotations " + data + "] executed successfully!");
528         }
529         // set or clear the sortbytree flag.
530         if (aparser.contains("sortbytree"))
531         {
532           af.getViewport().setSortByTree(true);
533           if (af.getViewport().getSortByTree())
534           {
535             System.out.println("CMD [-sortbytree] executed successfully!");
536           }
537         }
538         if (aparser.contains("no-annotation"))
539         {
540           af.getViewport().setShowAnnotation(false);
541           if (!af.getViewport().isShowAnnotation())
542           {
543             System.out.println("CMD no-annotation executed successfully!");
544           }
545         }
546         if (aparser.contains("nosortbytree"))
547         {
548           af.getViewport().setSortByTree(false);
549           if (!af.getViewport().getSortByTree())
550           {
551             System.out
552                     .println("CMD [-nosortbytree] executed successfully!");
553           }
554         }
555         data = aparser.getValue("tree", true);
556         if (data != null)
557         {
558           try
559           {
560             System.out.println(
561                     "CMD [-tree " + data + "] executed successfully!");
562             NewickFile nf = new NewickFile(data,
563                     AppletFormatAdapter.checkProtocol(data));
564             af.getViewport()
565                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
566           } catch (IOException ex)
567           {
568             System.err.println("Couldn't add tree " + data);
569             ex.printStackTrace(System.err);
570           }
571         }
572         // TODO - load PDB structure(s) to alignment JAL-629
573         // (associate with identical sequence in alignment, or a specified
574         // sequence)
575         if (groovyscript != null)
576         {
577           // Execute the groovy script after we've done all the rendering stuff
578           // and before any images or figures are generated.
579           System.out.println("Executing script " + groovyscript);
580           executeGroovyScript(groovyscript, af);
581           System.out.println("CMD groovy[" + groovyscript
582                   + "] executed successfully!");
583           groovyscript = null;
584         }
585         String imageName = "unnamed.png";
586         while (aparser.getSize() > 1)
587         {
588           String outputFormat = aparser.nextValue();
589           file = aparser.nextValue();
590
591           if (outputFormat.equalsIgnoreCase("png"))
592           {
593             af.createPNG(new File(file));
594             imageName = (new File(file)).getName();
595             System.out.println("Creating PNG image: " + file);
596             continue;
597           }
598           else if (outputFormat.equalsIgnoreCase("svg"))
599           {
600             File imageFile = new File(file);
601             imageName = imageFile.getName();
602             af.createSVG(imageFile);
603             System.out.println("Creating SVG image: " + file);
604             continue;
605           }
606           else if (outputFormat.equalsIgnoreCase("html"))
607           {
608             File imageFile = new File(file);
609             imageName = imageFile.getName();
610             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
611             htmlSVG.exportHTML(file);
612
613             System.out.println("Creating HTML image: " + file);
614             continue;
615           }
616           else if (outputFormat.equalsIgnoreCase("biojsmsa"))
617           {
618             if (file == null)
619             {
620               System.err.println("The output html file must not be null");
621               return;
622             }
623             try
624             {
625               BioJsHTMLOutput.refreshVersionInfo(
626                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
627             } catch (URISyntaxException e)
628             {
629               e.printStackTrace();
630             }
631             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
632             bjs.exportHTML(file);
633             System.out
634                     .println("Creating BioJS MSA Viwer HTML file: " + file);
635             continue;
636           }
637           else if (outputFormat.equalsIgnoreCase("imgMap"))
638           {
639             af.createImageMap(new File(file), imageName);
640             System.out.println("Creating image map: " + file);
641             continue;
642           }
643           else if (outputFormat.equalsIgnoreCase("eps"))
644           {
645             File outputFile = new File(file);
646             System.out.println(
647                     "Creating EPS file: " + outputFile.getAbsolutePath());
648             af.createEPS(outputFile);
649             continue;
650           }
651
652           if (af.saveAlignment(file, format))
653           {
654             System.out.println("Written alignment in " + format
655                     + " format to " + file);
656           }
657           else
658           {
659             System.out.println("Error writing file " + file + " in "
660                     + format + " format!!");
661           }
662
663         }
664
665         while (aparser.getSize() > 0)
666         {
667           System.out.println("Unknown arg: " + aparser.nextValue());
668         }
669       }
670     }
671     AlignFrame startUpAlframe = null;
672     // We'll only open the default file if the desktop is visible.
673     // And the user
674     // ////////////////////
675
676     if (!headless && file == null
677             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
678     {
679       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
680               jalview.bin.Cache.getDefault("www.jalview.org",
681                       "http://www.jalview.org")
682                       + "/examples/exampleFile_2_7.jar");
683       if (file.equals(
684               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
685       {
686         // hardwire upgrade of the startup file
687         file.replace("_2_3.jar", "_2_7.jar");
688         // and remove the stale setting
689         jalview.bin.Cache.removeProperty("STARTUP_FILE");
690       }
691
692       protocol = DataSourceType.FILE;
693
694       if (file.indexOf("http:") > -1)
695       {
696         protocol = DataSourceType.URL;
697       }
698
699       if (file.endsWith(".jar"))
700       {
701         format = FileFormat.Jalview;
702       }
703       else
704       {
705         try
706         {
707           format = new IdentifyFile().identify(file, protocol);
708         } catch (FileFormatException e)
709         {
710           // TODO what?
711         }
712       }
713
714       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
715               format);
716       // extract groovy arguments before anything else.
717     }
718
719     // Once all other stuff is done, execute any groovy scripts (in order)
720     if (groovyscript != null)
721     {
722       if (Cache.groovyJarsPresent())
723       {
724         System.out.println("Executing script " + groovyscript);
725         executeGroovyScript(groovyscript, startUpAlframe);
726       }
727       else
728       {
729         System.err.println(
730                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
731                         + groovyscript);
732       }
733     }
734     // and finally, turn off batch mode indicator - if the desktop still exists
735     if (desktop != null)
736     {
737       if (progress != -1)
738       {
739         desktop.setProgressBar(null, progress);
740       }
741       desktop.setInBatchMode(false);
742     }
743   }
744
745   private static void showUsage()
746   {
747     System.out.println(
748             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
749                     + "-nodisplay\tRun Jalview without User Interface.\n"
750                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
751                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
752                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
753                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
754                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
755                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
756                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
757                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
758                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
759                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
760                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
761                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
762                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
763                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
764                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
765                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
766                     + "-html FILE\tCreate HTML file from alignment.\n"
767                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
768                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
769                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
770                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
771                     + "-noquestionnaire\tTurn off questionnaire check.\n"
772                     + "-nonews\tTurn off check for Jalview news.\n"
773                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
774                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
775                     // +
776                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
777                     // after all other properties files have been read\n\t
778                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
779                     // passed in correctly)"
780                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
781                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
782                     + "-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"
783                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
784   }
785
786   private static void startUsageStats(final Desktop desktop)
787   {
788     /**
789      * start a User Config prompt asking if we can log usage statistics.
790      */
791     PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
792             "USAGESTATS", "Jalview Usage Statistics",
793             "Do you want to help make Jalview better by enabling "
794                     + "the collection of usage statistics with Google Analytics ?"
795                     + "\n\n(you can enable or disable usage tracking in the preferences)",
796             new Runnable()
797             {
798               @Override
799               public void run()
800               {
801                 Cache.log.debug(
802                         "Initialising googletracker for usage stats.");
803                 Cache.initGoogleTracker();
804                 Cache.log.debug("Tracking enabled.");
805               }
806             }, new Runnable()
807             {
808               @Override
809               public void run()
810               {
811                 Cache.log.debug("Not enabling Google Tracking.");
812               }
813             }, null, true);
814     desktop.addDialogThread(prompter);
815   }
816
817   /**
818    * Locate the given string as a file and pass it to the groovy interpreter.
819    * 
820    * @param groovyscript
821    *                         the script to execute
822    * @param jalviewContext
823    *                         the Jalview Desktop object passed in to the groovy
824    *                         binding as the 'Jalview' object.
825    */
826   private void executeGroovyScript(String groovyscript, AlignFrame af)
827   {
828     /**
829      * for scripts contained in files
830      */
831     File tfile = null;
832     /**
833      * script's URI
834      */
835     URL sfile = null;
836     if (groovyscript.trim().equals("STDIN"))
837     {
838       // read from stdin into a tempfile and execute it
839       try
840       {
841         tfile = File.createTempFile("jalview", "groovy");
842         PrintWriter outfile = new PrintWriter(
843                 new OutputStreamWriter(new FileOutputStream(tfile)));
844         BufferedReader br = new BufferedReader(
845                 new InputStreamReader(System.in));
846         String line = null;
847         while ((line = br.readLine()) != null)
848         {
849           outfile.write(line + "\n");
850         }
851         br.close();
852         outfile.flush();
853         outfile.close();
854
855       } catch (Exception ex)
856       {
857         System.err.println("Failed to read from STDIN into tempfile "
858                 + ((tfile == null) ? "(tempfile wasn't created)"
859                         : tfile.toString()));
860         ex.printStackTrace();
861         return;
862       }
863       try
864       {
865         sfile = tfile.toURI().toURL();
866       } catch (Exception x)
867       {
868         System.err.println(
869                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
870                         + tfile.toURI());
871         x.printStackTrace();
872         return;
873       }
874     }
875     else
876     {
877       try
878       {
879         sfile = new URI(groovyscript).toURL();
880       } catch (Exception x)
881       {
882         tfile = new File(groovyscript);
883         if (!tfile.exists())
884         {
885           System.err.println("File '" + groovyscript + "' does not exist.");
886           return;
887         }
888         if (!tfile.canRead())
889         {
890           System.err.println("File '" + groovyscript + "' cannot be read.");
891           return;
892         }
893         if (tfile.length() < 1)
894         {
895           System.err.println("File '" + groovyscript + "' is empty.");
896           return;
897         }
898         try
899         {
900           sfile = tfile.getAbsoluteFile().toURI().toURL();
901         } catch (Exception ex)
902         {
903           System.err.println("Failed to create a file URL for "
904                   + tfile.getAbsoluteFile());
905           return;
906         }
907       }
908     }
909     try
910     {
911       Map<String, java.lang.Object> vbinding = new HashMap<>();
912       vbinding.put("Jalview", this);
913       if (af != null)
914       {
915         vbinding.put("currentAlFrame", af);
916       }
917       Binding gbinding = new Binding(vbinding);
918       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
919       gse.run(sfile.toString(), gbinding);
920       if ("STDIN".equals(groovyscript))
921       {
922         // delete temp file that we made -
923         // only if it was successfully executed
924         tfile.delete();
925       }
926     } catch (Exception e)
927     {
928       System.err.println("Exception Whilst trying to execute file " + sfile
929               + " as a groovy script.");
930       e.printStackTrace(System.err);
931
932     }
933   }
934
935   public static boolean isHeadlessMode()
936   {
937     String isheadless = System.getProperty("java.awt.headless");
938     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
939     {
940       return true;
941     }
942     return false;
943   }
944
945   public AlignFrame[] getAlignFrames()
946   {
947     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
948             : Desktop.getAlignFrames();
949
950   }
951
952   /**
953    * Quit method delegates to Desktop.quit - unless running in headless mode when
954    * it just ends the JVM
955    */
956   public void quit()
957   {
958     if (desktop != null)
959     {
960       desktop.quit();
961     }
962     else
963     {
964       System.exit(0);
965     }
966   }
967
968   public static AlignFrame getCurrentAlignFrame()
969   {
970     return Jalview.currentAlignFrame;
971   }
972
973   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
974   {
975     Jalview.currentAlignFrame = currentAlignFrame;
976   }
977 }