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