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