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