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