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