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