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