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