JAL-2074 disable security manager at start up re: http://lopica.sourceforge.net/faq...
[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       @Override
72       public PermissionCollection getPermissions(CodeSource codesource)
73       {
74         Permissions perms = new Permissions();
75         perms.add(new AllPermission());
76         return (perms);
77       }
78
79       @Override
80       public void refresh()
81       {
82       }
83     });
84   }
85
86   /**
87    * main class for Jalview application
88    * 
89    * @param args
90    *          open <em>filename</em>
91    */
92   public static void main(String[] args)
93   {
94     System.setSecurityManager(null);
95     System.out.println("Java version: "
96             + System.getProperty("java.version"));
97     System.out.println(System.getProperty("os.arch") + " "
98             + System.getProperty("os.name") + " "
99             + System.getProperty("os.version"));
100
101     ArgsParser aparser = new ArgsParser(args);
102     boolean headless = false;
103
104     if (aparser.contains("help") || aparser.contains("h"))
105     {
106       showUsage();
107       System.exit(0);
108     }
109     if (aparser.contains("nodisplay") || aparser.contains("nogui")
110             || aparser.contains("headless"))
111     {
112       System.setProperty("java.awt.headless", "true");
113       headless = true;
114     }
115     String usrPropsFile = aparser.getValue("props");
116     Cache.loadProperties(usrPropsFile); // must do this before
117     if (usrPropsFile != null)
118     {
119       System.out.println("CMD [-props " + usrPropsFile
120               + "] executed successfully!");
121     }
122
123     // anything else!
124
125     final String jabawsUrl = aparser.getValue("jabaws");
126     if (jabawsUrl != null)
127     {
128       try
129       {
130         Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
131         System.out.println("CMD [-jabaws " + jabawsUrl
132                 + "] executed successfully!");
133       } catch (MalformedURLException e)
134       {
135         System.err.println("Invalid jabaws parameter: " + jabawsUrl
136                 + " ignored");
137       }
138     }
139
140     String defs = aparser.getValue("setprop");
141     while (defs != null)
142     {
143       int p = defs.indexOf('=');
144       if (p == -1)
145       {
146         System.err.println("Ignoring invalid setprop argument : " + defs);
147       }
148       else
149       {
150         System.out.println("Executing setprop argument: " + defs);
151         // DISABLED FOR SECURITY REASONS
152         // TODO: add a property to allow properties to be overriden by cli args
153         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
154       }
155       defs = aparser.getValue("setprop");
156     }
157     if (System.getProperty("java.awt.headless") != null
158             && System.getProperty("java.awt.headless").equals("true"))
159     {
160       headless = true;
161     }
162     System.setProperty("http.agent",
163             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
164     try
165     {
166       Cache.initLogger();
167     } catch (java.lang.NoClassDefFoundError error)
168     {
169       error.printStackTrace();
170       System.out
171               .println("\nEssential logging libraries not found."
172                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
173       System.exit(0);
174     }
175
176     Desktop desktop = null;
177
178     try
179     {
180       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
181     } catch (Exception ex)
182     {
183     }
184     if (new Platform().isAMac())
185     {
186       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
187               "Jalview");
188       System.setProperty("apple.laf.useScreenMenuBar", "true");
189       try
190       {
191         UIManager.setLookAndFeel(ch.randelshofer.quaqua.QuaquaManager
192                 .getLookAndFeel());
193       } catch (UnsupportedLookAndFeelException e)
194       {
195         // TODO Auto-generated catch block
196         e.printStackTrace();
197       }
198     }
199
200     if (!headless)
201     {
202       desktop = new Desktop();
203       desktop.setInBatchMode(true); // indicate we are starting up
204       desktop.setVisible(true);
205       desktop.startServiceDiscovery();
206       if (!aparser.contains("nousagestats"))
207       {
208         startUsageStats(desktop);
209       }
210       else
211       {
212         System.err.println("CMD [-nousagestats] executed successfully!");
213       }
214
215       if (!aparser.contains("noquestionnaire"))
216       {
217         String url = aparser.getValue("questionnaire");
218         if (url != null)
219         {
220           // Start the desktop questionnaire prompter with the specified
221           // questionnaire
222           Cache.log.debug("Starting questionnaire url at " + url);
223           desktop.checkForQuestionnaire(url);
224           System.out.println("CMD questionnaire[-" + url
225                   + "] executed successfully!");
226         }
227         else
228         {
229           if (Cache.getProperty("NOQUESTIONNAIRES") == null)
230           {
231             // Start the desktop questionnaire prompter with the specified
232             // questionnaire
233             // String defurl =
234             // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
235             // //
236             String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
237             Cache.log.debug("Starting questionnaire with default url: "
238                     + defurl);
239             desktop.checkForQuestionnaire(defurl);
240
241           }
242         }
243       }
244       else
245       {
246         System.err.println("CMD [-noquestionnaire] executed successfully!");
247       }
248       desktop.checkForNews();
249     }
250
251     if (!isHeadlessMode())
252     {
253       BioJsHTMLOutput.updateBioJS();
254     }
255
256     String file = null, protocol = null, format = null, data = null;
257     jalview.io.FileLoader fileLoader = new jalview.io.FileLoader(!headless);
258     Vector getFeatures = null; // vector of das source nicknames to fetch
259     // features from
260     // loading is done.
261     String groovyscript = null; // script to execute after all loading is
262     // completed one way or another
263     // extract groovy argument and execute if necessary
264     groovyscript = aparser.getValue("groovy", true);
265     file = aparser.getValue("open", true);
266
267     if (file == null && desktop == null)
268     {
269       System.out.println("No files to open!");
270       System.exit(1);
271     }
272     String vamsasImport = aparser.getValue("vdoc"), vamsasSession = aparser
273             .getValue("vsess");
274     if (vamsasImport != null || vamsasSession != null)
275     {
276       if (desktop == null || headless)
277       {
278         System.out
279                 .println("Headless vamsas sessions not yet supported. Sorry.");
280         System.exit(1);
281       }
282       // if we have a file, start a new session and import it.
283       boolean inSession = false;
284       if (vamsasImport != null)
285       {
286         try
287         {
288           String viprotocol = jalview.io.AppletFormatAdapter
289                   .checkProtocol(vamsasImport);
290           if (viprotocol == jalview.io.FormatAdapter.FILE)
291           {
292             inSession = desktop.vamsasImport(new File(vamsasImport));
293           }
294           else if (viprotocol == jalview.io.FormatAdapter.URL)
295           {
296             inSession = desktop.vamsasImport(new URL(vamsasImport));
297           }
298
299         } catch (Exception e)
300         {
301           System.err.println("Exeption when importing " + vamsasImport
302                   + " as a vamsas document.");
303           e.printStackTrace();
304         }
305         if (!inSession)
306         {
307           System.err.println("Failed to import " + vamsasImport
308                   + " as a vamsas document.");
309         }
310         else
311         {
312           System.out.println("Imported Successfully into new session "
313                   + desktop.getVamsasApplication().getCurrentSession());
314         }
315       }
316       if (vamsasSession != null)
317       {
318         if (vamsasImport != null)
319         {
320           // close the newly imported session and import the Jalview specific
321           // remnants into the new session later on.
322           desktop.vamsasStop_actionPerformed(null);
323         }
324         // now join the new session
325         try
326         {
327           if (desktop.joinVamsasSession(vamsasSession))
328           {
329             System.out.println("Successfully joined vamsas session "
330                     + vamsasSession);
331           }
332           else
333           {
334             System.err.println("WARNING: Failed to join vamsas session "
335                     + vamsasSession);
336           }
337         } catch (Exception e)
338         {
339           System.err.println("ERROR: Failed to join vamsas session "
340                   + vamsasSession);
341           e.printStackTrace();
342         }
343         if (vamsasImport != null)
344         {
345           // the Jalview specific remnants can now be imported into the new
346           // session at the user's leisure.
347           Cache.log
348                   .info("Skipping Push for import of data into existing vamsas session."); // TODO:
349           // enable
350           // this
351           // when
352           // debugged
353           // desktop.getVamsasApplication().push_update();
354         }
355       }
356     }
357     long progress = -1;
358     // Finally, deal with the remaining input data.
359     if (file != null)
360     {
361       if (!headless)
362       {
363         desktop.setProgressBar(MessageManager
364                 .getString("status.processing_commandline_args"),
365                 progress = System.currentTimeMillis());
366       }
367       System.out.println("CMD [-open " + file + "] executed successfully!");
368
369       if (!file.startsWith("http://"))
370       {
371         if (!(new java.io.File(file)).exists())
372         {
373           System.out.println("Can't find " + file);
374           if (headless)
375           {
376             System.exit(1);
377           }
378         }
379       }
380
381       protocol = jalview.io.AppletFormatAdapter.checkProtocol(file);
382
383       format = new jalview.io.IdentifyFile().identify(file, protocol);
384
385       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
386               format);
387       if (af == null)
388       {
389         System.out.println("error");
390       }
391       else
392       {
393         Desktop.setCurrentAlignFrame(af);
394         data = aparser.getValue("colour", true);
395         if (data != null)
396         {
397           data.replaceAll("%20", " ");
398
399           jalview.schemes.ColourSchemeI cs = jalview.schemes.ColourSchemeProperty
400                   .getColour(af.getViewport().getAlignment(), data);
401
402           if (cs == null)
403           {
404             jalview.schemes.UserColourScheme ucs = new jalview.schemes.UserColourScheme(
405                     "white");
406             ucs.parseAppletParameter(data);
407             cs = ucs;
408           }
409           else
410           {
411             System.out.println("CMD [-color " + data
412                     + "] executed successfully!");
413           }
414           af.changeColour(cs);
415         }
416
417         // Must maintain ability to use the groups flag
418         data = aparser.getValue("groups", true);
419         if (data != null)
420         {
421           af.parseFeaturesFile(data,
422                   jalview.io.AppletFormatAdapter.checkProtocol(data));
423           // System.out.println("Added " + data);
424           System.out.println("CMD groups[-" + data
425                   + "]  executed successfully!");
426         }
427         data = aparser.getValue("features", true);
428         if (data != null)
429         {
430           af.parseFeaturesFile(data,
431                   jalview.io.AppletFormatAdapter.checkProtocol(data));
432           // System.out.println("Added " + data);
433           System.out.println("CMD [-features " + data
434                   + "]  executed successfully!");
435         }
436
437         data = aparser.getValue("annotations", true);
438         if (data != null)
439         {
440           af.loadJalviewDataFile(data, null, null, null);
441           // System.out.println("Added " + data);
442           System.out.println("CMD [-annotations " + data
443                   + "] executed successfully!");
444         }
445         // set or clear the sortbytree flag.
446         if (aparser.contains("sortbytree"))
447         {
448           af.getViewport().setSortByTree(true);
449           if (af.getViewport().getSortByTree())
450           {
451             System.out.println("CMD [-sortbytree] executed successfully!");
452           }
453         }
454         if (aparser.contains("no-annotation"))
455         {
456           af.getViewport().setShowAnnotation(false);
457           if (!af.getViewport().isShowAnnotation())
458           {
459             System.out.println("CMD no-annotation executed successfully!");
460           }
461         }
462         if (aparser.contains("nosortbytree"))
463         {
464           af.getViewport().setSortByTree(false);
465           if (!af.getViewport().getSortByTree())
466           {
467             System.out
468                     .println("CMD [-nosortbytree] executed successfully!");
469           }
470         }
471         data = aparser.getValue("tree", true);
472         if (data != null)
473         {
474           jalview.io.NewickFile fin = null;
475           try
476           {
477             System.out.println("CMD [-tree " + data
478                     + "] executed successfully!");
479             fin = new jalview.io.NewickFile(data,
480                     jalview.io.AppletFormatAdapter.checkProtocol(data));
481             if (fin != null)
482             {
483               af.getViewport().setCurrentTree(
484                       af.ShowNewickTree(fin, data).getTree());
485             }
486           } catch (IOException ex)
487           {
488             System.err.println("Couldn't add tree " + data);
489             ex.printStackTrace(System.err);
490           }
491         }
492         // TODO - load PDB structure(s) to alignment JAL-629
493         // (associate with identical sequence in alignment, or a specified
494         // sequence)
495
496         getFeatures = checkDasArguments(aparser);
497         if (af != null && getFeatures != null)
498         {
499           FeatureFetcher ff = startFeatureFetching(getFeatures);
500           if (ff != null)
501           {
502             while (!ff.allFinished() || af.operationInProgress())
503             {
504               // wait around until fetching is finished.
505               try
506               {
507                 Thread.sleep(100);
508               } catch (Exception e)
509               {
510
511               }
512             }
513           }
514           getFeatures = null; // have retrieved features - forget them now.
515         }
516         if (groovyscript != null)
517         {
518           // Execute the groovy script after we've done all the rendering stuff
519           // and before any images or figures are generated.
520           if (jalview.bin.Cache.groovyJarsPresent())
521           {
522             System.out.println("Executing script " + groovyscript);
523             executeGroovyScript(groovyscript, new Object[] { 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[] { desktop,
659             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               @Override
736               public void run()
737               {
738                 Cache.log
739                         .debug("Initialising googletracker for usage stats.");
740                 Cache.initGoogleTracker();
741                 Cache.log.debug("Tracking enabled.");
742               }
743             }, new Runnable()
744             {
745               @Override
746               public void run()
747               {
748                 Cache.log.debug("Not enabling Google Tracking.");
749               }
750             }, null, true);
751     desktop.addDialogThread(prompter);
752   }
753
754   /**
755    * Locate the given string as a file and pass it to the groovy interpreter.
756    * 
757    * @param groovyscript
758    *          the script to execute
759    * @param jalviewContext
760    *          the Jalview Desktop object passed in to the groovy binding as the
761    *          'Jalview' object.
762    */
763   private static void executeGroovyScript(String groovyscript,
764           Object[] jalviewContext)
765   {
766     if (jalviewContext == null)
767     {
768       System.err
769               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
770     }
771     /**
772      * for scripts contained in files
773      */
774     File tfile = null;
775     /**
776      * script's URI
777      */
778     URL sfile = null;
779     if (groovyscript.trim().equals("STDIN"))
780     {
781       // read from stdin into a tempfile and execute it
782       try
783       {
784         tfile = File.createTempFile("jalview", "groovy");
785         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
786                 new FileOutputStream(tfile)));
787         BufferedReader br = new BufferedReader(
788                 new java.io.InputStreamReader(System.in));
789         String line = null;
790         while ((line = br.readLine()) != null)
791         {
792           outfile.write(line + "\n");
793         }
794         br.close();
795         outfile.flush();
796         outfile.close();
797
798       } catch (Exception ex)
799       {
800         System.err.println("Failed to read from STDIN into tempfile "
801                 + ((tfile == null) ? "(tempfile wasn't created)" : tfile
802                         .toString()));
803         ex.printStackTrace();
804         return;
805       }
806       try
807       {
808         sfile = tfile.toURI().toURL();
809       } catch (Exception x)
810       {
811         System.err
812                 .println("Unexpected Malformed URL Exception for temporary file created from STDIN: "
813                         + tfile.toURI());
814         x.printStackTrace();
815         return;
816       }
817     }
818     else
819     {
820       try
821       {
822         sfile = new URI(groovyscript).toURL();
823       } catch (Exception x)
824       {
825         tfile = new File(groovyscript);
826         if (!tfile.exists())
827         {
828           System.err.println("File '" + groovyscript + "' does not exist.");
829           return;
830         }
831         if (!tfile.canRead())
832         {
833           System.err.println("File '" + groovyscript + "' cannot be read.");
834           return;
835         }
836         if (tfile.length() < 1)
837         {
838           System.err.println("File '" + groovyscript + "' is empty.");
839           return;
840         }
841         try
842         {
843           sfile = tfile.getAbsoluteFile().toURI().toURL();
844         } catch (Exception ex)
845         {
846           System.err.println("Failed to create a file URL for "
847                   + tfile.getAbsoluteFile());
848           return;
849         }
850       }
851     }
852     boolean success = false;
853     try
854     {
855       /*
856        * The following code performs the GroovyScriptEngine invocation using
857        * reflection, and is equivalent to this fragment from the embedding
858        * groovy documentation on the groovy site: <code> import
859        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
860        * 
861        * String[] roots = new String[] { "/my/groovy/script/path" };
862        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
863        * = new Binding(); binding.setVariable("input", "world");
864        * gse.run("hello.groovy", binding); </code>
865        */
866       Class<?>[] bspec;
867       Object[] binding;
868       int blen = ((jalviewContext[0] == null) ? 0 : 1)
869               + ((jalviewContext[1] == null) ? 0 : 1);
870       String cnames[] = new String[] { "Jalview", "currentAlFrame" };
871       bspec = new Class[blen * 2];
872       binding = new Object[blen * 2];
873       blen = 0;
874       ClassLoader cl = null;
875       Map<String, Object> vbinding = new HashMap<String, Object>();
876       for (int jc = 0; jc < jalviewContext.length; jc++)
877       {
878         if (jalviewContext[jc] != null)
879         {
880           if (cl == null)
881           {
882             cl = jalviewContext[jc].getClass().getClassLoader();
883           }
884           bspec[blen * 2] = String.class;
885           bspec[blen * 2 + 1] = Object.class;
886           binding[blen * 2] = cnames[jc];
887           binding[blen * 2 + 1] = jalviewContext[jc];
888           vbinding.put(cnames[jc], jalviewContext[jc]);
889           blen++;
890         }
891       }
892       Class<?> gbindingc = cl.loadClass("groovy.lang.Binding");
893       Constructor<?> gbcons;
894       Object gbinding;
895       try
896       {
897         gbcons = gbindingc.getConstructor(Map.class);
898         gbinding = gbcons.newInstance(vbinding);
899       } catch (NoSuchMethodException x)
900       {
901         // old style binding config - using series of string/object values to
902         // setVariable.
903         gbcons = gbindingc.getConstructor();
904         gbinding = gbcons.newInstance();
905         java.lang.reflect.Method setvar = gbindingc.getMethod(
906                 "setVariable", bspec);
907         setvar.invoke(gbinding, binding);
908       }
909
910       Class<?> gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
911       Constructor<?> gseccons = gsec
912               .getConstructor(new Class[] { URL[].class }); // String[].class
913                                                             // });
914       Object gse = gseccons
915               .newInstance(new Object[] { new URL[] { sfile } }); // .toString()
916                                                                   // } });
917       java.lang.reflect.Method run = gsec.getMethod("run", new Class[] {
918           String.class, gbindingc });
919       run.invoke(gse, new Object[] { sfile.toString(), gbinding });
920       success = true;
921     } catch (Exception e)
922     {
923       System.err.println("Exception Whilst trying to execute file " + sfile
924               + " as a groovy script.");
925       e.printStackTrace(System.err);
926
927     }
928     if (success && groovyscript.equals("STDIN"))
929     {
930       // delete temp file that we made - but only if it was successfully
931       // executed
932       tfile.delete();
933     }
934   }
935
936   /**
937    * Check commandline for any das server definitions or any fetchfrom switches
938    * 
939    * @return vector of DAS source nicknames to retrieve from
940    */
941   private static Vector checkDasArguments(ArgsParser aparser)
942   {
943     Vector source = null;
944     String data;
945     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
946     while ((data = aparser.getValue("dasserver", true)) != null)
947     {
948       String nickname = null;
949       String url = null;
950       boolean seq = false, feat = true;
951       int pos = data.indexOf('=');
952       // determine capabilities
953       if (pos > 0)
954       {
955         nickname = data.substring(0, pos);
956       }
957       url = data.substring(pos + 1);
958       if (url != null
959               && (url.startsWith("http:") || url
960                       .startsWith("sequence:http:")))
961       {
962         if (nickname == null)
963         {
964           nickname = url;
965         }
966         if (locsources == null)
967         {
968           locsources = "";
969         }
970         else
971         {
972           locsources += "\t";
973         }
974         locsources = locsources + nickname + "|" + url;
975         System.err
976                 .println("NOTE! dasserver parameter not yet really supported (got args of "
977                         + nickname + "|" + url);
978         if (source == null)
979         {
980           source = new Vector();
981         }
982         source.addElement(nickname);
983       }
984       System.out.println("CMD [-dasserver " + data
985               + "] executed successfully!");
986     } // loop until no more server entries are found.
987     if (locsources != null && locsources.indexOf('|') > -1)
988     {
989       Cache.log.debug("Setting local source list in properties file to:\n"
990               + locsources);
991       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
992     }
993     while ((data = aparser.getValue("fetchfrom", true)) != null)
994     {
995       System.out.println("adding source '" + data + "'");
996       if (source == null)
997       {
998         source = new Vector();
999       }
1000       source.addElement(data);
1001     }
1002     return source;
1003   }
1004
1005   /**
1006    * start a feature fetcher for every alignment frame
1007    * 
1008    * @param dasSources
1009    */
1010   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
1011   {
1012     FeatureFetcher ff = new FeatureFetcher();
1013     AlignFrame afs[] = Desktop.getAlignFrames();
1014     if (afs == null || afs.length == 0)
1015     {
1016       return null;
1017     }
1018     for (int i = 0; i < afs.length; i++)
1019     {
1020       ff.addFetcher(afs[i], dasSources);
1021     }
1022     return ff;
1023   }
1024
1025   public static boolean isHeadlessMode()
1026   {
1027     String isheadless = System.getProperty("java.awt.headless");
1028     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1029     {
1030       return true;
1031     }
1032     return false;
1033   }
1034 }
1035
1036 /**
1037  * Notes: this argParser does not distinguish between parameter switches,
1038  * parameter values and argument text. If an argument happens to be identical to
1039  * a parameter, it will be taken as such (even though it didn't have a '-'
1040  * prefixing it).
1041  * 
1042  * @author Andrew Waterhouse and JBP documented.
1043  * 
1044  */
1045
1046 class rnabuttonlistener implements ActionListener
1047 {
1048   @Override
1049   public void actionPerformed(ActionEvent arg0)
1050   {
1051     System.out.println("Good idea ! ");
1052
1053   }
1054 }
1055
1056 class pbuttonlistener implements ActionListener
1057 {
1058   @Override
1059   public void actionPerformed(ActionEvent arg0)
1060   {
1061
1062   }
1063 }
1064
1065 class ArgsParser
1066 {
1067   Vector vargs = null;
1068
1069   public ArgsParser(String[] args)
1070   {
1071     vargs = new Vector();
1072     for (int i = 0; i < args.length; i++)
1073     {
1074       String arg = args[i].trim();
1075       if (arg.charAt(0) == '-')
1076       {
1077         arg = arg.substring(1);
1078       }
1079       vargs.addElement(arg);
1080     }
1081   }
1082
1083   /**
1084    * check for and remove first occurence of arg+parameter in arglist.
1085    * 
1086    * @param arg
1087    * @return return the argument following the given arg if arg was in list.
1088    */
1089   public String getValue(String arg)
1090   {
1091     return getValue(arg, false);
1092   }
1093
1094   public String getValue(String arg, boolean utf8decode)
1095   {
1096     int index = vargs.indexOf(arg);
1097     String dc = null, ret = null;
1098     if (index != -1)
1099     {
1100       ret = vargs.elementAt(index + 1).toString();
1101       vargs.removeElementAt(index);
1102       vargs.removeElementAt(index);
1103       if (utf8decode && ret != null)
1104       {
1105         try
1106         {
1107           dc = URLDecoder.decode(ret, "UTF-8");
1108           ret = dc;
1109         } catch (Exception e)
1110         {
1111           // TODO: log failure to decode
1112         }
1113       }
1114     }
1115     return ret;
1116   }
1117
1118   /**
1119    * check for and remove first occurence of arg in arglist.
1120    * 
1121    * @param arg
1122    * @return true if arg was present in argslist.
1123    */
1124   public boolean contains(String arg)
1125   {
1126     if (vargs.contains(arg))
1127     {
1128       vargs.removeElement(arg);
1129       return true;
1130     }
1131     else
1132     {
1133       return false;
1134     }
1135   }
1136
1137   public String nextValue()
1138   {
1139     return vargs.remove(0).toString();
1140   }
1141
1142   public int getSize()
1143   {
1144     return vargs.size();
1145   }
1146
1147 }
1148
1149 /**
1150  * keep track of feature fetching tasks.
1151  * 
1152  * @author JimP
1153  * 
1154  */
1155 class FeatureFetcher
1156 {
1157   /*
1158    * TODO: generalise to track all jalview events to orchestrate batch
1159    * processing events.
1160    */
1161
1162   private int queued = 0;
1163
1164   private int running = 0;
1165
1166   public FeatureFetcher()
1167   {
1168
1169   }
1170
1171   public void addFetcher(final AlignFrame af, final Vector dasSources)
1172   {
1173     final long id = System.currentTimeMillis();
1174     queued++;
1175     final FeatureFetcher us = this;
1176     new Thread(new Runnable()
1177     {
1178
1179       @Override
1180       public void run()
1181       {
1182         synchronized (us)
1183         {
1184           queued--;
1185           running++;
1186         }
1187
1188         af.setProgressBar(MessageManager
1189                 .getString("status.das_features_being_retrived"), id);
1190         af.featureSettings_actionPerformed(null);
1191         af.featureSettings.fetchDasFeatures(dasSources, true);
1192         af.setProgressBar(null, id);
1193         synchronized (us)
1194         {
1195           running--;
1196         }
1197       }
1198     }).start();
1199   }
1200
1201   public synchronized boolean allFinished()
1202   {
1203     return queued == 0 && running == 0;
1204   }
1205
1206 }