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