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