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