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