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