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