first experiment with GA application use tracking
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3  * Copyright (C) 2008 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.bin;
20
21 import java.io.BufferedReader;
22 import java.io.File;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.OutputStreamWriter;
26 import java.io.PrintWriter;
27 import java.lang.reflect.Constructor;
28 import java.net.URL;
29 import java.util.*;
30
31 import javax.swing.*;
32
33 import jalview.gui.*;
34 import jalview.io.AppletFormatAdapter;
35
36 /**
37  * Main class for Jalview Application <br>
38  * <br>
39  * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
40  * 
41  * @author $author$
42  * @version $Revision$
43  */
44 public class Jalview
45 {
46
47   /**
48    * main class for Jalview application
49    * 
50    * @param args
51    *                open <em>filename</em>
52    */
53   public static void main(String[] args)
54   {
55     System.out.println("Java version: "
56             + System.getProperty("java.version"));
57     System.out.println(System.getProperty("os.arch") + " "
58             + System.getProperty("os.name") + " "
59             + System.getProperty("os.version"));
60
61     ArgsParser aparser = new ArgsParser(args);
62     boolean headless = false;
63
64     if (aparser.contains("help") || aparser.contains("h"))
65     {
66       System.out
67               .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
68                       + "-nodisplay\tRun Jalview without User Interface.\n"
69                       + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
70                       + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
71                       + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
72                       + "-features FILE\tUse the given file to mark features on the alignment.\n"
73                       + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
74                       + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
75                       + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
76                       + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
77                       + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
78                       + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
79                       + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
80                       + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
81                       + "-png FILE\tCreate PNG image FILE from alignment.\n"
82                       + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
83                       + "-eps FILE\tCreate EPS file FILE from alignment.\n"
84                       + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
85                       + "-noquestionnaire\tTurn off questionnaire check.\n"
86                       + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
87                       + "-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)"
88                       + "-dasserver nickname=URL\tAdd and enable a das server with given nickname (alphanumeric or underscores only) for retrieval of features for all alignments.\n"
89                       +"\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
90                       +"\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
91                       + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
92                       + "-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"
93                       + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
94       System.exit(0);
95     }
96     Cache.loadProperties(aparser.getValue("props")); // must do this before
97     // anything else!
98     String defs = aparser.getValue("setprop");
99     while (defs!=null)
100     {
101       int p = defs.indexOf('=');
102       if ( p==-1 )
103       {
104         System.err.println("Ignoring invalid setprop argument : "+defs);
105       } else {
106         System.out.println("Executing setprop argument: "+defs);
107         // DISABLED FOR SECURITY REASONS
108         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
109       }
110       defs = aparser.getValue("setprop");
111     }
112     if (aparser.contains("nodisplay"))
113     {
114       System.setProperty("java.awt.headless", "true");
115     }
116     if (System.getProperty("java.awt.headless") != null
117             && System.getProperty("java.awt.headless").equals("true"))
118     {
119       headless = true;
120     }
121
122     try
123     {
124       Cache.initLogger();
125     } catch (java.lang.NoClassDefFoundError error)
126     {
127       error.printStackTrace();
128       System.out
129               .println("\nEssential logging libraries not found."
130                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
131       System.exit(0);
132     }
133
134     Desktop desktop = null;
135
136     try
137     {
138       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()
139       // UIManager.getCrossPlatformLookAndFeelClassName()
140               // "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"
141               // "javax.swing.plaf.metal.MetalLookAndFeel"
142               // "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"
143               // "com.sun.java.swing.plaf.motif.MotifLookAndFeel"
144
145               
146               );
147     } catch (Exception ex)
148     {
149     }
150     if (!headless)
151     {
152       desktop = new Desktop();
153       desktop.setVisible(true);
154       desktop.discoverer.start();
155       if (!aparser.contains("nousagestats") && Cache.getDefault("USAGESTATS", true)) {
156         Cache.log.info("Initialising googletracker for usage stats.");
157         Cache.initGoogleTracker();
158         Cache.log.debug("Tracking enabled.");
159       } else {
160         Cache.log.info("Not enabling Google Tracking.");
161       }
162       if (!aparser.contains("noquestionnaire"))
163       {
164         String url = aparser.getValue("questionnaire");
165         if (url != null)
166         {
167           // Start the desktop questionnaire prompter with the specified
168           // questionnaire
169           Cache.log.debug("Starting questionnaire url at " + url);
170           desktop.checkForQuestionnaire(url);
171         }
172         else
173         {
174           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
175           {
176             // Start the desktop questionnaire prompter with the specified
177             // questionnaire
178             // String defurl =
179             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
180             // //
181             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
182             Cache.log.debug("Starting questionnaire with default url: "
183                     + defurl);
184             desktop.checkForQuestionnaire(defurl);
185
186           }
187         }
188       }
189     }
190
191     String file = null, protocol = null, format = null, data = null;
192     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader();
193     Vector getFeatures = null; // vector of das source nicknames to fetch
194                                 // features from
195     // loading is done.
196     String groovyscript = null; // script to execute after all loading is
197                                 // completed one way or another
198     // extract groovy argument and execute if necessary
199     groovyscript = aparser.getValue("groovy");
200     file = aparser.getValue("open");
201
202     if (file == null && desktop == null)
203     {
204       System.out.println("No files to open!");
205       System.exit(1);
206     }
207
208     if (file != null)
209     {
210       System.out.println("Opening file: " + file);
211
212       if (!file.startsWith("http://"))
213       {
214         if (!(new java.io.File(file)).exists())
215         {
216           System.out.println("Can't find " + file);
217           if (headless)
218           {
219             System.exit(1);
220           }
221         }
222       }
223
224       protocol = checkProtocol(file);
225
226       format = new jalview.io.IdentifyFile().Identify(file, protocol);
227
228       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
229               format);
230
231       if (af == null)
232       {
233         System.out.println("error");
234         return;
235       }
236
237       data = aparser.getValue("colour");
238       if (data != null)
239       {
240         data.replaceAll("%20", " ");
241
242         jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
243                 .getColour(af.getViewport().getAlignment(), data);
244
245         if (cs == null)
246         {
247           jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
248                   "white");
249           ucs.parseAppletParameter(data);
250           cs = ucs;
251         }
252
253         System.out.println("colour is " + data);
254         af.changeColour(cs);
255       }
256
257       // Must maintain ability to use the groups flag
258       data = aparser.getValue("groups");
259       if (data != null)
260       {
261         af.parseFeaturesFile(data, checkProtocol(data));
262         System.out.println("Added " + data);
263       }
264       data = aparser.getValue("features");
265       if (data != null)
266       {
267         af.parseFeaturesFile(data, checkProtocol(data));
268         System.out.println("Added " + data);
269       }
270
271       data = aparser.getValue("annotations");
272       if (data != null)
273       {
274         af.loadJalviewDataFile(data);
275         System.out.println("Added " + data);
276       }
277       // set or clear the sortbytree flag.
278       if (aparser.contains("sortbytree"))
279       {
280         af.getViewport().setSortByTree(true);
281       }
282       if (aparser.contains("nosortbytree"))
283       {
284         af.getViewport().setSortByTree(false);
285       }
286       data = aparser.getValue("tree");
287       if (data != null)
288       {
289         jalview.io.NewickFile fin = null;
290         try
291         {
292           fin = new jalview.io.NewickFile(data, checkProtocol(data));
293           if (fin != null)
294           {
295             af.getViewport().setCurrentTree(
296                     af.ShowNewickTree(fin, data).getTree());
297             System.out.println("Added tree " + data);
298           }
299         } catch (IOException ex)
300         {
301           System.err.println("Couldn't add tree " + data);
302           ex.printStackTrace(System.err);
303         }
304       }
305       getFeatures = checkDasArguments(aparser);
306       if (af != null && getFeatures != null)
307       {
308         startFeatureFetching(getFeatures);
309         // need to block until fetching is complete.
310         while (af.operationInProgress())
311         {
312           // wait around until fetching is finished.
313           try
314           {
315             Thread.sleep(10);
316           } catch (Exception e)
317           {
318
319           }
320         }
321       }
322       if (groovyscript != null)
323       {
324         // Execute the groovy script after we've done all the rendering stuff
325         // and before any images or figures are generated.
326         if (jalview.bin.Cache.groovyJarsPresent())
327         {
328           System.out.println("Executing script " + groovyscript);
329           executeGroovyScript(groovyscript, desktop);
330         }
331         else
332         {
333           System.err
334                   .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
335                           + groovyscript);
336         }
337         groovyscript = null;
338       }
339       String imageName = "unnamed.png";
340       while (aparser.getSize() > 1)
341       {
342         format = aparser.nextValue();
343         file = aparser.nextValue();
344
345         if (format.equalsIgnoreCase("png"))
346         {
347           af.createPNG(new java.io.File(file));
348           imageName = (new java.io.File(file)).getName();
349           System.out.println("Creating PNG image: " + file);
350           continue;
351         }
352         else if (format.equalsIgnoreCase("imgMap"))
353         {
354           af.createImageMap(new java.io.File(file), imageName);
355           System.out.println("Creating image map: " + file);
356           continue;
357         }
358         else if (format.equalsIgnoreCase("eps"))
359         {
360           System.out.println("Creating EPS file: " + file);
361           af.createEPS(new java.io.File(file));
362           continue;
363         }
364
365         if (af.saveAlignment(file, format))
366         {
367           System.out.println("Written alignment in " + format
368                   + " format to " + file);
369         }
370         else
371         {
372           System.out.println("Error writing file " + file + " in " + format
373                   + " format!!");
374         }
375
376       }
377
378       while (aparser.getSize() > 0)
379       {
380         System.out.println("Unknown arg: " + aparser.nextValue());
381       }
382     }
383     AlignFrame startUpAlframe = null;
384     // We'll only open the default file if the desktop is visible.
385     // And the user
386     // ////////////////////
387     if (!headless && file == null
388             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
389     {
390       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
391               "http://www.jalview.org/examples/exampleFile_2_3.jar");
392
393       protocol = "File";
394
395       if (file.indexOf("http:") > -1)
396       {
397         protocol = "URL";
398       }
399
400       if (file.endsWith(".jar"))
401       {
402         format = "Jalview";
403       }
404       else
405       {
406         format = new jalview.io.IdentifyFile().Identify(file, protocol);
407       }
408
409       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
410               format);
411       getFeatures = checkDasArguments(aparser);
412       // extract groovy arguments before anything else.
413     }
414     // Once all loading is done. Retrieve features.
415     if (getFeatures != null)
416     {
417       if (startUpAlframe != null)
418       {
419         startFeatureFetching(getFeatures);
420       }
421     }
422     if (groovyscript != null)
423     {
424       if (jalview.bin.Cache.groovyJarsPresent())
425       {
426         System.out.println("Executing script " + groovyscript);
427         executeGroovyScript(groovyscript, desktop);
428       }
429       else
430       {
431         System.err
432                 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
433                         + groovyscript);
434       }
435     }
436
437     // Once all other stuff is done, execute any groovy scripts (in order)
438   }
439
440   /**
441    * Locate the given string as a file and pass it to the groovy interpreter.
442    * 
443    * @param groovyscript
444    *                the script to execute
445    * @param jalviewContext
446    *                the Jalview Desktop object passed in to the groovy binding
447    *                as the 'Jalview' object.
448    */
449   private static void executeGroovyScript(String groovyscript,
450           Object jalviewContext)
451   {
452     if (jalviewContext == null)
453     {
454       System.err
455               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
456     }
457     File sfile = null;
458     if (groovyscript.trim().equals("STDIN"))
459     {
460       // read from stdin into a tempfile and execute it
461       try
462       {
463         sfile = File.createTempFile("jalview", "groovy");
464         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
465                 new FileOutputStream(sfile)));
466         BufferedReader br = new BufferedReader(
467                 new java.io.InputStreamReader(System.in));
468         String line = null;
469         while ((line = br.readLine()) != null)
470         {
471           outfile.write(line + "\n");
472         }
473         br.close();
474         outfile.flush();
475         outfile.close();
476
477       } catch (Exception ex)
478       {
479         System.err.println("Failed to read from STDIN into tempfile "
480                 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
481                         .toString()));
482         ex.printStackTrace();
483         return;
484       }
485     }
486     else
487     {
488       sfile = new File(groovyscript);
489     }
490     if (!sfile.exists())
491     {
492       System.err.println("File '" + groovyscript + "' does not exist.");
493       return;
494     }
495     if (!sfile.canRead())
496     {
497       System.err.println("File '" + groovyscript + "' cannot be read.");
498       return;
499     }
500     if (sfile.length() < 1)
501     {
502       System.err.println("File '" + groovyscript + "' is empty.");
503       return;
504     }
505     boolean success = false;
506     try
507     {
508       /*
509        * The following code performs the GroovyScriptEngine invocation using
510        * reflection, and is equivalent to this fragment from the embedding
511        * groovy documentation on the groovy site: <code> import
512        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
513        * 
514        * String[] roots = new String[] { "/my/groovy/script/path" };
515        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding =
516        * new Binding(); binding.setVariable("input", "world");
517        * gse.run("hello.groovy", binding); </code>
518        */
519       ClassLoader cl = jalviewContext.getClass().getClassLoader();
520       Class gbindingc = cl.loadClass("groovy.lang.Binding");
521       Constructor gbcons = gbindingc.getConstructor(null);
522       Object gbinding = gbcons.newInstance(null);
523       java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
524               new Class[]
525               { String.class, Object.class });
526       setvar.invoke(gbinding, new Object[]
527       { "Jalview", jalviewContext });
528       Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
529       Constructor gseccons = gsec.getConstructor(new Class[]
530       { URL[].class }); // String[].class });
531       Object gse = gseccons.newInstance(new Object[]
532       { new URL[]
533       { sfile.toURL() } }); // .toString() } });
534       java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
535       { String.class, gbindingc });
536       run.invoke(gse, new Object[]
537       { sfile.getName(), gbinding });
538       success = true;
539     } catch (Exception e)
540     {
541       System.err.println("Exception Whilst trying to execute file " + sfile
542               + " as a groovy script.");
543       e.printStackTrace(System.err);
544
545     }
546     if (success && groovyscript.equals("STDIN"))
547     {
548       // delete temp file that we made - but only if it was successfully
549       // executed
550       sfile.delete();
551     }
552   }
553
554   /**
555    * Check commandline for any das server definitions or any fetchfrom switches
556    * 
557    * @return vector of DAS source nicknames to retrieve from
558    */
559   private static Vector checkDasArguments(ArgsParser aparser)
560   {
561     Vector source = null;
562     String data;
563     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
564     while ((data = aparser.getValue("dasserver")) != null)
565     {
566       String nickname = null;
567       String url = null;
568       boolean seq=false,feat=true;
569       int pos = data.indexOf('=');
570       // determine capabilities
571       if (pos > 0)
572       {
573         nickname = data.substring(0, pos);
574       }
575       url = data.substring(pos + 1);
576       if (url != null && (url.startsWith("http:") || url.startsWith("sequence:http:")))
577       {
578         if (nickname == null)
579         {
580           nickname = url;
581         }
582         if (locsources == null)
583         {
584           locsources = "";
585         }
586         else
587         {
588           locsources += "\t";
589         }
590         locsources = locsources + nickname + "|" + url;
591         System.err
592                 .println("NOTE! dasserver parameter not yet really supported (got args of "
593                         + nickname + "|" + url);
594         if (source == null)
595         {
596           source = new Vector();
597         }
598         source.addElement(nickname);
599       }
600     } // loop until no more server entries are found.
601     if (locsources != null && locsources.indexOf('|') > -1)
602     {
603       Cache.log.debug("Setting local source list in properties file to:\n"
604               + locsources);
605       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
606     }
607     while ((data = aparser.getValue("fetchfrom")) != null)
608     {
609       System.out.println("adding source '" + data + "'");
610       if (source == null)
611       {
612         source = new Vector();
613       }
614       source.addElement(data);
615     }
616     return source;
617   }
618
619   /**
620    * start a feature fetcher for every alignment frame
621    * 
622    * @param dasSources
623    */
624   private static void startFeatureFetching(final Vector dasSources)
625   {
626     AlignFrame afs[] = Desktop.getAlignframes();
627     if (afs == null || afs.length == 0)
628     {
629       return;
630     }
631     for (int i = 0; i < afs.length; i++)
632     {
633       final AlignFrame af = afs[i];
634       SwingUtilities.invokeLater(new Runnable()
635       {
636
637         public void run()
638         {
639           af.featureSettings_actionPerformed(null);
640           af.featureSettings.fetchDasFeatures(dasSources);
641         }
642       });
643     }
644   }
645
646   private static String checkProtocol(String file)
647   {
648     String protocol = jalview.io.FormatAdapter.FILE;
649
650     if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
651     {
652       protocol = jalview.io.FormatAdapter.URL;
653     }
654     return protocol;
655   }
656 }
657
658 /**
659  * Notes: this argParser does not distinguish between parameter switches,
660  * parameter values and argument text. If an argument happens to be identical to
661  * a parameter, it will be taken as such (even though it didn't have a '-'
662  * prefixing it).
663  * 
664  * @author Andrew Waterhouse and JBP documented.
665  * 
666  */
667 class ArgsParser
668 {
669   Vector vargs = null;
670
671   public ArgsParser(String[] args)
672   {
673     vargs = new Vector();
674     for (int i = 0; i < args.length; i++)
675     {
676       String arg = args[i].trim();
677       if (arg.charAt(0) == '-')
678       {
679         arg = arg.substring(1);
680       }
681       vargs.addElement(arg);
682     }
683   }
684
685   /**
686    * check for and remove first occurence of arg+parameter in arglist.
687    * 
688    * @param arg
689    * @return return the argument following the given arg if arg was in list.
690    */
691   public String getValue(String arg)
692   {
693     int index = vargs.indexOf(arg);
694     String ret = null;
695     if (index != -1)
696     {
697       ret = vargs.elementAt(index + 1).toString();
698       vargs.removeElementAt(index);
699       vargs.removeElementAt(index);
700     }
701     return ret;
702   }
703
704   /**
705    * check for and remove first occurence of arg in arglist.
706    * 
707    * @param arg
708    * @return true if arg was present in argslist.
709    */
710   public boolean contains(String arg)
711   {
712     if (vargs.contains(arg))
713     {
714       vargs.removeElement(arg);
715       return true;
716     }
717     else
718     {
719       return false;
720     }
721   }
722
723   public String nextValue()
724   {
725     return vargs.remove(0).toString();
726   }
727
728   public int getSize()
729   {
730     return vargs.size();
731   }
732
733 }