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