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