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