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