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