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