JAL-1788 added help documentation for biojson
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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
244 .println("CMD [-noquestionnaire] executed successfully!");
245       }
246       desktop.checkForNews();
247     }
248
249     if (!isHeadlessMode())
250     {
251       BioJsHTMLOutput.updateBioJS();
252     }
253
254     String file = null, protocol = null, format = null, data = null;
255     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader(!headless);
256     Vector getFeatures = null; // vector of das source nicknames to fetch
257     // features from
258     // loading is done.
259     String groovyscript = null; // script to execute after all loading is
260     // completed one way or another
261     // extract groovy argument and execute if necessary
262     groovyscript = aparser.getValue("groovy", true);
263     file = aparser.getValue("open", true);
264
265     if (file == null && desktop == null)
266     {
267       System.out.println("No files to open!");
268       System.exit(1);
269     }
270     String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
271             .getValue("vsess");
272     if (vamsasImport != null || vamsasSession != null)
273     {
274       if (desktop == null || headless)
275       {
276         System.out
277                 .println("Headless vamsas sessions not yet supported. Sorry.");
278         System.exit(1);
279       }
280       // if we have a file, start a new session and import it.
281       boolean inSession = false;
282       if (vamsasImport != null)
283       {
284         try
285         {
286           String viprotocol = jalview.io.AppletFormatAdapter
287                   .checkProtocol(vamsasImport);
288           if (viprotocol == jalview.io.FormatAdapter.FILE)
289           {
290             inSession = desktop.vamsasImport(new File(vamsasImport));
291           }
292           else if (viprotocol == jalview.io.FormatAdapter.URL)
293           {
294             inSession = desktop.vamsasImport(new URL(vamsasImport));
295           }
296
297         } catch (Exception e)
298         {
299           System.err.println("Exeption when importing " + vamsasImport
300                   + " as a vamsas document.");
301           e.printStackTrace();
302         }
303         if (!inSession)
304         {
305           System.err.println("Failed to import " + vamsasImport
306                   + " as a vamsas document.");
307         }
308         else
309         {
310           System.out.println("Imported Successfully into new session "
311                   + desktop.getVamsasApplication().getCurrentSession());
312         }
313       }
314       if (vamsasSession != null)
315       {
316         if (vamsasImport != null)
317         {
318           // close the newly imported session and import the Jalview specific
319           // remnants into the new session later on.
320           desktop.vamsasStop_actionPerformed(null);
321         }
322         // now join the new session
323         try
324         {
325           if (desktop.joinVamsasSession(vamsasSession))
326           {
327             System.out.println("Successfully joined vamsas session "
328                     + vamsasSession);
329           }
330           else
331           {
332             System.err.println("WARNING: Failed to join vamsas session "
333                     + vamsasSession);
334           }
335         } catch (Exception e)
336         {
337           System.err.println("ERROR: Failed to join vamsas session "
338                   + vamsasSession);
339           e.printStackTrace();
340         }
341         if (vamsasImport != null)
342         {
343           // the Jalview specific remnants can now be imported into the new
344           // session at the user's leisure.
345           Cache.log
346                   .info("Skipping Push for import of data into existing vamsas session."); // TODO:
347           // enable
348           // this
349           // when
350           // debugged
351           // desktop.getVamsasApplication().push_update();
352         }
353       }
354     }
355     long progress = -1;
356     // Finally, deal with the remaining input data.
357     if (file != null)
358     {
359       if (!headless)
360       {
361         desktop.setProgressBar(MessageManager.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
449 .println("CMD [-sortbytree] executed successfully!");
450           }
451         }
452         if (aparser.contains("no-annotation"))
453         {
454           af.getViewport().setShowAnnotation(false);
455           if (!af.getViewport().isShowAnnotation())
456           {
457             System.out
458 .println("CMD no-annotation executed successfully!");
459           }
460         }
461         if (aparser.contains("nosortbytree"))
462         {
463           af.getViewport().setSortByTree(false);
464           if (!af.getViewport().getSortByTree())
465           {
466             System.out
467                     .println("CMD [-nosortbytree] executed successfully!");
468           }
469         }
470         data = aparser.getValue("tree", true);
471         if (data != null)
472         {
473           jalview.io.NewickFile fin = null;
474           try
475           {
476             System.out.println("CMD [-tree " + data
477                     + "] executed successfully!");
478             fin = new jalview.io.NewickFile(data,
479                     jalview.io.AppletFormatAdapter.checkProtocol(data));
480             if (fin != null)
481             {
482               af.getViewport().setCurrentTree(
483                       af.ShowNewickTree(fin, data).getTree());
484             }
485           } catch (IOException ex)
486           {
487             System.err.println("Couldn't add tree " + data);
488             ex.printStackTrace(System.err);
489           }
490         }
491         // TODO - load PDB structure(s) to alignment JAL-629
492         // (associate with identical sequence in alignment, or a specified
493         // sequence)
494
495         getFeatures = checkDasArguments(aparser);
496         if (af != null && getFeatures != null)
497         {
498           FeatureFetcher ff = startFeatureFetching(getFeatures);
499           if (ff != null)
500           {
501             while (!ff.allFinished() || af.operationInProgress())
502             {
503               // wait around until fetching is finished.
504               try
505               {
506                 Thread.sleep(100);
507               } catch (Exception e)
508               {
509
510               }
511             }
512           }
513           getFeatures = null; // have retrieved features - forget them now.
514         }
515         if (groovyscript != null)
516         {
517           // Execute the groovy script after we've done all the rendering stuff
518           // and before any images or figures are generated.
519           if (jalview.bin.Cache.groovyJarsPresent())
520           {
521             System.out.println("Executing script " + groovyscript);
522             executeGroovyScript(groovyscript, new Object[]
523             { desktop, af });
524
525             System.out.println("CMD groovy[" + groovyscript
526                     + "] executed successfully!");
527           }
528           else
529           {
530             System.err
531                     .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
532                             + groovyscript);
533           }
534           groovyscript = null;
535         }
536         String imageName = "unnamed.png";
537         while (aparser.getSize() > 1)
538         {
539           format = aparser.nextValue();
540           file = aparser.nextValue();
541
542           if (format.equalsIgnoreCase("png"))
543           {
544             af.createPNG(new java.io.File(file));
545             imageName = (new java.io.File(file)).getName();
546             System.out.println("Creating PNG image: " + file);
547             continue;
548           }
549           else if (format.equalsIgnoreCase("svg"))
550           {
551             File imageFile = new java.io.File(file);
552             imageName = imageFile.getName();
553             af.createSVG(imageFile);
554             System.out.println("Creating SVG image: " + file);
555             continue;
556           }
557           else if (format.equalsIgnoreCase("html"))
558           {
559             File imageFile = new java.io.File(file);
560             imageName = imageFile.getName();
561             new HtmlSvgOutput(new java.io.File(file), af.alignPanel);
562             System.out.println("Creating HTML image: " + file);
563             continue;
564           }
565           else if (format.equalsIgnoreCase("imgMap"))
566           {
567             af.createImageMap(new java.io.File(file), imageName);
568             System.out.println("Creating image map: " + file);
569             continue;
570           }
571           else if (format.equalsIgnoreCase("eps"))
572           {
573             File outputFile = new java.io.File(file);
574             System.out.println("Creating EPS file: "
575                     + outputFile.getAbsolutePath());
576             af.createEPS(outputFile);
577             continue;
578           }
579
580           if (af.saveAlignment(file, format))
581           {
582             System.out.println("Written alignment in " + format
583                     + " format to " + file);
584           }
585           else
586           {
587             System.out.println("Error writing file " + file + " in "
588                     + format + " format!!");
589           }
590
591         }
592
593         while (aparser.getSize() > 0)
594         {
595           System.out.println("Unknown arg: " + aparser.nextValue());
596         }
597       }
598     }
599     AlignFrame startUpAlframe = null;
600     // We'll only open the default file if the desktop is visible.
601     // And the user
602     // ////////////////////
603
604     if (!headless && file == null && vamsasImport == null
605             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
606     {
607       file = jalview.bin.Cache.getDefault(
608               "STARTUP_FILE",
609               jalview.bin.Cache.getDefault("www.jalview.org",
610                       "http://www.jalview.org")
611                       + "/examples/exampleFile_2_7.jar");
612       if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar"))
613       {
614         // hardwire upgrade of the startup file
615         file.replace("_2_3.jar", "_2_7.jar");
616         // and remove the stale setting
617         jalview.bin.Cache.removeProperty("STARTUP_FILE");
618       }
619
620       protocol = "File";
621
622       if (file.indexOf("http:") > -1)
623       {
624         protocol = "URL";
625       }
626
627       if (file.endsWith(".jar"))
628       {
629         format = "Jalview";
630       }
631       else
632       {
633         format = new jalview.io.IdentifyFile().Identify(file, protocol);
634       }
635
636       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
637               format);
638       getFeatures = checkDasArguments(aparser);
639       // extract groovy arguments before anything else.
640     }
641     // If the user has specified features to be retrieved,
642     // or a groovy script to be executed, do them if they
643     // haven't been done already
644     // fetch features for the default alignment
645     if (getFeatures != null)
646     {
647       if (startUpAlframe != null)
648       {
649         startFeatureFetching(getFeatures);
650       }
651     }
652     // Once all other stuff is done, execute any groovy scripts (in order)
653     if (groovyscript != null)
654     {
655       if (jalview.bin.Cache.groovyJarsPresent())
656       {
657         System.out.println("Executing script " + groovyscript);
658         executeGroovyScript(groovyscript, new Object[]
659         { desktop, startUpAlframe });
660       }
661       else
662       {
663         System.err
664                 .println("Sorry. Groovy Support is not available, so ignoring the provided groovy script "
665                         + groovyscript);
666       }
667     }
668     // and finally, turn off batch mode indicator - if the desktop still exists
669     if (desktop != null)
670     {
671       if (progress != -1)
672       {
673         desktop.setProgressBar(null, progress);
674       }
675       desktop.setInBatchMode(false);
676     }
677   }
678
679   private static void showUsage()
680   {
681     System.out
682             .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
683                     + "-nodisplay\tRun Jalview without User Interface.\n"
684                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
685                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
686                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
687                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
688                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
689                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
690                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
691                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
692                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
693                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
694                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
695                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
696                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
697                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
698                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
699                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
700                     + "-html FILE\tCreate HTML file from alignment.\n"
701                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
702                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
703                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
704                     + "-noquestionnaire\tTurn off questionnaire check.\n"
705                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
706                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
707                     // +
708                     // "-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)"
709                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
710                     + "-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"
711                     + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
712                     + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
713                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
714                     // +
715                     // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
716                     // + "-vses vamsas-session\tJoin session with given URN\n"
717                     + "-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"
718                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
719   }
720
721   private static void startUsageStats(final Desktop desktop)
722   {
723     /**
724      * start a User Config prompt asking if we can log usage statistics.
725      */
726     jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
727             desktop.desktop,
728             "USAGESTATS",
729             "Jalview Usage Statistics",
730             "Do you want to help make Jalview better by enabling "
731                     + "the collection of usage statistics with Google Analytics ?"
732                     + "\n\n(you can enable or disable usage tracking in the preferences)",
733             new Runnable()
734             {
735               public void run()
736               {
737                 Cache.log
738                         .debug("Initialising googletracker for usage stats.");
739                 Cache.initGoogleTracker();
740                 Cache.log.debug("Tracking enabled.");
741               }
742             }, new Runnable()
743             {
744               public void run()
745               {
746                 Cache.log.debug("Not enabling Google Tracking.");
747               }
748             }, null, true);
749     desktop.addDialogThread(prompter);
750   }
751
752   /**
753    * Locate the given string as a file and pass it to the groovy interpreter.
754    * 
755    * @param groovyscript
756    *          the script to execute
757    * @param jalviewContext
758    *          the Jalview Desktop object passed in to the groovy binding as the
759    *          'Jalview' object.
760    */
761   private static void executeGroovyScript(String groovyscript,
762           Object[] jalviewContext)
763   {
764     if (jalviewContext == null)
765     {
766       System.err
767               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
768     }
769     /**
770      * for scripts contained in files
771      */
772     File tfile = null;
773     /**
774      * script's URI
775      */
776     URL sfile = null;
777     if (groovyscript.trim().equals("STDIN"))
778     {
779       // read from stdin into a tempfile and execute it
780       try
781       {
782         tfile = File.createTempFile("jalview", "groovy");
783         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
784                 new FileOutputStream(tfile)));
785         BufferedReader br = new BufferedReader(
786                 new java.io.InputStreamReader(System.in));
787         String line = null;
788         while ((line = br.readLine()) != null)
789         {
790           outfile.write(line + "\n");
791         }
792         br.close();
793         outfile.flush();
794         outfile.close();
795
796       } catch (Exception ex)
797       {
798         System.err.println("Failed to read from STDIN into tempfile "
799                 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
800                         .toString()));
801         ex.printStackTrace();
802         return;
803       }
804       try
805       {
806         sfile = tfile.toURI().toURL();
807       } catch (Exception x)
808       {
809         System.err
810                 .println("Unexpected Malformed URL Exception for temporary file created from STDIN: "
811                         + tfile.toURI());
812         x.printStackTrace();
813         return;
814       }
815     }
816     else
817     {
818       try
819       {
820         sfile = new URI(groovyscript).toURL();
821       } catch (Exception x)
822       {
823         tfile = new File(groovyscript);
824         if (!tfile.exists())
825         {
826           System.err.println("File '" + groovyscript + "' does not exist.");
827           return;
828         }
829         if (!tfile.canRead())
830         {
831           System.err.println("File '" + groovyscript + "' cannot be read.");
832           return;
833         }
834         if (tfile.length() < 1)
835         {
836           System.err.println("File '" + groovyscript + "' is empty.");
837           return;
838         }
839         try
840         {
841           sfile = tfile.getAbsoluteFile().toURI().toURL();
842         } catch (Exception ex)
843         {
844           System.err.println("Failed to create a file URL for "
845                   + tfile.getAbsoluteFile());
846           return;
847         }
848       }
849     }
850     boolean success = false;
851     try
852     {
853       /*
854        * The following code performs the GroovyScriptEngine invocation using
855        * reflection, and is equivalent to this fragment from the embedding
856        * groovy documentation on the groovy site: <code> import
857        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
858        * 
859        * String[] roots = new String[] { "/my/groovy/script/path" };
860        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
861        * = new Binding(); binding.setVariable("input", "world");
862        * gse.run("hello.groovy", binding); </code>
863        */
864       Class<?>[] bspec;
865       Object[] binding;
866       int blen = ((jalviewContext[0] == null) ? 0 : 1)
867               + ((jalviewContext[1] == null) ? 0 : 1);
868       String cnames[] = new String[]
869       { "Jalview", "currentAlFrame" };
870       bspec = new Class[blen * 2];
871       binding = new Object[blen * 2];
872       blen = 0;
873       ClassLoader cl = null;
874       Map<String, Object> vbinding = new HashMap<String, Object>();
875       for (int jc = 0; jc < jalviewContext.length; jc++)
876       {
877         if (jalviewContext[jc] != null)
878         {
879           if (cl == null)
880           {
881             cl = jalviewContext[jc].getClass().getClassLoader();
882           }
883           bspec[blen * 2] = String.class;
884           bspec[blen * 2 + 1] = Object.class;
885           binding[blen * 2] = cnames[jc];
886           binding[blen * 2 + 1] = jalviewContext[jc];
887           vbinding.put(cnames[jc], jalviewContext[jc]);
888           blen++;
889         }
890       }
891       Class<?> gbindingc = cl.loadClass("groovy.lang.Binding");
892       Constructor<?> gbcons;
893       Object gbinding;
894       try
895       {
896         gbcons = gbindingc.getConstructor(Map.class);
897         gbinding = gbcons.newInstance(vbinding);
898       } catch (NoSuchMethodException x)
899       {
900         // old style binding config - using series of string/object values to
901         // setVariable.
902         gbcons = gbindingc.getConstructor();
903         gbinding = gbcons.newInstance();
904         java.lang.reflect.Method setvar = gbindingc.getMethod(
905                 "setVariable", bspec);
906         setvar.invoke(gbinding, binding);
907       }
908
909       Class<?> gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
910       Constructor<?> gseccons = gsec.getConstructor(new Class[]
911       { URL[].class }); // String[].class });
912       Object gse = gseccons.newInstance(new Object[]
913       { new URL[]
914       { sfile } }); // .toString() } });
915       java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
916       { String.class, gbindingc });
917       run.invoke(gse, new Object[]
918       { sfile.toString(), gbinding });
919       success = true;
920     } catch (Exception e)
921     {
922       System.err.println("Exception Whilst trying to execute file " + sfile
923               + " as a groovy script.");
924       e.printStackTrace(System.err);
925
926     }
927     if (success && groovyscript.equals("STDIN"))
928     {
929       // delete temp file that we made - but only if it was successfully
930       // executed
931       tfile.delete();
932     }
933   }
934
935   /**
936    * Check commandline for any das server definitions or any fetchfrom switches
937    * 
938    * @return vector of DAS source nicknames to retrieve from
939    */
940   private static Vector checkDasArguments(ArgsParser aparser)
941   {
942     Vector source = null;
943     String data;
944     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
945     while ((data = aparser.getValue("dasserver", true)) != null)
946     {
947       String nickname = null;
948       String url = null;
949       boolean seq = false, feat = true;
950       int pos = data.indexOf('=');
951       // determine capabilities
952       if (pos > 0)
953       {
954         nickname = data.substring(0, pos);
955       }
956       url = data.substring(pos + 1);
957       if (url != null
958               && (url.startsWith("http:") || url
959                       .startsWith("sequence:http:")))
960       {
961         if (nickname == null)
962         {
963           nickname = url;
964         }
965         if (locsources == null)
966         {
967           locsources = "";
968         }
969         else
970         {
971           locsources += "\t";
972         }
973         locsources = locsources + nickname + "|" + url;
974         System.err
975                 .println("NOTE! dasserver parameter not yet really supported (got args of "
976                         + nickname + "|" + url);
977         if (source == null)
978         {
979           source = new Vector();
980         }
981         source.addElement(nickname);
982       }
983       System.out.println("CMD [-dasserver " + data
984               + "] executed successfully!");
985     } // loop until no more server entries are found.
986     if (locsources != null && locsources.indexOf('|') > -1)
987     {
988       Cache.log.debug("Setting local source list in properties file to:\n"
989               + locsources);
990       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
991     }
992     while ((data = aparser.getValue("fetchfrom", true)) != null)
993     {
994       System.out.println("adding source '" + data + "'");
995       if (source == null)
996       {
997         source = new Vector();
998       }
999       source.addElement(data);
1000     }
1001     return source;
1002   }
1003
1004   /**
1005    * start a feature fetcher for every alignment frame
1006    * 
1007    * @param dasSources
1008    */
1009   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
1010   {
1011     FeatureFetcher ff = new FeatureFetcher();
1012     AlignFrame afs[] = Desktop.getAlignFrames();
1013     if (afs == null || afs.length == 0)
1014     {
1015       return null;
1016     }
1017     for (int i = 0; i < afs.length; i++)
1018     {
1019       ff.addFetcher(afs[i], dasSources);
1020     }
1021     return ff;
1022   }
1023
1024   public static boolean isHeadlessMode()
1025   {
1026     String isheadless = System.getProperty("java.awt.headless");
1027     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1028     {
1029       return true;
1030     }
1031     return false;
1032   }
1033 }
1034
1035 /**
1036  * Notes: this argParser does not distinguish between parameter switches,
1037  * parameter values and argument text. If an argument happens to be identical to
1038  * a parameter, it will be taken as such (even though it didn't have a '-'
1039  * prefixing it).
1040  * 
1041  * @author Andrew Waterhouse and JBP documented.
1042  * 
1043  */
1044
1045 class rnabuttonlistener implements ActionListener
1046 {
1047   public void actionPerformed(ActionEvent arg0)
1048   {
1049     System.out.println("Good idea ! ");
1050
1051   }
1052 }
1053
1054 class pbuttonlistener implements ActionListener
1055 {
1056   public void actionPerformed(ActionEvent arg0)
1057   {
1058
1059   }
1060 }
1061
1062 class ArgsParser
1063 {
1064   Vector vargs = null;
1065
1066   public ArgsParser(String[] args)
1067   {
1068     vargs = new Vector();
1069     for (int i = 0; i < args.length; i++)
1070     {
1071       String arg = args[i].trim();
1072       if (arg.charAt(0) == '-')
1073       {
1074         arg = arg.substring(1);
1075       }
1076       vargs.addElement(arg);
1077     }
1078   }
1079
1080   /**
1081    * check for and remove first occurence of arg+parameter in arglist.
1082    * 
1083    * @param arg
1084    * @return return the argument following the given arg if arg was in list.
1085    */
1086   public String getValue(String arg)
1087   {
1088     return getValue(arg, false);
1089   }
1090
1091   public String getValue(String arg, boolean utf8decode)
1092   {
1093     int index = vargs.indexOf(arg);
1094     String dc = null, ret = null;
1095     if (index != -1)
1096     {
1097       ret = vargs.elementAt(index + 1).toString();
1098       vargs.removeElementAt(index);
1099       vargs.removeElementAt(index);
1100       if (utf8decode && ret != null)
1101       {
1102         try
1103         {
1104           dc = URLDecoder.decode(ret, "UTF-8");
1105           ret = dc;
1106         } catch (Exception e)
1107         {
1108           // TODO: log failure to decode
1109         }
1110       }
1111     }
1112     return ret;
1113   }
1114
1115   /**
1116    * check for and remove first occurence of arg in arglist.
1117    * 
1118    * @param arg
1119    * @return true if arg was present in argslist.
1120    */
1121   public boolean contains(String arg)
1122   {
1123     if (vargs.contains(arg))
1124     {
1125       vargs.removeElement(arg);
1126       return true;
1127     }
1128     else
1129     {
1130       return false;
1131     }
1132   }
1133
1134   public String nextValue()
1135   {
1136     return vargs.remove(0).toString();
1137   }
1138
1139   public int getSize()
1140   {
1141     return vargs.size();
1142   }
1143
1144 }
1145
1146 /**
1147  * keep track of feature fetching tasks.
1148  * 
1149  * @author JimP
1150  * 
1151  */
1152 class FeatureFetcher
1153 {
1154   /*
1155    * TODO: generalise to track all jalview events to orchestrate batch
1156    * processing events.
1157    */
1158
1159   private int queued = 0;
1160
1161   private int running = 0;
1162
1163   public FeatureFetcher()
1164   {
1165
1166   }
1167
1168   public void addFetcher(final AlignFrame af, final Vector dasSources)
1169   {
1170     final long id = System.currentTimeMillis();
1171     queued++;
1172     final FeatureFetcher us = this;
1173     new Thread(new Runnable()
1174     {
1175
1176       public void run()
1177       {
1178         synchronized (us)
1179         {
1180           queued--;
1181           running++;
1182         }
1183
1184         af.setProgressBar(MessageManager.getString("status.das_features_being_retrived"), id);
1185         af.featureSettings_actionPerformed(null);
1186         af.featureSettings.fetchDasFeatures(dasSources, true);
1187         af.setProgressBar(null, id);
1188         synchronized (us)
1189         {
1190           running--;
1191         }
1192       }
1193     }).start();
1194   }
1195
1196   public synchronized boolean allFinished()
1197   {
1198     return queued == 0 && running == 0;
1199   }
1200
1201 }