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