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