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