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