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