JAL-3609 HiDPI scale setting done via system prop in getdown or halview.bin.Launcher
[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
358       desktop = new Desktop();
359       desktop.setInBatchMode(true); // indicate we are starting up
360
361       try
362       {
363         JalviewTaskbar.setTaskbar(this);
364       } catch (Exception e)
365       {
366         System.out.println("Cannot set Taskbar");
367         // e.printStackTrace();
368       } catch (Throwable t)
369       {
370         System.out.println("Cannot set Taskbar");
371         // t.printStackTrace();
372       }
373
374       desktop.setVisible(true);
375       desktop.startServiceDiscovery();
376       if (!aparser.contains("nousagestats"))
377       {
378         startUsageStats(desktop);
379       }
380       else
381       {
382         System.err.println("CMD [-nousagestats] executed successfully!");
383       }
384
385       if (!aparser.contains("noquestionnaire"))
386       {
387         String url = aparser.getValue("questionnaire");
388         if (url != null)
389         {
390           // Start the desktop questionnaire prompter with the specified
391           // questionnaire
392           Cache.log.debug("Starting questionnaire url at " + url);
393           desktop.checkForQuestionnaire(url);
394           System.out.println(
395                   "CMD questionnaire[-" + url + "] executed successfully!");
396         }
397         else
398         {
399           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
400           {
401             // Start the desktop questionnaire prompter with the specified
402             // questionnaire
403             // String defurl =
404             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
405             // //
406             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
407             Cache.log.debug(
408                     "Starting questionnaire with default url: " + defurl);
409             desktop.checkForQuestionnaire(defurl);
410           }
411         }
412       }
413       else
414       {
415         System.err.println("CMD [-noquestionnaire] executed successfully!");
416       }
417
418       if (!aparser.contains("nonews"))
419       {
420         desktop.checkForNews();
421       }
422
423       BioJsHTMLOutput.updateBioJS();
424     }
425
426     // Move any new getdown-launcher-new.jar into place over old
427     // getdown-launcher.jar
428     String appdirString = System.getProperty("getdownappdir");
429     if (appdirString != null && appdirString.length() > 0)
430     {
431       final File appdir = new File(appdirString);
432       new Thread()
433       {
434         @Override
435         public void run()
436         {
437           LaunchUtil.upgradeGetdown(
438                   new File(appdir, "getdown-launcher-old.jar"),
439                   new File(appdir, "getdown-launcher.jar"),
440                   new File(appdir, "getdown-launcher-new.jar"));
441         }
442       }.start();
443     }
444
445     String file = null, data = null;
446     FileFormatI format = null;
447     DataSourceType protocol = null;
448     FileLoader fileLoader = new FileLoader(!headless);
449
450     String groovyscript = null; // script to execute after all loading is
451     // completed one way or another
452     // extract groovy argument and execute if necessary
453     groovyscript = aparser.getValue("groovy", true);
454     file = aparser.getValue("open", true);
455
456     if (file == null && desktop == null)
457     {
458       System.out.println("No files to open!");
459       System.exit(1);
460     }
461     long progress = -1;
462     // Finally, deal with the remaining input data.
463     if (file != null)
464     {
465       if (!headless)
466       {
467         desktop.setProgressBar(
468                 MessageManager
469                         .getString("status.processing_commandline_args"),
470                 progress = System.currentTimeMillis());
471       }
472       System.out.println("CMD [-open " + file + "] executed successfully!");
473
474       if (!file.startsWith("http://"))
475       {
476         if (!(new File(file)).exists())
477         {
478           System.out.println("Can't find " + file);
479           if (headless)
480           {
481             System.exit(1);
482           }
483         }
484       }
485
486       protocol = AppletFormatAdapter.checkProtocol(file);
487
488       try
489       {
490         format = new IdentifyFile().identify(file, protocol);
491       } catch (FileFormatException e1)
492       {
493         // TODO ?
494       }
495
496       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
497               format);
498       if (af == null)
499       {
500         System.out.println("error");
501       }
502       else
503       {
504         setCurrentAlignFrame(af);
505         data = aparser.getValue("colour", true);
506         if (data != null)
507         {
508           data.replaceAll("%20", " ");
509
510           ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
511                   af.getViewport(), af.getViewport().getAlignment(), data);
512
513           if (cs != null)
514           {
515             System.out.println(
516                     "CMD [-color " + data + "] executed successfully!");
517           }
518           af.changeColour(cs);
519         }
520
521         // Must maintain ability to use the groups flag
522         data = aparser.getValue("groups", true);
523         if (data != null)
524         {
525           af.parseFeaturesFile(data,
526                   AppletFormatAdapter.checkProtocol(data));
527           // System.out.println("Added " + data);
528           System.out.println(
529                   "CMD groups[-" + data + "]  executed successfully!");
530         }
531         data = aparser.getValue("features", true);
532         if (data != null)
533         {
534           af.parseFeaturesFile(data,
535                   AppletFormatAdapter.checkProtocol(data));
536           // System.out.println("Added " + data);
537           System.out.println(
538                   "CMD [-features " + data + "]  executed successfully!");
539         }
540
541         data = aparser.getValue("annotations", true);
542         if (data != null)
543         {
544           af.loadJalviewDataFile(data, null, null, null);
545           // System.out.println("Added " + data);
546           System.out.println(
547                   "CMD [-annotations " + data + "] executed successfully!");
548         }
549         // set or clear the sortbytree flag.
550         if (aparser.contains("sortbytree"))
551         {
552           af.getViewport().setSortByTree(true);
553           if (af.getViewport().getSortByTree())
554           {
555             System.out.println("CMD [-sortbytree] executed successfully!");
556           }
557         }
558         if (aparser.contains("no-annotation"))
559         {
560           af.getViewport().setShowAnnotation(false);
561           if (!af.getViewport().isShowAnnotation())
562           {
563             System.out.println("CMD no-annotation executed successfully!");
564           }
565         }
566         if (aparser.contains("nosortbytree"))
567         {
568           af.getViewport().setSortByTree(false);
569           if (!af.getViewport().getSortByTree())
570           {
571             System.out
572                     .println("CMD [-nosortbytree] executed successfully!");
573           }
574         }
575         data = aparser.getValue("tree", true);
576         if (data != null)
577         {
578           try
579           {
580             System.out.println(
581                     "CMD [-tree " + data + "] executed successfully!");
582             NewickFile nf = new NewickFile(data,
583                     AppletFormatAdapter.checkProtocol(data));
584             af.getViewport()
585                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
586           } catch (IOException ex)
587           {
588             System.err.println("Couldn't add tree " + data);
589             ex.printStackTrace(System.err);
590           }
591         }
592         // TODO - load PDB structure(s) to alignment JAL-629
593         // (associate with identical sequence in alignment, or a specified
594         // sequence)
595         if (groovyscript != null)
596         {
597           // Execute the groovy script after we've done all the rendering stuff
598           // and before any images or figures are generated.
599           System.out.println("Executing script " + groovyscript);
600           executeGroovyScript(groovyscript, af);
601           System.out.println("CMD groovy[" + groovyscript
602                   + "] executed successfully!");
603           groovyscript = null;
604         }
605         String imageName = "unnamed.png";
606         while (aparser.getSize() > 1)
607         {
608           String outputFormat = aparser.nextValue();
609           file = aparser.nextValue();
610
611           if (outputFormat.equalsIgnoreCase("png"))
612           {
613             af.createPNG(new File(file));
614             imageName = (new File(file)).getName();
615             System.out.println("Creating PNG image: " + file);
616             continue;
617           }
618           else if (outputFormat.equalsIgnoreCase("svg"))
619           {
620             File imageFile = new File(file);
621             imageName = imageFile.getName();
622             af.createSVG(imageFile);
623             System.out.println("Creating SVG image: " + file);
624             continue;
625           }
626           else if (outputFormat.equalsIgnoreCase("html"))
627           {
628             File imageFile = new File(file);
629             imageName = imageFile.getName();
630             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
631             htmlSVG.exportHTML(file);
632
633             System.out.println("Creating HTML image: " + file);
634             continue;
635           }
636           else if (outputFormat.equalsIgnoreCase("biojsmsa"))
637           {
638             if (file == null)
639             {
640               System.err.println("The output html file must not be null");
641               return;
642             }
643             try
644             {
645               BioJsHTMLOutput.refreshVersionInfo(
646                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
647             } catch (URISyntaxException e)
648             {
649               e.printStackTrace();
650             }
651             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
652             bjs.exportHTML(file);
653             System.out
654                     .println("Creating BioJS MSA Viwer HTML file: " + file);
655             continue;
656           }
657           else if (outputFormat.equalsIgnoreCase("imgMap"))
658           {
659             af.createImageMap(new File(file), imageName);
660             System.out.println("Creating image map: " + file);
661             continue;
662           }
663           else if (outputFormat.equalsIgnoreCase("eps"))
664           {
665             File outputFile = new File(file);
666             System.out.println(
667                     "Creating EPS file: " + outputFile.getAbsolutePath());
668             af.createEPS(outputFile);
669             continue;
670           }
671
672           if (af.saveAlignment(file, format))
673           {
674             System.out.println("Written alignment in " + format
675                     + " format to " + file);
676           }
677           else
678           {
679             System.out.println("Error writing file " + file + " in "
680                     + format + " format!!");
681           }
682
683         }
684
685         while (aparser.getSize() > 0)
686         {
687           System.out.println("Unknown arg: " + aparser.nextValue());
688         }
689       }
690     }
691     AlignFrame startUpAlframe = null;
692     // We'll only open the default file if the desktop is visible.
693     // And the user
694     // ////////////////////
695
696     if (!headless && file == null
697             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
698     {
699       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
700               jalview.bin.Cache.getDefault("www.jalview.org",
701                       "http://www.jalview.org")
702                       + "/examples/exampleFile_2_7.jar");
703       if (file.equals(
704               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
705       {
706         // hardwire upgrade of the startup file
707         file.replace("_2_3.jar", "_2_7.jar");
708         // and remove the stale setting
709         jalview.bin.Cache.removeProperty("STARTUP_FILE");
710       }
711
712       protocol = DataSourceType.FILE;
713
714       if (file.indexOf("http:") > -1)
715       {
716         protocol = DataSourceType.URL;
717       }
718
719       if (file.endsWith(".jar"))
720       {
721         format = FileFormat.Jalview;
722       }
723       else
724       {
725         try
726         {
727           format = new IdentifyFile().identify(file, protocol);
728         } catch (FileFormatException e)
729         {
730           // TODO what?
731         }
732       }
733
734       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
735               format);
736       // extract groovy arguments before anything else.
737     }
738
739     // Once all other stuff is done, execute any groovy scripts (in order)
740     if (groovyscript != null)
741     {
742       if (Cache.groovyJarsPresent())
743       {
744         System.out.println("Executing script " + groovyscript);
745         executeGroovyScript(groovyscript, startUpAlframe);
746       }
747       else
748       {
749         System.err.println(
750                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
751                         + groovyscript);
752       }
753     }
754     // and finally, turn off batch mode indicator - if the desktop still exists
755     if (desktop != null)
756     {
757       if (progress != -1)
758       {
759         desktop.setProgressBar(null, progress);
760       }
761       desktop.setInBatchMode(false);
762     }
763   }
764
765   private static void showUsage()
766   {
767     System.out.println(
768             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
769                     + "-nodisplay\tRun Jalview without User Interface.\n"
770                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
771                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
772                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
773                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
774                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
775                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
776                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
777                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
778                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
779                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
780                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
781                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
782                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
783                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
784                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
785                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
786                     + "-html FILE\tCreate HTML file from alignment.\n"
787                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
788                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
789                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
790                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
791                     + "-noquestionnaire\tTurn off questionnaire check.\n"
792                     + "-nonews\tTurn off check for Jalview news.\n"
793                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
794                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
795                     // +
796                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
797                     // after all other properties files have been read\n\t
798                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
799                     // passed in correctly)"
800                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
801                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
802                     + "-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"
803                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
804   }
805
806   private static void startUsageStats(final Desktop desktop)
807   {
808     /**
809      * start a User Config prompt asking if we can log usage statistics.
810      */
811     PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
812             "USAGESTATS", "Jalview Usage Statistics",
813             "Do you want to help make Jalview better by enabling "
814                     + "the collection of usage statistics with Google Analytics ?"
815                     + "\n\n(you can enable or disable usage tracking in the preferences)",
816             new Runnable()
817             {
818               @Override
819               public void run()
820               {
821                 Cache.log.debug(
822                         "Initialising googletracker for usage stats.");
823                 Cache.initGoogleTracker();
824                 Cache.log.debug("Tracking enabled.");
825               }
826             }, new Runnable()
827             {
828               @Override
829               public void run()
830               {
831                 Cache.log.debug("Not enabling Google Tracking.");
832               }
833             }, null, true);
834     desktop.addDialogThread(prompter);
835   }
836
837   /**
838    * Locate the given string as a file and pass it to the groovy interpreter.
839    * 
840    * @param groovyscript
841    *          the script to execute
842    * @param jalviewContext
843    *          the Jalview Desktop object passed in to the groovy binding as the
844    *          'Jalview' object.
845    */
846   private void executeGroovyScript(String groovyscript, AlignFrame af)
847   {
848     /**
849      * for scripts contained in files
850      */
851     File tfile = null;
852     /**
853      * script's URI
854      */
855     URL sfile = null;
856     if (groovyscript.trim().equals("STDIN"))
857     {
858       // read from stdin into a tempfile and execute it
859       try
860       {
861         tfile = File.createTempFile("jalview", "groovy");
862         PrintWriter outfile = new PrintWriter(
863                 new OutputStreamWriter(new FileOutputStream(tfile)));
864         BufferedReader br = new BufferedReader(
865                 new InputStreamReader(System.in));
866         String line = null;
867         while ((line = br.readLine()) != null)
868         {
869           outfile.write(line + "\n");
870         }
871         br.close();
872         outfile.flush();
873         outfile.close();
874
875       } catch (Exception ex)
876       {
877         System.err.println("Failed to read from STDIN into tempfile "
878                 + ((tfile == null) ? "(tempfile wasn't created)"
879                         : tfile.toString()));
880         ex.printStackTrace();
881         return;
882       }
883       try
884       {
885         sfile = tfile.toURI().toURL();
886       } catch (Exception x)
887       {
888         System.err.println(
889                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
890                         + tfile.toURI());
891         x.printStackTrace();
892         return;
893       }
894     }
895     else
896     {
897       try
898       {
899         sfile = new URI(groovyscript).toURL();
900       } catch (Exception x)
901       {
902         tfile = new File(groovyscript);
903         if (!tfile.exists())
904         {
905           System.err.println("File '" + groovyscript + "' does not exist.");
906           return;
907         }
908         if (!tfile.canRead())
909         {
910           System.err.println("File '" + groovyscript + "' cannot be read.");
911           return;
912         }
913         if (tfile.length() < 1)
914         {
915           System.err.println("File '" + groovyscript + "' is empty.");
916           return;
917         }
918         try
919         {
920           sfile = tfile.getAbsoluteFile().toURI().toURL();
921         } catch (Exception ex)
922         {
923           System.err.println("Failed to create a file URL for "
924                   + tfile.getAbsoluteFile());
925           return;
926         }
927       }
928     }
929     try
930     {
931       Map<String, java.lang.Object> vbinding = new HashMap<>();
932       vbinding.put("Jalview", this);
933       if (af != null)
934       {
935         vbinding.put("currentAlFrame", af);
936       }
937       Binding gbinding = new Binding(vbinding);
938       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
939       gse.run(sfile.toString(), gbinding);
940       if ("STDIN".equals(groovyscript))
941       {
942         // delete temp file that we made -
943         // only if it was successfully executed
944         tfile.delete();
945       }
946     } catch (Exception e)
947     {
948       System.err.println("Exception Whilst trying to execute file " + sfile
949               + " as a groovy script.");
950       e.printStackTrace(System.err);
951
952     }
953   }
954
955   public static boolean isHeadlessMode()
956   {
957     String isheadless = System.getProperty("java.awt.headless");
958     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
959     {
960       return true;
961     }
962     return false;
963   }
964
965   public AlignFrame[] getAlignFrames()
966   {
967     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
968             : Desktop.getAlignFrames();
969
970   }
971
972   /**
973    * Quit method delegates to Desktop.quit - unless running in headless mode
974    * when it just ends the JVM
975    */
976   public void quit()
977   {
978     if (desktop != null)
979     {
980       desktop.quit();
981     }
982     else
983     {
984       System.exit(0);
985     }
986   }
987
988   public static AlignFrame getCurrentAlignFrame()
989   {
990     return Jalview.currentAlignFrame;
991   }
992
993   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
994   {
995     Jalview.currentAlignFrame = currentAlignFrame;
996   }
997 }