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