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