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