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