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