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