e890cb85bd00a5cfc35c166152a4b05c74b92004
[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           af.saveAlignment(file, format);
753           if (af.isSaveAlignmentSuccessful())
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 }