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