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