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