JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
3  * Copyright (C) 2015 The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import jalview.gui.AlignFrame;
24 import jalview.gui.Desktop;
25 import jalview.io.BioJsHTMLOutput;
26 import jalview.io.HtmlSvgOutput;
27 import jalview.util.MessageManager;
28 import jalview.util.Platform;
29 import jalview.ws.jws2.Jws2Discoverer;
30
31 import java.awt.event.ActionEvent;
32 import java.awt.event.ActionListener;
33 import java.io.BufferedReader;
34 import java.io.File;
35 import java.io.FileOutputStream;
36 import java.io.IOException;
37 import java.io.OutputStreamWriter;
38 import java.io.PrintWriter;
39 import java.lang.reflect.Constructor;
40 import java.net.MalformedURLException;
41 import java.net.URI;
42 import java.net.URL;
43 import java.net.URLDecoder;
44 import java.security.AllPermission;
45 import java.security.CodeSource;
46 import java.security.PermissionCollection;
47 import java.security.Permissions;
48 import java.security.Policy;
49 import java.util.HashMap;
50 import java.util.Map;
51 import java.util.Vector;
52
53 import javax.swing.UIManager;
54 import javax.swing.UnsupportedLookAndFeelException;
55
56 /**
57  * Main class for Jalview Application <br>
58  * <br>
59  * start with java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview
60  * 
61  * @author $author$
62  * @version $Revision$
63  */
64 public class Jalview
65 {
66   static
67   {
68     // grab all the rights we can the JVM
69     Policy.setPolicy(new Policy()
70     {
71       public PermissionCollection getPermissions(CodeSource codesource)
72       {
73         Permissions perms = new Permissions();
74         perms.add(new AllPermission());
75         return (perms);
76       }
77
78       public void refresh()
79       {
80       }
81     });
82   }
83
84   /**
85    * main class for Jalview application
86    * 
87    * @param args
88    *          open <em>filename</em>
89    */
90   public static void main(String[] args)
91   {
92     System.out.println("Java version: "
93             + System.getProperty("java.version"));
94     System.out.println(System.getProperty("os.arch") + " "
95             + System.getProperty("os.name") + " "
96             + System.getProperty("os.version"));
97
98     ArgsParser aparser = new ArgsParser(args);
99     boolean headless = false;
100
101     if (aparser.contains("help") || aparser.contains("h"))
102     {
103       showUsage();
104       System.exit(0);
105     }
106     if (aparser.contains("nodisplay") || aparser.contains("nogui")
107             || aparser.contains("headless"))
108     {
109       System.setProperty("java.awt.headless", "true");
110       headless = true;
111     }
112     String usrPropsFile = aparser.getValue("props");
113     Cache.loadProperties(usrPropsFile); // must do this before
114     if (usrPropsFile != null)
115     {
116       System.out.println("CMD [-props " + usrPropsFile
117               + "] executed successfully!");
118     }
119
120     // anything else!
121
122     final String jabawsUrl = aparser.getValue("jabaws");
123     if (jabawsUrl != null)
124     {
125       try
126       {
127         Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
128         System.out.println("CMD [-jabaws " + jabawsUrl
129                 + "] executed successfully!");
130       } catch (MalformedURLException e)
131       {
132         System.err.println("Invalid jabaws parameter: " + jabawsUrl
133                 + " ignored");
134       }
135     }
136
137     String defs = aparser.getValue("setprop");
138     while (defs != null)
139     {
140       int p = defs.indexOf('=');
141       if (p == -1)
142       {
143         System.err.println("Ignoring invalid setprop argument : " + defs);
144       }
145       else
146       {
147         System.out.println("Executing setprop argument: " + defs);
148         // DISABLED FOR SECURITY REASONS
149         // TODO: add a property to allow properties to be overriden by cli args
150         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
151       }
152       defs = aparser.getValue("setprop");
153     }
154     if (System.getProperty("java.awt.headless") != null
155             && System.getProperty("java.awt.headless").equals("true"))
156     {
157       headless = true;
158     }
159     System.setProperty("http.agent",
160             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
161     try
162     {
163       Cache.initLogger();
164     } catch (java.lang.NoClassDefFoundError error)
165     {
166       error.printStackTrace();
167       System.out
168               .println("\nEssential logging libraries not found."
169                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
170       System.exit(0);
171     }
172
173     Desktop desktop = null;
174
175     try
176     {
177       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
178     } catch (Exception ex)
179     {
180     }
181     if (new Platform().isAMac())
182     {
183       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
184               "Jalview");
185       System.setProperty("apple.laf.useScreenMenuBar", "true");
186       try
187       {
188         UIManager.setLookAndFeel(ch.randelshofer.quaqua.QuaquaManager
189                 .getLookAndFeel());
190       } catch (UnsupportedLookAndFeelException e)
191       {
192         // TODO Auto-generated catch block
193         e.printStackTrace();
194       }
195     }
196
197     if (!headless)
198     {
199       desktop = new Desktop();
200       desktop.setInBatchMode(true); // indicate we are starting up
201       desktop.setVisible(true);
202       desktop.startServiceDiscovery();
203       if (!aparser.contains("nousagestats"))
204       {
205         startUsageStats(desktop);
206       }
207       else
208       {
209         System.err.println("CMD [-nousagestats] executed successfully!");
210       }
211
212       if (!aparser.contains("noquestionnaire"))
213       {
214         String url = aparser.getValue("questionnaire");
215         if (url != null)
216         {
217           // Start the desktop questionnaire prompter with the specified
218           // questionnaire
219           Cache.log.debug("Starting questionnaire url at " + url);
220           desktop.checkForQuestionnaire(url);
221           System.out.println("CMD questionnaire[-" + url
222                   + "] executed successfully!");
223         }
224         else
225         {
226           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
227           {
228             // Start the desktop questionnaire prompter with the specified
229             // questionnaire
230             // String defurl =
231             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
232             // //
233             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
234             Cache.log.debug("Starting questionnaire with default url: "
235                     + defurl);
236             desktop.checkForQuestionnaire(defurl);
237
238           }
239         }
240       }
241       else
242       {
243         System.err.println("CMD [-noquestionnaire] executed successfully!");
244       }
245       desktop.checkForNews();
246     }
247
248     if (!isHeadlessMode())
249     {
250       BioJsHTMLOutput.updateBioJS();
251     }
252
253     String file = null, protocol = null, format = null, data = null;
254     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader(!headless);
255     Vector getFeatures = null; // vector of das source nicknames to fetch
256     // features from
257     // loading is done.
258     String groovyscript = null; // script to execute after all loading is
259     // completed one way or another
260     // extract groovy argument and execute if necessary
261     groovyscript = aparser.getValue("groovy", true);
262     file = aparser.getValue("open", true);
263
264     if (file == null && desktop == null)
265     {
266       System.out.println("No files to open!");
267       System.exit(1);
268     }
269     String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
270             .getValue("vsess");
271     if (vamsasImport != null || vamsasSession != null)
272     {
273       if (desktop == null || headless)
274       {
275         System.out
276                 .println("Headless vamsas sessions not yet supported. Sorry.");
277         System.exit(1);
278       }
279       // if we have a file, start a new session and import it.
280       boolean inSession = false;
281       if (vamsasImport != null)
282       {
283         try
284         {
285           String viprotocol = jalview.io.AppletFormatAdapter
286                   .checkProtocol(vamsasImport);
287           if (viprotocol == jalview.io.FormatAdapter.FILE)
288           {
289             inSession = desktop.vamsasImport(new File(vamsasImport));
290           }
291           else if (viprotocol == jalview.io.FormatAdapter.URL)
292           {
293             inSession = desktop.vamsasImport(new URL(vamsasImport));
294           }
295
296         } catch (Exception e)
297         {
298           System.err.println("Exeption when importing " + vamsasImport
299                   + " as a vamsas document.");
300           e.printStackTrace();
301         }
302         if (!inSession)
303         {
304           System.err.println("Failed to import " + vamsasImport
305                   + " as a vamsas document.");
306         }
307         else
308         {
309           System.out.println("Imported Successfully into new session "
310                   + desktop.getVamsasApplication().getCurrentSession());
311         }
312       }
313       if (vamsasSession != null)
314       {
315         if (vamsasImport != null)
316         {
317           // close the newly imported session and import the Jalview specific
318           // remnants into the new session later on.
319           desktop.vamsasStop_actionPerformed(null);
320         }
321         // now join the new session
322         try
323         {
324           if (desktop.joinVamsasSession(vamsasSession))
325           {
326             System.out.println("Successfully joined vamsas session "
327                     + vamsasSession);
328           }
329           else
330           {
331             System.err.println("WARNING: Failed to join vamsas session "
332                     + vamsasSession);
333           }
334         } catch (Exception e)
335         {
336           System.err.println("ERROR: Failed to join vamsas session "
337                   + vamsasSession);
338           e.printStackTrace();
339         }
340         if (vamsasImport != null)
341         {
342           // the Jalview specific remnants can now be imported into the new
343           // session at the user's leisure.
344           Cache.log
345                   .info("Skipping Push for import of data into existing vamsas session."); // TODO:
346           // enable
347           // this
348           // when
349           // debugged
350           // desktop.getVamsasApplication().push_update();
351         }
352       }
353     }
354     long progress = -1;
355     // Finally, deal with the remaining input data.
356     if (file != null)
357     {
358       if (!headless)
359       {
360         desktop.setProgressBar(MessageManager
361                 .getString("status.processing_commandline_args"),
362                 progress = System.currentTimeMillis());
363       }
364       System.out.println("CMD [-open " + file + "] executed successfully!");
365
366       if (!file.startsWith("http://"))
367       {
368         if (!(new java.io.File(file)).exists())
369         {
370           System.out.println("Can't find " + file);
371           if (headless)
372           {
373             System.exit(1);
374           }
375         }
376       }
377
378       protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
379
380       format = new jalview.io.IdentifyFile().Identify(file, protocol);
381
382       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
383               format);
384       if (af == null)
385       {
386         System.out.println("error");
387       }
388       else
389       {
390
391         data = aparser.getValue("colour", true);
392         if (data != null)
393         {
394           data.replaceAll("%20", " ");
395
396           jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
397                   .getColour(af.getViewport().getAlignment(), data);
398
399           if (cs == null)
400           {
401             jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
402                     "white");
403             ucs.parseAppletParameter(data);
404             cs = ucs;
405           }
406           else
407           {
408             System.out.println("CMD [-color " + data
409                     + "] executed successfully!");
410           }
411           af.changeColour(cs);
412         }
413
414         // Must maintain ability to use the groups flag
415         data = aparser.getValue("groups", true);
416         if (data != null)
417         {
418           af.parseFeaturesFile(data,
419                   jalview.io.AppletFormatAdapter.checkProtocol(data));
420           // System.out.println("Added " + data);
421           System.out.println("CMD groups[-" + data
422                   + "]  executed successfully!");
423         }
424         data = aparser.getValue("features", true);
425         if (data != null)
426         {
427           af.parseFeaturesFile(data,
428                   jalview.io.AppletFormatAdapter.checkProtocol(data));
429           // System.out.println("Added " + data);
430           System.out.println("CMD [-features " + data
431                   + "]  executed successfully!");
432         }
433
434         data = aparser.getValue("annotations", true);
435         if (data != null)
436         {
437           af.loadJalviewDataFile(data, null, null, null);
438           // System.out.println("Added " + data);
439           System.out.println("CMD [-annotations " + data
440                   + "] executed successfully!");
441         }
442         // set or clear the sortbytree flag.
443         if (aparser.contains("sortbytree"))
444         {
445           af.getViewport().setSortByTree(true);
446           if (af.getViewport().getSortByTree())
447           {
448             System.out.println("CMD [-sortbytree] executed successfully!");
449           }
450         }
451         if (aparser.contains("no-annotation"))
452         {
453           af.getViewport().setShowAnnotation(false);
454           if (!af.getViewport().isShowAnnotation())
455           {
456             System.out.println("CMD no-annotation executed successfully!");
457           }
458         }
459         if (aparser.contains("nosortbytree"))
460         {
461           af.getViewport().setSortByTree(false);
462           if (!af.getViewport().getSortByTree())
463           {
464             System.out
465                     .println("CMD [-nosortbytree] executed successfully!");
466           }
467         }
468         data = aparser.getValue("tree", true);
469         if (data != null)
470         {
471           jalview.io.NewickFile fin = null;
472           try
473           {
474             System.out.println("CMD [-tree " + data
475                     + "] executed successfully!");
476             fin = new jalview.io.NewickFile(data,
477                     jalview.io.AppletFormatAdapter.checkProtocol(data));
478             if (fin != null)
479             {
480               af.getViewport().setCurrentTree(
481                       af.ShowNewickTree(fin, data).getTree());
482             }
483           } catch (IOException ex)
484           {
485             System.err.println("Couldn't add tree " + data);
486             ex.printStackTrace(System.err);
487           }
488         }
489         // TODO - load PDB structure(s) to alignment JAL-629
490         // (associate with identical sequence in alignment, or a specified
491         // sequence)
492
493         getFeatures = checkDasArguments(aparser);
494         if (af != null && getFeatures != null)
495         {
496           FeatureFetcher ff = startFeatureFetching(getFeatures);
497           if (ff != null)
498           {
499             while (!ff.allFinished() || af.operationInProgress())
500             {
501               // wait around until fetching is finished.
502               try
503               {
504                 Thread.sleep(100);
505               } catch (Exception e)
506               {
507
508               }
509             }
510           }
511           getFeatures = null; // have retrieved features - forget them now.
512         }
513         if (groovyscript != null)
514         {
515           // Execute the groovy script after we've done all the rendering stuff
516           // and before any images or figures are generated.
517           if (jalview.bin.Cache.groovyJarsPresent())
518           {
519             System.out.println("Executing script " + groovyscript);
520             executeGroovyScript(groovyscript, new Object[] { desktop, af });
521
522             System.out.println("CMD groovy[" + groovyscript
523                     + "] executed successfully!");
524           }
525           else
526           {
527             System.err
528                     .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
529                             + groovyscript);
530           }
531           groovyscript = null;
532         }
533         String imageName = "unnamed.png";
534         while (aparser.getSize() > 1)
535         {
536           format = aparser.nextValue();
537           file = aparser.nextValue();
538
539           if (format.equalsIgnoreCase("png"))
540           {
541             af.createPNG(new java.io.File(file));
542             imageName = (new java.io.File(file)).getName();
543             System.out.println("Creating PNG image: " + file);
544             continue;
545           }
546           else if (format.equalsIgnoreCase("svg"))
547           {
548             File imageFile = new java.io.File(file);
549             imageName = imageFile.getName();
550             af.createSVG(imageFile);
551             System.out.println("Creating SVG image: " + file);
552             continue;
553           }
554           else if (format.equalsIgnoreCase("html"))
555           {
556             File imageFile = new java.io.File(file);
557             imageName = imageFile.getName();
558             new HtmlSvgOutput(new java.io.File(file), af.alignPanel);
559             System.out.println("Creating HTML image: " + file);
560             continue;
561           }
562           else if (format.equalsIgnoreCase("imgMap"))
563           {
564             af.createImageMap(new java.io.File(file), imageName);
565             System.out.println("Creating image map: " + file);
566             continue;
567           }
568           else if (format.equalsIgnoreCase("eps"))
569           {
570             File outputFile = new java.io.File(file);
571             System.out.println("Creating EPS file: "
572                     + outputFile.getAbsolutePath());
573             af.createEPS(outputFile);
574             continue;
575           }
576
577           if (af.saveAlignment(file, format))
578           {
579             System.out.println("Written alignment in " + format
580                     + " format to " + file);
581           }
582           else
583           {
584             System.out.println("Error writing file " + file + " in "
585                     + format + " format!!");
586           }
587
588         }
589
590         while (aparser.getSize() > 0)
591         {
592           System.out.println("Unknown arg: " + aparser.nextValue());
593         }
594       }
595     }
596     AlignFrame startUpAlframe = null;
597     // We'll only open the default file if the desktop is visible.
598     // And the user
599     // ////////////////////
600
601     if (!headless && file == null && vamsasImport == null
602             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
603     {
604       file = jalview.bin.Cache.getDefault(
605               "STARTUP_FILE",
606               jalview.bin.Cache.getDefault("www.jalview.org",
607                       "http://www.jalview.org")
608                       + "/examples/exampleFile_2_7.jar");
609       if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar"))
610       {
611         // hardwire upgrade of the startup file
612         file.replace("_2_3.jar", "_2_7.jar");
613         // and remove the stale setting
614         jalview.bin.Cache.removeProperty("STARTUP_FILE");
615       }
616
617       protocol = "File";
618
619       if (file.indexOf("http:") > -1)
620       {
621         protocol = "URL";
622       }
623
624       if (file.endsWith(".jar"))
625       {
626         format = "Jalview";
627       }
628       else
629       {
630         format = new jalview.io.IdentifyFile().Identify(file, protocol);
631       }
632
633       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
634               format);
635       getFeatures = checkDasArguments(aparser);
636       // extract groovy arguments before anything else.
637     }
638     // If the user has specified features to be retrieved,
639     // or a groovy script to be executed, do them if they
640     // haven't been done already
641     // fetch features for the default alignment
642     if (getFeatures != null)
643     {
644       if (startUpAlframe != null)
645       {
646         startFeatureFetching(getFeatures);
647       }
648     }
649     // Once all other stuff is done, execute any groovy scripts (in order)
650     if (groovyscript != null)
651     {
652       if (jalview.bin.Cache.groovyJarsPresent())
653       {
654         System.out.println("Executing script " + groovyscript);
655         executeGroovyScript(groovyscript, new Object[] { desktop,
656             startUpAlframe });
657       }
658       else
659       {
660         System.err
661                 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
662                         + groovyscript);
663       }
664     }
665     // and finally, turn off batch mode indicator - if the desktop still exists
666     if (desktop != null)
667     {
668       if (progress != -1)
669       {
670         desktop.setProgressBar(null, progress);
671       }
672       desktop.setInBatchMode(false);
673     }
674   }
675
676   private static void showUsage()
677   {
678     System.out
679             .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
680                     + "-nodisplay\tRun Jalview without User Interface.\n"
681                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
682                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
683                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
684                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
685                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
686                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
687                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
688                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
689                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
690                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
691                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
692                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
693                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
694                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
695                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
696                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
697                     + "-html FILE\tCreate HTML file from alignment.\n"
698                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
699                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
700                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
701                     + "-noquestionnaire\tTurn off questionnaire check.\n"
702                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
703                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
704                     // +
705                     // "-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)"
706                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
707                     + "-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"
708                     + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
709                     + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
710                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
711                     // +
712                     // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
713                     // + "-vses vamsas-session\tJoin session with given URN\n"
714                     + "-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"
715                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
716   }
717
718   private static void startUsageStats(final Desktop desktop)
719   {
720     /**
721      * start a User Config prompt asking if we can log usage statistics.
722      */
723     jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
724             desktop.desktop,
725             "USAGESTATS",
726             "Jalview Usage Statistics",
727             "Do you want to help make Jalview better by enabling "
728                     + "the collection of usage statistics with Google Analytics ?"
729                     + "\n\n(you can enable or disable usage tracking in the preferences)",
730             new Runnable()
731             {
732               public void run()
733               {
734                 Cache.log
735                         .debug("Initialising googletracker for usage stats.");
736                 Cache.initGoogleTracker();
737                 Cache.log.debug("Tracking enabled.");
738               }
739             }, new Runnable()
740             {
741               public void run()
742               {
743                 Cache.log.debug("Not enabling Google Tracking.");
744               }
745             }, null, true);
746     desktop.addDialogThread(prompter);
747   }
748
749   /**
750    * Locate the given string as a file and pass it to the groovy interpreter.
751    * 
752    * @param groovyscript
753    *          the script to execute
754    * @param jalviewContext
755    *          the Jalview Desktop object passed in to the groovy binding as the
756    *          'Jalview' object.
757    */
758   private static void executeGroovyScript(String groovyscript,
759           Object[] jalviewContext)
760   {
761     if (jalviewContext == null)
762     {
763       System.err
764               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
765     }
766     /**
767      * for scripts contained in files
768      */
769     File tfile = null;
770     /**
771      * script's URI
772      */
773     URL sfile = null;
774     if (groovyscript.trim().equals("STDIN"))
775     {
776       // read from stdin into a tempfile and execute it
777       try
778       {
779         tfile = File.createTempFile("jalview", "groovy");
780         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
781                 new FileOutputStream(tfile)));
782         BufferedReader br = new BufferedReader(
783                 new java.io.InputStreamReader(System.in));
784         String line = null;
785         while ((line = br.readLine()) != null)
786         {
787           outfile.write(line + "\n");
788         }
789         br.close();
790         outfile.flush();
791         outfile.close();
792
793       } catch (Exception ex)
794       {
795         System.err.println("Failed to read from STDIN into tempfile "
796                 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
797                         .toString()));
798         ex.printStackTrace();
799         return;
800       }
801       try
802       {
803         sfile = tfile.toURI().toURL();
804       } catch (Exception x)
805       {
806         System.err
807                 .println("Unexpected Malformed URL Exception for temporary file created from STDIN: "
808                         + tfile.toURI());
809         x.printStackTrace();
810         return;
811       }
812     }
813     else
814     {
815       try
816       {
817         sfile = new URI(groovyscript).toURL();
818       } catch (Exception x)
819       {
820         tfile = new File(groovyscript);
821         if (!tfile.exists())
822         {
823           System.err.println("File '" + groovyscript + "' does not exist.");
824           return;
825         }
826         if (!tfile.canRead())
827         {
828           System.err.println("File '" + groovyscript + "' cannot be read.");
829           return;
830         }
831         if (tfile.length() < 1)
832         {
833           System.err.println("File '" + groovyscript + "' is empty.");
834           return;
835         }
836         try
837         {
838           sfile = tfile.getAbsoluteFile().toURI().toURL();
839         } catch (Exception ex)
840         {
841           System.err.println("Failed to create a file URL for "
842                   + tfile.getAbsoluteFile());
843           return;
844         }
845       }
846     }
847     boolean success = false;
848     try
849     {
850       /*
851        * The following code performs the GroovyScriptEngine invocation using
852        * reflection, and is equivalent to this fragment from the embedding
853        * groovy documentation on the groovy site: <code> import
854        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
855        * 
856        * String[] roots = new String[] { "/my/groovy/script/path" };
857        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
858        * = new Binding(); binding.setVariable("input", "world");
859        * gse.run("hello.groovy", binding); </code>
860        */
861       Class<?>[] bspec;
862       Object[] binding;
863       int blen = ((jalviewContext[0] == null) ? 0 : 1)
864               + ((jalviewContext[1] == null) ? 0 : 1);
865       String cnames[] = new String[] { "Jalview", "currentAlFrame" };
866       bspec = new Class[blen * 2];
867       binding = new Object[blen * 2];
868       blen = 0;
869       ClassLoader cl = null;
870       Map<String, Object> vbinding = new HashMap<String, Object>();
871       for (int jc = 0; jc < jalviewContext.length; jc++)
872       {
873         if (jalviewContext[jc] != null)
874         {
875           if (cl == null)
876           {
877             cl = jalviewContext[jc].getClass().getClassLoader();
878           }
879           bspec[blen * 2] = String.class;
880           bspec[blen * 2 + 1] = Object.class;
881           binding[blen * 2] = cnames[jc];
882           binding[blen * 2 + 1] = jalviewContext[jc];
883           vbinding.put(cnames[jc], jalviewContext[jc]);
884           blen++;
885         }
886       }
887       Class<?> gbindingc = cl.loadClass("groovy.lang.Binding");
888       Constructor<?> gbcons;
889       Object gbinding;
890       try
891       {
892         gbcons = gbindingc.getConstructor(Map.class);
893         gbinding = gbcons.newInstance(vbinding);
894       } catch (NoSuchMethodException x)
895       {
896         // old style binding config - using series of string/object values to
897         // setVariable.
898         gbcons = gbindingc.getConstructor();
899         gbinding = gbcons.newInstance();
900         java.lang.reflect.Method setvar = gbindingc.getMethod(
901                 "setVariable", bspec);
902         setvar.invoke(gbinding, binding);
903       }
904
905       Class<?> gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
906       Constructor<?> gseccons = gsec
907               .getConstructor(new Class[] { URL[].class }); // String[].class
908                                                             // });
909       Object gse = gseccons
910               .newInstance(new Object[] { new URL[] { sfile } }); // .toString()
911                                                                   // } });
912       java.lang.reflect.Method run = gsec.getMethod("run", new Class[] {
913           String.class, gbindingc });
914       run.invoke(gse, new Object[] { sfile.toString(), gbinding });
915       success = true;
916     } catch (Exception e)
917     {
918       System.err.println("Exception Whilst trying to execute file " + sfile
919               + " as a groovy script.");
920       e.printStackTrace(System.err);
921
922     }
923     if (success && groovyscript.equals("STDIN"))
924     {
925       // delete temp file that we made - but only if it was successfully
926       // executed
927       tfile.delete();
928     }
929   }
930
931   /**
932    * Check commandline for any das server definitions or any fetchfrom switches
933    * 
934    * @return vector of DAS source nicknames to retrieve from
935    */
936   private static Vector checkDasArguments(ArgsParser aparser)
937   {
938     Vector source = null;
939     String data;
940     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
941     while ((data = aparser.getValue("dasserver", true)) != null)
942     {
943       String nickname = null;
944       String url = null;
945       boolean seq = false, feat = true;
946       int pos = data.indexOf('=');
947       // determine capabilities
948       if (pos > 0)
949       {
950         nickname = data.substring(0, pos);
951       }
952       url = data.substring(pos + 1);
953       if (url != null
954               && (url.startsWith("http:") || url
955                       .startsWith("sequence:http:")))
956       {
957         if (nickname == null)
958         {
959           nickname = url;
960         }
961         if (locsources == null)
962         {
963           locsources = "";
964         }
965         else
966         {
967           locsources += "\t";
968         }
969         locsources = locsources + nickname + "|" + url;
970         System.err
971                 .println("NOTE! dasserver parameter not yet really supported (got args of "
972                         + nickname + "|" + url);
973         if (source == null)
974         {
975           source = new Vector();
976         }
977         source.addElement(nickname);
978       }
979       System.out.println("CMD [-dasserver " + data
980               + "] executed successfully!");
981     } // loop until no more server entries are found.
982     if (locsources != null && locsources.indexOf('|') > -1)
983     {
984       Cache.log.debug("Setting local source list in properties file to:\n"
985               + locsources);
986       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
987     }
988     while ((data = aparser.getValue("fetchfrom", true)) != null)
989     {
990       System.out.println("adding source '" + data + "'");
991       if (source == null)
992       {
993         source = new Vector();
994       }
995       source.addElement(data);
996     }
997     return source;
998   }
999
1000   /**
1001    * start a feature fetcher for every alignment frame
1002    * 
1003    * @param dasSources
1004    */
1005   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
1006   {
1007     FeatureFetcher ff = new FeatureFetcher();
1008     AlignFrame afs[] = Desktop.getAlignFrames();
1009     if (afs == null || afs.length == 0)
1010     {
1011       return null;
1012     }
1013     for (int i = 0; i < afs.length; i++)
1014     {
1015       ff.addFetcher(afs[i], dasSources);
1016     }
1017     return ff;
1018   }
1019
1020   public static boolean isHeadlessMode()
1021   {
1022     String isheadless = System.getProperty("java.awt.headless");
1023     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1024     {
1025       return true;
1026     }
1027     return false;
1028   }
1029 }
1030
1031 /**
1032  * Notes: this argParser does not distinguish between parameter switches,
1033  * parameter values and argument text. If an argument happens to be identical to
1034  * a parameter, it will be taken as such (even though it didn't have a '-'
1035  * prefixing it).
1036  * 
1037  * @author Andrew Waterhouse and JBP documented.
1038  * 
1039  */
1040
1041 class rnabuttonlistener implements ActionListener
1042 {
1043   public void actionPerformed(ActionEvent arg0)
1044   {
1045     System.out.println("Good idea ! ");
1046
1047   }
1048 }
1049
1050 class pbuttonlistener implements ActionListener
1051 {
1052   public void actionPerformed(ActionEvent arg0)
1053   {
1054
1055   }
1056 }
1057
1058 class ArgsParser
1059 {
1060   Vector vargs = null;
1061
1062   public ArgsParser(String[] args)
1063   {
1064     vargs = new Vector();
1065     for (int i = 0; i < args.length; i++)
1066     {
1067       String arg = args[i].trim();
1068       if (arg.charAt(0) == '-')
1069       {
1070         arg = arg.substring(1);
1071       }
1072       vargs.addElement(arg);
1073     }
1074   }
1075
1076   /**
1077    * check for and remove first occurence of arg+parameter in arglist.
1078    * 
1079    * @param arg
1080    * @return return the argument following the given arg if arg was in list.
1081    */
1082   public String getValue(String arg)
1083   {
1084     return getValue(arg, false);
1085   }
1086
1087   public String getValue(String arg, boolean utf8decode)
1088   {
1089     int index = vargs.indexOf(arg);
1090     String dc = null, ret = null;
1091     if (index != -1)
1092     {
1093       ret = vargs.elementAt(index + 1).toString();
1094       vargs.removeElementAt(index);
1095       vargs.removeElementAt(index);
1096       if (utf8decode && ret != null)
1097       {
1098         try
1099         {
1100           dc = URLDecoder.decode(ret, "UTF-8");
1101           ret = dc;
1102         } catch (Exception e)
1103         {
1104           // TODO: log failure to decode
1105         }
1106       }
1107     }
1108     return ret;
1109   }
1110
1111   /**
1112    * check for and remove first occurence of arg in arglist.
1113    * 
1114    * @param arg
1115    * @return true if arg was present in argslist.
1116    */
1117   public boolean contains(String arg)
1118   {
1119     if (vargs.contains(arg))
1120     {
1121       vargs.removeElement(arg);
1122       return true;
1123     }
1124     else
1125     {
1126       return false;
1127     }
1128   }
1129
1130   public String nextValue()
1131   {
1132     return vargs.remove(0).toString();
1133   }
1134
1135   public int getSize()
1136   {
1137     return vargs.size();
1138   }
1139
1140 }
1141
1142 /**
1143  * keep track of feature fetching tasks.
1144  * 
1145  * @author JimP
1146  * 
1147  */
1148 class FeatureFetcher
1149 {
1150   /*
1151    * TODO: generalise to track all jalview events to orchestrate batch
1152    * processing events.
1153    */
1154
1155   private int queued = 0;
1156
1157   private int running = 0;
1158
1159   public FeatureFetcher()
1160   {
1161
1162   }
1163
1164   public void addFetcher(final AlignFrame af, final Vector dasSources)
1165   {
1166     final long id = System.currentTimeMillis();
1167     queued++;
1168     final FeatureFetcher us = this;
1169     new Thread(new Runnable()
1170     {
1171
1172       public void run()
1173       {
1174         synchronized (us)
1175         {
1176           queued--;
1177           running++;
1178         }
1179
1180         af.setProgressBar(MessageManager
1181                 .getString("status.das_features_being_retrived"), id);
1182         af.featureSettings_actionPerformed(null);
1183         af.featureSettings.fetchDasFeatures(dasSources, true);
1184         af.setProgressBar(null, id);
1185         synchronized (us)
1186         {
1187           running--;
1188         }
1189       }
1190     }).start();
1191   }
1192
1193   public synchronized boolean allFinished()
1194   {
1195     return queued == 0 && running == 0;
1196   }
1197
1198 }