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