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