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