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