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