Jalview 2.6 source licence
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
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.util.Platform;
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     if (new Platform().isAMac())
83     {
84         System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Jalview");
85         System.setProperty("apple.laf.useScreenMenuBar", "true");
86     }
87
88     ArgsParser aparser = new ArgsParser(args);
89     boolean headless = false;
90
91     if (aparser.contains("help") || aparser.contains("h"))
92     {
93       System.out
94               .println("Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
95                       + "-nodisplay\tRun Jalview without User Interface.\n"
96                       + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
97                       + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
98                       + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
99                       + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
100                       + "-features FILE\tUse the given file to mark features on the alignment.\n"
101                       + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
102                       + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
103                       + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
104                       + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
105                       + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
106                       + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
107                       + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
108                       + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
109                       + "-png FILE\tCreate PNG image FILE from alignment.\n"
110                       + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
111                       + "-eps FILE\tCreate EPS file FILE from alignment.\n"
112                       + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
113                       + "-noquestionnaire\tTurn off questionnaire check.\n"
114                       + "-nousagestats\tTurn off google analytics tracking for this session.\n"
115                       + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
116                       // +
117                       // "-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)"
118                       + "-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"
119                       + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
120                       + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
121                       + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
122                       // +
123                       // "-vdoc vamsas-document\tImport vamsas document into new session or join existing session with same URN\n"
124                       // + "-vses vamsas-session\tJoin session with given URN\n"
125                       + "-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"
126                       + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
127       System.exit(0);
128     }
129     Cache.loadProperties(aparser.getValue("props")); // must do this before
130     // anything else!
131     String defs = aparser.getValue("setprop");
132     while (defs != null)
133     {
134       int p = defs.indexOf('=');
135       if (p == -1)
136       {
137         System.err.println("Ignoring invalid setprop argument : " + defs);
138       }
139       else
140       {
141         System.out.println("Executing setprop argument: " + defs);
142         // DISABLED FOR SECURITY REASONS
143         // TODO: add a property to allow properties to be overriden by cli args
144         // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
145       }
146       defs = aparser.getValue("setprop");
147     }
148     if (aparser.contains("nodisplay"))
149     {
150       System.setProperty("java.awt.headless", "true");
151     }
152     if (System.getProperty("java.awt.headless") != null
153             && System.getProperty("java.awt.headless").equals("true"))
154     {
155       headless = true;
156     }
157
158     try
159     {
160       Cache.initLogger();
161     } catch (java.lang.NoClassDefFoundError error)
162     {
163       error.printStackTrace();
164       System.out
165               .println("\nEssential logging libraries not found."
166                       + "\nUse: java -Djava.ext.dirs=$PATH_TO_LIB$ jalview.bin.Jalview");
167       System.exit(0);
168     }
169
170     Desktop desktop = null;
171
172     try
173     {
174       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
175     } catch (Exception ex)
176     {
177     }
178
179     if (!headless)
180     {
181       desktop = new Desktop();
182       desktop.setInBatchMode(true); // indicate we are starting up
183       desktop.setVisible(true);
184       desktop.startServiceDiscovery();
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(s) to alignment JAL-629
416       // (associate with identical sequence in alignment, or a specified
417       // sequence)
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     // Once all other stuff is done, execute any groovy scripts (in order)
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     // and finally, turn off batch mode indicator - if the desktop still exists
556     if (desktop!=null)
557     {
558       desktop.setInBatchMode(false);
559     }
560   }
561
562   private static void startUsageStats(final Desktop desktop)
563   {
564     /**
565      * start a User Config prompt asking if we can log usage statistics.
566      */
567     jalview.gui.PromptUserConfig prompter = new jalview.gui.PromptUserConfig(
568             desktop.desktop,
569             "USAGESTATS",
570             "Jalview Usage Statistics",
571             "Do you want to help make Jalview better by enabling "
572                     + "the collection of usage statistics with Google Analytics ?"
573                     + "\n\n(you can enable or disable usage tracking in the preferences)",
574             new Runnable()
575             {
576               public void run()
577               {
578                 Cache.log
579                         .info("Initialising googletracker for usage stats.");
580                 Cache.initGoogleTracker();
581                 Cache.log.debug("Tracking enabled.");
582               }
583             }, new Runnable()
584             {
585               public void run()
586               {
587                 Cache.log.info("Not enabling Google Tracking.");
588               }
589             }, null, true);
590     SwingUtilities.invokeLater(prompter);
591   }
592
593   /**
594    * Locate the given string as a file and pass it to the groovy interpreter.
595    * 
596    * @param groovyscript
597    *          the script to execute
598    * @param jalviewContext
599    *          the Jalview Desktop object passed in to the groovy binding as the
600    *          'Jalview' object.
601    */
602   private static void executeGroovyScript(String groovyscript,
603           Object jalviewContext)
604   {
605     if (jalviewContext == null)
606     {
607       System.err
608               .println("Sorry. Groovy support is currently only available when running with the Jalview GUI enabled.");
609     }
610     File sfile = null;
611     if (groovyscript.trim().equals("STDIN"))
612     {
613       // read from stdin into a tempfile and execute it
614       try
615       {
616         sfile = File.createTempFile("jalview", "groovy");
617         PrintWriter outfile = new PrintWriter(new OutputStreamWriter(
618                 new FileOutputStream(sfile)));
619         BufferedReader br = new BufferedReader(
620                 new java.io.InputStreamReader(System.in));
621         String line = null;
622         while ((line = br.readLine()) != null)
623         {
624           outfile.write(line + "\n");
625         }
626         br.close();
627         outfile.flush();
628         outfile.close();
629
630       } catch (Exception ex)
631       {
632         System.err.println("Failed to read from STDIN into tempfile "
633                 + ((sfile == null) ? "(tempfile wasn't created)" : sfile
634                         .toString()));
635         ex.printStackTrace();
636         return;
637       }
638     }
639     else
640     {
641       sfile = new File(groovyscript);
642     }
643     if (!sfile.exists())
644     {
645       System.err.println("File '" + groovyscript + "' does not exist.");
646       return;
647     }
648     if (!sfile.canRead())
649     {
650       System.err.println("File '" + groovyscript + "' cannot be read.");
651       return;
652     }
653     if (sfile.length() < 1)
654     {
655       System.err.println("File '" + groovyscript + "' is empty.");
656       return;
657     }
658     boolean success = false;
659     try
660     {
661       /*
662        * The following code performs the GroovyScriptEngine invocation using
663        * reflection, and is equivalent to this fragment from the embedding
664        * groovy documentation on the groovy site: <code> import
665        * groovy.lang.Binding; import groovy.util.GroovyScriptEngine;
666        * 
667        * String[] roots = new String[] { "/my/groovy/script/path" };
668        * GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding
669        * = new Binding(); binding.setVariable("input", "world");
670        * gse.run("hello.groovy", binding); </code>
671        */
672       ClassLoader cl = jalviewContext.getClass().getClassLoader();
673       Class gbindingc = cl.loadClass("groovy.lang.Binding");
674       Constructor gbcons = gbindingc.getConstructor(null);
675       Object gbinding = gbcons.newInstance(null);
676       java.lang.reflect.Method setvar = gbindingc.getMethod("setVariable",
677               new Class[]
678               { String.class, Object.class });
679       setvar.invoke(gbinding, new Object[]
680       { "Jalview", jalviewContext });
681       Class gsec = cl.loadClass("groovy.util.GroovyScriptEngine");
682       Constructor gseccons = gsec.getConstructor(new Class[]
683       { URL[].class }); // String[].class });
684       Object gse = gseccons.newInstance(new Object[]
685       { new URL[]
686       { sfile.toURL() } }); // .toString() } });
687       java.lang.reflect.Method run = gsec.getMethod("run", new Class[]
688       { String.class, gbindingc });
689       run.invoke(gse, new Object[]
690       { sfile.getName(), gbinding });
691       success = true;
692     } catch (Exception e)
693     {
694       System.err.println("Exception Whilst trying to execute file " + sfile
695               + " as a groovy script.");
696       e.printStackTrace(System.err);
697
698     }
699     if (success && groovyscript.equals("STDIN"))
700     {
701       // delete temp file that we made - but only if it was successfully
702       // executed
703       sfile.delete();
704     }
705   }
706
707   /**
708    * Check commandline for any das server definitions or any fetchfrom switches
709    * 
710    * @return vector of DAS source nicknames to retrieve from
711    */
712   private static Vector checkDasArguments(ArgsParser aparser)
713   {
714     Vector source = null;
715     String data;
716     String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
717     while ((data = aparser.getValue("dasserver", true)) != null)
718     {
719       String nickname = null;
720       String url = null;
721       boolean seq = false, feat = true;
722       int pos = data.indexOf('=');
723       // determine capabilities
724       if (pos > 0)
725       {
726         nickname = data.substring(0, pos);
727       }
728       url = data.substring(pos + 1);
729       if (url != null
730               && (url.startsWith("http:") || url
731                       .startsWith("sequence:http:")))
732       {
733         if (nickname == null)
734         {
735           nickname = url;
736         }
737         if (locsources == null)
738         {
739           locsources = "";
740         }
741         else
742         {
743           locsources += "\t";
744         }
745         locsources = locsources + nickname + "|" + url;
746         System.err
747                 .println("NOTE! dasserver parameter not yet really supported (got args of "
748                         + nickname + "|" + url);
749         if (source == null)
750         {
751           source = new Vector();
752         }
753         source.addElement(nickname);
754       }
755     } // loop until no more server entries are found.
756     if (locsources != null && locsources.indexOf('|') > -1)
757     {
758       Cache.log.debug("Setting local source list in properties file to:\n"
759               + locsources);
760       Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
761     }
762     while ((data = aparser.getValue("fetchfrom", true)) != null)
763     {
764       System.out.println("adding source '" + data + "'");
765       if (source == null)
766       {
767         source = new Vector();
768       }
769       source.addElement(data);
770     }
771     return source;
772   }
773
774   /**
775    * start a feature fetcher for every alignment frame
776    * 
777    * @param dasSources
778    */
779   private static FeatureFetcher startFeatureFetching(final Vector dasSources)
780   {
781     FeatureFetcher ff = new FeatureFetcher();
782     AlignFrame afs[] = Desktop.getAlignframes();
783     if (afs == null || afs.length == 0)
784     {
785       return null;
786     }
787     for (int i = 0; i < afs.length; i++)
788     {
789       ff.addFetcher(afs[i], dasSources);
790     }
791     return ff;
792   }
793
794   private static String checkProtocol(String file)
795   {
796     String protocol = jalview.io.FormatAdapter.FILE;
797
798     if (file.indexOf("http:") > -1 || file.indexOf("file:") > -1)
799     {
800       protocol = jalview.io.FormatAdapter.URL;
801     }
802     return protocol;
803   }
804 }
805
806 /**
807  * Notes: this argParser does not distinguish between parameter switches,
808  * parameter values and argument text. If an argument happens to be identical to
809  * a parameter, it will be taken as such (even though it didn't have a '-'
810  * prefixing it).
811  * 
812  * @author Andrew Waterhouse and JBP documented.
813  * 
814  */
815 class ArgsParser
816 {
817   Vector vargs = null;
818
819   public ArgsParser(String[] args)
820   {
821     vargs = new Vector();
822     for (int i = 0; i < args.length; i++)
823     {
824       String arg = args[i].trim();
825       if (arg.charAt(0) == '-')
826       {
827         arg = arg.substring(1);
828       }
829       vargs.addElement(arg);
830     }
831   }
832
833   /**
834    * check for and remove first occurence of arg+parameter in arglist.
835    * 
836    * @param arg
837    * @return return the argument following the given arg if arg was in list.
838    */
839   public String getValue(String arg)
840   {
841     return getValue(arg, false);
842   }
843
844   public String getValue(String arg, boolean utf8decode)
845   {
846     int index = vargs.indexOf(arg);
847     String dc = null, ret = null;
848     if (index != -1)
849     {
850       ret = vargs.elementAt(index + 1).toString();
851       vargs.removeElementAt(index);
852       vargs.removeElementAt(index);
853       if (utf8decode && ret != null)
854       {
855         try
856         {
857           dc = URLDecoder.decode(ret, "UTF-8");
858           ret = dc;
859         } catch (Exception e)
860         {
861           // TODO: log failure to decode
862         }
863       }
864     }
865     return ret;
866   }
867
868   /**
869    * check for and remove first occurence of arg in arglist.
870    * 
871    * @param arg
872    * @return true if arg was present in argslist.
873    */
874   public boolean contains(String arg)
875   {
876     if (vargs.contains(arg))
877     {
878       vargs.removeElement(arg);
879       return true;
880     }
881     else
882     {
883       return false;
884     }
885   }
886
887   public String nextValue()
888   {
889     return vargs.remove(0).toString();
890   }
891
892   public int getSize()
893   {
894     return vargs.size();
895   }
896
897 }
898
899 /**
900  * keep track of feature fetching tasks.
901  * 
902  * @author JimP
903  * 
904  */
905 class FeatureFetcher
906 {
907   /*
908    * TODO: generalise to track all jalview events to orchestrate batch
909    * processing events.
910    */
911
912   private int queued = 0;
913
914   private int running = 0;
915
916   public FeatureFetcher()
917   {
918
919   }
920
921   public void addFetcher(final AlignFrame af, final Vector dasSources)
922   {
923     final long id = System.currentTimeMillis();
924     queued++;
925     final FeatureFetcher us = this;
926     new Thread(new Runnable()
927     {
928
929       public void run()
930       {
931         synchronized (us)
932         {
933           queued--;
934           running++;
935         }
936
937         af.setProgressBar("DAS features being retrieved...", id);
938         af.featureSettings_actionPerformed(null);
939         af.featureSettings.fetchDasFeatures(dasSources, true);
940         af.setProgressBar(null, id);
941         synchronized (us)
942         {
943           running--;
944         }
945       }
946     }).start();
947   }
948
949   public synchronized boolean allFinished()
950   {
951     return queued == 0 && running == 0;
952   }
953 };