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