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