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