JAL-2694 add maximal set of chain mappings between a PDBEntry and a sequence
[jalview.git] / src / jalview / structure / StructureSelectionManager.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.structure;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.api.StructureSelectionManagerProvider;
25 import jalview.commands.CommandI;
26 import jalview.commands.EditCommand;
27 import jalview.commands.OrderCommand;
28 import jalview.datamodel.AlignedCodonFrame;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.Annotation;
32 import jalview.datamodel.HiddenColumns;
33 import jalview.datamodel.PDBEntry;
34 import jalview.datamodel.SearchResults;
35 import jalview.datamodel.SearchResultsI;
36 import jalview.datamodel.SequenceI;
37 import jalview.ext.jmol.JmolParser;
38 import jalview.gui.IProgressIndicator;
39 import jalview.io.AppletFormatAdapter;
40 import jalview.io.DataSourceType;
41 import jalview.io.StructureFile;
42 import jalview.util.MappingUtils;
43 import jalview.util.MessageManager;
44 import jalview.ws.sifts.SiftsClient;
45 import jalview.ws.sifts.SiftsException;
46 import jalview.ws.sifts.SiftsSettings;
47
48 import java.io.PrintStream;
49 import java.util.ArrayList;
50 import java.util.Arrays;
51 import java.util.Collections;
52 import java.util.Enumeration;
53 import java.util.HashMap;
54 import java.util.IdentityHashMap;
55 import java.util.List;
56 import java.util.Map;
57 import java.util.Vector;
58
59 import MCview.Atom;
60 import MCview.PDBChain;
61 import MCview.PDBfile;
62
63 public class StructureSelectionManager
64 {
65   public final static String NEWLINE = System.lineSeparator();
66
67   static IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> instances;
68
69   private List<StructureMapping> mappings = new ArrayList<StructureMapping>();
70
71   private boolean processSecondaryStructure = false;
72
73   private boolean secStructServices = false;
74
75   private boolean addTempFacAnnot = false;
76
77   private IProgressIndicator progressIndicator;
78
79   private SiftsClient siftsClient = null;
80
81   private long progressSessionId;
82
83   /*
84    * Set of any registered mappings between (dataset) sequences.
85    */
86   private List<AlignedCodonFrame> seqmappings = new ArrayList<AlignedCodonFrame>();
87
88   private List<CommandListener> commandListeners = new ArrayList<CommandListener>();
89
90   private List<SelectionListener> sel_listeners = new ArrayList<SelectionListener>();
91
92   /**
93    * @return true if will try to use external services for processing secondary
94    *         structure
95    */
96   public boolean isSecStructServices()
97   {
98     return secStructServices;
99   }
100
101   /**
102    * control use of external services for processing secondary structure
103    * 
104    * @param secStructServices
105    */
106   public void setSecStructServices(boolean secStructServices)
107   {
108     this.secStructServices = secStructServices;
109   }
110
111   /**
112    * flag controlling addition of any kind of structural annotation
113    * 
114    * @return true if temperature factor annotation will be added
115    */
116   public boolean isAddTempFacAnnot()
117   {
118     return addTempFacAnnot;
119   }
120
121   /**
122    * set flag controlling addition of structural annotation
123    * 
124    * @param addTempFacAnnot
125    */
126   public void setAddTempFacAnnot(boolean addTempFacAnnot)
127   {
128     this.addTempFacAnnot = addTempFacAnnot;
129   }
130
131   /**
132    * 
133    * @return if true, the structure manager will attempt to add secondary
134    *         structure lines for unannotated sequences
135    */
136
137   public boolean isProcessSecondaryStructure()
138   {
139     return processSecondaryStructure;
140   }
141
142   /**
143    * Control whether structure manager will try to annotate mapped sequences
144    * with secondary structure from PDB data.
145    * 
146    * @param enable
147    */
148   public void setProcessSecondaryStructure(boolean enable)
149   {
150     processSecondaryStructure = enable;
151   }
152
153   /**
154    * debug function - write all mappings to stdout
155    */
156   public void reportMapping()
157   {
158     if (mappings.isEmpty())
159     {
160       System.err.println("reportMapping: No PDB/Sequence mappings.");
161     }
162     else
163     {
164       System.err.println(
165               "reportMapping: There are " + mappings.size() + " mappings.");
166       int i = 0;
167       for (StructureMapping sm : mappings)
168       {
169         System.err.println("mapping " + i++ + " : " + sm.pdbfile);
170       }
171     }
172   }
173
174   /**
175    * map between the PDB IDs (or structure identifiers) used by Jalview and the
176    * absolute filenames for PDB data that corresponds to it
177    */
178   Map<String, String> pdbIdFileName = new HashMap<String, String>();
179
180   Map<String, String> pdbFileNameId = new HashMap<String, String>();
181
182   public void registerPDBFile(String idForFile, String absoluteFile)
183   {
184     pdbIdFileName.put(idForFile, absoluteFile);
185     pdbFileNameId.put(absoluteFile, idForFile);
186   }
187
188   public String findIdForPDBFile(String idOrFile)
189   {
190     String id = pdbFileNameId.get(idOrFile);
191     return id;
192   }
193
194   public String findFileForPDBId(String idOrFile)
195   {
196     String id = pdbIdFileName.get(idOrFile);
197     return id;
198   }
199
200   public boolean isPDBFileRegistered(String idOrFile)
201   {
202     return pdbFileNameId.containsKey(idOrFile)
203             || pdbIdFileName.containsKey(idOrFile);
204   }
205
206   private static StructureSelectionManager nullProvider = null;
207
208   public static StructureSelectionManager getStructureSelectionManager(
209           StructureSelectionManagerProvider context)
210   {
211     if (context == null)
212     {
213       if (nullProvider == null)
214       {
215         if (instances != null)
216         {
217           throw new Error(MessageManager.getString(
218                   "error.implementation_error_structure_selection_manager_null"),
219                   new NullPointerException(MessageManager
220                           .getString("exception.ssm_context_is_null")));
221         }
222         else
223         {
224           nullProvider = new StructureSelectionManager();
225         }
226         return nullProvider;
227       }
228     }
229     if (instances == null)
230     {
231       instances = new java.util.IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager>();
232     }
233     StructureSelectionManager instance = instances.get(context);
234     if (instance == null)
235     {
236       if (nullProvider != null)
237       {
238         instance = nullProvider;
239       }
240       else
241       {
242         instance = new StructureSelectionManager();
243       }
244       instances.put(context, instance);
245     }
246     return instance;
247   }
248
249   /**
250    * flag controlling whether SeqMappings are relayed from received sequence
251    * mouse over events to other sequences
252    */
253   boolean relaySeqMappings = true;
254
255   /**
256    * Enable or disable relay of seqMapping events to other sequences. You might
257    * want to do this if there are many sequence mappings and the host computer
258    * is slow
259    * 
260    * @param relay
261    */
262   public void setRelaySeqMappings(boolean relay)
263   {
264     relaySeqMappings = relay;
265   }
266
267   /**
268    * get the state of the relay seqMappings flag.
269    * 
270    * @return true if sequence mouse overs are being relayed to other mapped
271    *         sequences
272    */
273   public boolean isRelaySeqMappingsEnabled()
274   {
275     return relaySeqMappings;
276   }
277
278   Vector listeners = new Vector();
279
280   /**
281    * register a listener for alignment sequence mouseover events
282    * 
283    * @param svl
284    */
285   public void addStructureViewerListener(Object svl)
286   {
287     if (!listeners.contains(svl))
288     {
289       listeners.addElement(svl);
290     }
291   }
292
293   /**
294    * Returns the file name for a mapped PDB id (or null if not mapped).
295    * 
296    * @param pdbid
297    * @return
298    */
299   public String alreadyMappedToFile(String pdbid)
300   {
301     for (StructureMapping sm : mappings)
302     {
303       if (sm.getPdbId().equals(pdbid))
304       {
305         return sm.pdbfile;
306       }
307     }
308     return null;
309   }
310
311   /**
312    * Import structure data and register a structure mapping for broadcasting
313    * colouring, mouseovers and selection events (convenience wrapper).
314    * 
315    * @param sequence
316    *          - one or more sequences to be mapped to pdbFile
317    * @param targetChains
318    *          - optional chain specification for mapping each sequence to pdb
319    *          (may be nill, individual elements may be nill)
320    * @param pdbFile
321    *          - structure data resource
322    * @param protocol
323    *          - how to resolve data from resource
324    * @return null or the structure data parsed as a pdb file
325    */
326   synchronized public StructureFile setMapping(SequenceI[] sequence,
327           String[] targetChains, String pdbFile, DataSourceType protocol)
328   {
329     return setMapping(true, sequence, targetChains, pdbFile, protocol);
330   }
331
332   /**
333    * create sequence structure mappings between each sequence and the given
334    * pdbFile (retrieved via the given protocol).
335    * 
336    * @param forStructureView
337    *          when true, record the mapping for use in mouseOvers
338    * 
339    * @param sequenceArray
340    *          - one or more sequences to be mapped to pdbFile
341    * @param targetChainIds
342    *          - optional chain specification for mapping each sequence to pdb
343    *          (may be nill, individual elements may be nill) - JBPNote: JAL-2693
344    *          - this should be List<List<String>>, empty lists indicate no
345    *          predefined mappings
346    * @param pdbFile
347    *          - structure data resource
348    * @param sourceType
349    *          - how to resolve data from resource
350    * @return null or the structure data parsed as a pdb file
351    */
352   synchronized public StructureFile setMapping(boolean forStructureView,
353           SequenceI[] sequenceArray, String[] targetChainIds,
354           String pdbFile, DataSourceType sourceType)
355   {
356     /*
357      * There will be better ways of doing this in the future, for now we'll use
358      * the tried and tested MCview pdb mapping
359      */
360     boolean parseSecStr = processSecondaryStructure;
361     if (isPDBFileRegistered(pdbFile))
362     {
363       for (SequenceI sq : sequenceArray)
364       {
365         SequenceI ds = sq;
366         while (ds.getDatasetSequence() != null)
367         {
368           ds = ds.getDatasetSequence();
369         }
370         ;
371         if (ds.getAnnotation() != null)
372         {
373           for (AlignmentAnnotation ala : ds.getAnnotation())
374           {
375             // false if any annotation present from this structure
376             // JBPNote this fails for jmol/chimera view because the *file* is
377             // passed, not the structure data ID -
378             if (PDBfile.isCalcIdForFile(ala, findIdForPDBFile(pdbFile)))
379             {
380               parseSecStr = false;
381             }
382           }
383         }
384       }
385     }
386     StructureFile pdb = null;
387     boolean isMapUsingSIFTs = SiftsSettings.isMapWithSifts();
388     try
389     {
390       sourceType = AppletFormatAdapter.checkProtocol(pdbFile);
391       pdb = new JmolParser(pdbFile, sourceType);
392
393       if (pdb.getId() != null && pdb.getId().trim().length() > 0
394               && DataSourceType.FILE == sourceType)
395       {
396         registerPDBFile(pdb.getId().trim(), pdbFile);
397       }
398       // if PDBId is unavailable then skip SIFTS mapping execution path
399       isMapUsingSIFTs = isMapUsingSIFTs && pdb.isPPDBIdAvailable();
400
401     } catch (Exception ex)
402     {
403       ex.printStackTrace();
404       return null;
405     }
406
407     try
408     {
409       if (isMapUsingSIFTs)
410       {
411         siftsClient = new SiftsClient(pdb);
412       }
413     } catch (SiftsException e)
414     {
415       isMapUsingSIFTs = false;
416       e.printStackTrace();
417     }
418
419     String targetChainId;
420     for (int s = 0; s < sequenceArray.length; s++)
421     {
422       boolean infChain = true;
423       final SequenceI seq = sequenceArray[s];
424       SequenceI ds = seq;
425       while (ds.getDatasetSequence() != null)
426       {
427         ds = ds.getDatasetSequence();
428       }
429
430       if (targetChainIds != null && targetChainIds[s] != null)
431       {
432         infChain = false;
433         targetChainId = targetChainIds[s];
434       }
435       else if (seq.getName().indexOf("|") > -1)
436       {
437         targetChainId = seq.getName()
438                 .substring(seq.getName().lastIndexOf("|") + 1);
439         if (targetChainId.length() > 1)
440         {
441           if (targetChainId.trim().length() == 0)
442           {
443             targetChainId = " ";
444           }
445           else
446           {
447             // not a valid chain identifier
448             targetChainId = "";
449           }
450         }
451       }
452       else
453       {
454         targetChainId = "";
455       }
456
457       /*
458        * Attempt pairwise alignment of the sequence with each chain in the PDB,
459        * and remember the highest scoring chain
460        */
461       float max = -10;
462       AlignSeq maxAlignseq = null;
463       String maxChainId = " ";
464       PDBChain maxChain = null;
465       boolean first = true;
466       List<PDBChain> maximalChain = new ArrayList<>();
467       List<AlignSeq> maximalAlignseqs = new ArrayList<>();
468       List<String> maximalChainIds = new ArrayList<>();
469       for (PDBChain chain : pdb.getChains())
470       {
471         if (targetChainId.length() > 0 && !targetChainId.equals(chain.id)
472                 && !infChain)
473         {
474           continue; // don't try to map chains don't match.
475         }
476         // TODO: correctly determine sequence type for mixed na/peptide
477         // structures
478         final String type = chain.isNa ? AlignSeq.DNA : AlignSeq.PEP;
479         AlignSeq as = AlignSeq.doGlobalNWAlignment(seq, chain.sequence,
480                 type);
481         // equivalent to:
482         // AlignSeq as = new AlignSeq(sequence[s], chain.sequence, type);
483         // as.calcScoreMatrix();
484         // as.traceAlignment();
485
486         if (targetChainId.length() > 0 && chain.id.equals(targetChainId))
487         {
488           // Don't care - just pick this chain as the mapping
489           maxChain = chain;
490           max = as.maxscore;
491           maxAlignseq = as;
492           maxChainId = chain.id;
493           // if targetChainId is specified then it is expected to be unique, so
494           // precisely one maximal chain will be added
495           maximalChainIds.add(chain.id);
496           maximalChain.add(chain);
497           maximalAlignseqs.add(as);
498         }
499         else
500         {
501           // select chains with maximal mappings to this sequence
502           if (first || as.maxscore > max)
503           {
504             // clear out old maximal mappings (if any)
505             max = as.maxscore;
506             maximalChain.clear();
507             maxChain = chain;
508             max = as.maxscore;
509             maxAlignseq = as;
510             maxChainId = chain.id;
511             first = false;
512           }
513           if (as.maxscore == max)
514           {
515             maximalChainIds.add(chain.id);
516             maximalChain.add(chain);
517             maximalAlignseqs.add(as);
518           }
519         }
520       }
521       if (maxChain == null)
522       {
523         continue;
524       }
525
526       if (sourceType == DataSourceType.PASTE)
527       {
528         pdbFile = "INLINE" + pdb.getId();
529       }
530
531       List<StructureMapping> seqToStrucMapping = new ArrayList<>();
532       if (isMapUsingSIFTs && seq.isProtein())
533       {
534         setProgressBar(null);
535         setProgressBar(MessageManager
536                 .getString("status.obtaining_mapping_with_sifts"));
537         jalview.datamodel.Mapping sqmpping = maxAlignseq
538                 .getMappingFromS1(false);
539         if (targetChainId != null && !targetChainId.trim().isEmpty())
540         {
541           StructureMapping siftsMapping;
542           try
543           {
544             siftsMapping = getStructureMapping(seq, pdbFile, targetChainId,
545                     pdb, maxChain, sqmpping, maxAlignseq);
546             seqToStrucMapping.add(siftsMapping);
547             maxChain.makeExactMapping(maxAlignseq, seq);
548             maxChain.transferRESNUMFeatures(seq, null);// FIXME: is this
549                                                        // "IEA:SIFTS" ?
550             maxChain.transferResidueAnnotation(siftsMapping, sqmpping);
551             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
552
553           } catch (SiftsException e)
554           {
555             // fall back to NW alignment
556             System.err.println(e.getMessage());
557             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
558                     maximalChainIds, maximalChain, pdb, maximalAlignseqs)
559                             .get(0);
560             seqToStrucMapping.add(nwMapping);
561             maxChain.makeExactMapping(maxAlignseq, seq);
562             maxChain.transferRESNUMFeatures(seq, null); // FIXME: is this
563                                                         // "IEA:Jalview" ?
564             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
565             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
566           }
567         }
568         else
569         {
570           List<StructureMapping> foundSiftsMappings = new ArrayList<>();
571           for (PDBChain chain : pdb.getChains())
572           {
573             try
574             {
575               StructureMapping siftsMapping = getStructureMapping(seq,
576                       pdbFile, chain.id, pdb, chain, sqmpping, maxAlignseq);
577               foundSiftsMappings.add(siftsMapping);
578             } catch (SiftsException e)
579             {
580               System.err.println(e.getMessage());
581             }
582           }
583           if (!foundSiftsMappings.isEmpty())
584           {
585             seqToStrucMapping.addAll(foundSiftsMappings);
586             maxChain.makeExactMapping(maxAlignseq, seq);
587             maxChain.transferRESNUMFeatures(seq, null);// FIXME: is this
588                                                        // "IEA:SIFTS" ?
589             maxChain.transferResidueAnnotation(foundSiftsMappings.get(0),
590                     sqmpping);
591             ds.addPDBId(sqmpping.getTo().getAllPDBEntries().get(0));
592           }
593           else
594           {
595             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
596                     maximalChainIds, maximalChain, pdb, maximalAlignseqs)
597                             .get(0);
598             seqToStrucMapping.add(nwMapping);
599             maxChain.transferRESNUMFeatures(seq, null); // FIXME: is this
600                                                         // "IEA:Jalview" ?
601             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
602             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
603           }
604         }
605       }
606       else
607       {
608         setProgressBar(null);
609         setProgressBar(MessageManager
610                 .getString("status.obtaining_mapping_with_nw_alignment"));
611         List<StructureMapping> nwMapping = getNWMappings(seq, pdbFile,
612                 maximalChainIds, maximalChain, pdb, maximalAlignseqs);
613         seqToStrucMapping.addAll(nwMapping);
614         for (PDBChain mc : maximalChain)
615         {
616           ds.addPDBId(mc.sequence.getAllPDBEntries().get(0));
617         }
618         ;
619
620       }
621
622       if (forStructureView)
623       {
624         mappings.addAll(seqToStrucMapping);
625       }
626     }
627     return pdb;
628   }
629
630   public void addStructureMapping(StructureMapping sm)
631   {
632     mappings.add(sm);
633   }
634
635   /**
636    * retrieve a mapping for seq from SIFTs using associated DBRefEntry for
637    * uniprot or PDB
638    * 
639    * @param seq
640    * @param pdbFile
641    * @param targetChainId
642    * @param pdb
643    * @param maxChain
644    * @param sqmpping
645    * @param maxAlignseq
646    * @return
647    * @throws SiftsException
648    */
649   private StructureMapping getStructureMapping(SequenceI seq,
650           String pdbFile, String targetChainId, StructureFile pdb,
651           PDBChain maxChain, jalview.datamodel.Mapping sqmpping,
652           AlignSeq maxAlignseq) throws SiftsException
653   {
654     StructureMapping curChainMapping = siftsClient
655             .getSiftsStructureMapping(seq, pdbFile, targetChainId);
656     try
657     {
658       PDBChain chain = pdb.findChain(targetChainId);
659       if (chain != null)
660       {
661         chain.transferResidueAnnotation(curChainMapping, sqmpping);
662       }
663     } catch (Exception e)
664     {
665       e.printStackTrace();
666     }
667     return curChainMapping;
668   }
669
670   private List<StructureMapping> getNWMappings(SequenceI seq,
671           String pdbFile,
672           List<String> maximalChainId, List<PDBChain> maximalChain,
673           StructureFile pdb, List<AlignSeq> maximalAlignseq)
674   {
675     List<StructureMapping> nwMappings = new ArrayList();
676     for (int ch = 0; ch < maximalChain.size(); ch++)
677     {
678       String maxChainId = maximalChainId.get(ch);
679       PDBChain maxChain = maximalChain.get(ch);
680       AlignSeq maxAlignseq = maximalAlignseq.get(ch);
681     final StringBuilder mappingDetails = new StringBuilder(128);
682     mappingDetails.append(NEWLINE)
683             .append("Sequence \u27f7 Structure mapping details");
684     mappingDetails.append(NEWLINE);
685     mappingDetails
686             .append("Method: inferred with Needleman & Wunsch alignment");
687     mappingDetails.append(NEWLINE).append("PDB Sequence is :")
688             .append(NEWLINE).append("Sequence = ")
689             .append(maxChain.sequence.getSequenceAsString());
690     mappingDetails.append(NEWLINE).append("No of residues = ")
691             .append(maxChain.residues.size()).append(NEWLINE)
692             .append(NEWLINE);
693     PrintStream ps = new PrintStream(System.out)
694     {
695       @Override
696       public void print(String x)
697       {
698         mappingDetails.append(x);
699       }
700
701       @Override
702       public void println()
703       {
704         mappingDetails.append(NEWLINE);
705       }
706     };
707
708     maxAlignseq.printAlignment(ps);
709
710     mappingDetails.append(NEWLINE).append("PDB start/end ");
711     mappingDetails.append(String.valueOf(maxAlignseq.seq2start))
712             .append(" ");
713     mappingDetails.append(String.valueOf(maxAlignseq.seq2end));
714     mappingDetails.append(NEWLINE).append("SEQ start/end ");
715     mappingDetails
716             .append(String
717                     .valueOf(maxAlignseq.seq1start + (seq.getStart() - 1)))
718             .append(" ");
719     mappingDetails.append(
720             String.valueOf(maxAlignseq.seq1end + (seq.getStart() - 1)));
721     mappingDetails.append(NEWLINE);
722     maxChain.makeExactMapping(maxAlignseq, seq);
723     jalview.datamodel.Mapping sqmpping = maxAlignseq
724             .getMappingFromS1(false);
725     maxChain.transferRESNUMFeatures(seq, null);
726
727     HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
728     int resNum = -10000;
729     int index = 0;
730     char insCode = ' ';
731
732     do
733     {
734       Atom tmp = maxChain.atoms.elementAt(index);
735       if ((resNum != tmp.resNumber || insCode != tmp.insCode)
736               && tmp.alignmentMapping != -1)
737       {
738         resNum = tmp.resNumber;
739         insCode = tmp.insCode;
740         if (tmp.alignmentMapping >= -1)
741         {
742           mapping.put(tmp.alignmentMapping + 1,
743                   new int[]
744                   { tmp.resNumber, tmp.atomIndex });
745         }
746       }
747
748       index++;
749     } while (index < maxChain.atoms.size());
750
751     StructureMapping nwMapping = new StructureMapping(seq, pdbFile,
752             pdb.getId(), maxChainId, mapping, mappingDetails.toString());
753     maxChain.transferResidueAnnotation(nwMapping, sqmpping);
754       nwMappings.add(nwMapping);
755     }
756     return nwMappings;
757   }
758
759   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
760   {
761     listeners.removeElement(svl);
762     if (svl instanceof SequenceListener)
763     {
764       for (int i = 0; i < listeners.size(); i++)
765       {
766         if (listeners.elementAt(i) instanceof StructureListener)
767         {
768           ((StructureListener) listeners.elementAt(i))
769                   .releaseReferences(svl);
770         }
771       }
772     }
773
774     if (pdbfiles == null)
775     {
776       return;
777     }
778
779     /*
780      * Remove mappings to the closed listener's PDB files, but first check if
781      * another listener is still interested
782      */
783     List<String> pdbs = new ArrayList<String>(Arrays.asList(pdbfiles));
784
785     StructureListener sl;
786     for (int i = 0; i < listeners.size(); i++)
787     {
788       if (listeners.elementAt(i) instanceof StructureListener)
789       {
790         sl = (StructureListener) listeners.elementAt(i);
791         for (String pdbfile : sl.getStructureFiles())
792         {
793           pdbs.remove(pdbfile);
794         }
795       }
796     }
797
798     /*
799      * Rebuild the mappings set, retaining only those which are for 'other' PDB
800      * files
801      */
802     if (pdbs.size() > 0)
803     {
804       List<StructureMapping> tmp = new ArrayList<StructureMapping>();
805       for (StructureMapping sm : mappings)
806       {
807         if (!pdbs.contains(sm.pdbfile))
808         {
809           tmp.add(sm);
810         }
811       }
812
813       mappings = tmp;
814     }
815   }
816
817   /**
818    * Propagate mouseover of a single position in a structure
819    * 
820    * @param pdbResNum
821    * @param chain
822    * @param pdbfile
823    */
824   public void mouseOverStructure(int pdbResNum, String chain,
825           String pdbfile)
826   {
827     AtomSpec atomSpec = new AtomSpec(pdbfile, chain, pdbResNum, 0);
828     List<AtomSpec> atoms = Collections.singletonList(atomSpec);
829     mouseOverStructure(atoms);
830   }
831
832   /**
833    * Propagate mouseover or selection of multiple positions in a structure
834    * 
835    * @param atoms
836    */
837   public void mouseOverStructure(List<AtomSpec> atoms)
838   {
839     if (listeners == null)
840     {
841       // old or prematurely sent event
842       return;
843     }
844     boolean hasSequenceListener = false;
845     for (int i = 0; i < listeners.size(); i++)
846     {
847       if (listeners.elementAt(i) instanceof SequenceListener)
848       {
849         hasSequenceListener = true;
850       }
851     }
852     if (!hasSequenceListener)
853     {
854       return;
855     }
856
857     SearchResultsI results = findAlignmentPositionsForStructurePositions(
858             atoms);
859     for (Object li : listeners)
860     {
861       if (li instanceof SequenceListener)
862       {
863         ((SequenceListener) li).highlightSequence(results);
864       }
865     }
866   }
867
868   /**
869    * Constructs a SearchResults object holding regions (if any) in the Jalview
870    * alignment which have a mapping to the structure viewer positions in the
871    * supplied list
872    * 
873    * @param atoms
874    * @return
875    */
876   public SearchResultsI findAlignmentPositionsForStructurePositions(
877           List<AtomSpec> atoms)
878   {
879     SearchResultsI results = new SearchResults();
880     for (AtomSpec atom : atoms)
881     {
882       SequenceI lastseq = null;
883       int lastipos = -1;
884       for (StructureMapping sm : mappings)
885       {
886         if (sm.pdbfile.equals(atom.getPdbFile())
887                 && sm.pdbchain.equals(atom.getChain()))
888         {
889           int indexpos = sm.getSeqPos(atom.getPdbResNum());
890           if (lastipos != indexpos && lastseq != sm.sequence)
891           {
892             results.addResult(sm.sequence, indexpos, indexpos);
893             lastipos = indexpos;
894             lastseq = sm.sequence;
895             // construct highlighted sequence list
896             for (AlignedCodonFrame acf : seqmappings)
897             {
898               acf.markMappedRegion(sm.sequence, indexpos, results);
899             }
900           }
901         }
902       }
903     }
904     return results;
905   }
906
907   /**
908    * highlight regions associated with a position (indexpos) in seq
909    * 
910    * @param seq
911    *          the sequence that the mouse over occurred on
912    * @param indexpos
913    *          the absolute position being mouseovered in seq (0 to seq.length())
914    * @param seqPos
915    *          the sequence position (if -1, seq.findPosition is called to
916    *          resolve the residue number)
917    */
918   public void mouseOverSequence(SequenceI seq, int indexpos, int seqPos,
919           VamsasSource source)
920   {
921     boolean hasSequenceListeners = handlingVamsasMo
922             || !seqmappings.isEmpty();
923     SearchResultsI results = null;
924     if (seqPos == -1)
925     {
926       seqPos = seq.findPosition(indexpos);
927     }
928     for (int i = 0; i < listeners.size(); i++)
929     {
930       Object listener = listeners.elementAt(i);
931       if (listener == source)
932       {
933         // TODO listener (e.g. SeqPanel) is never == source (AlignViewport)
934         // Temporary fudge with SequenceListener.getVamsasSource()
935         continue;
936       }
937       if (listener instanceof StructureListener)
938       {
939         highlightStructure((StructureListener) listener, seq, seqPos);
940       }
941       else
942       {
943         if (listener instanceof SequenceListener)
944         {
945           final SequenceListener seqListener = (SequenceListener) listener;
946           if (hasSequenceListeners
947                   && seqListener.getVamsasSource() != source)
948           {
949             if (relaySeqMappings)
950             {
951               if (results == null)
952               {
953                 results = MappingUtils.buildSearchResults(seq, seqPos,
954                         seqmappings);
955               }
956               if (handlingVamsasMo)
957               {
958                 results.addResult(seq, seqPos, seqPos);
959
960               }
961               if (!results.isEmpty())
962               {
963                 seqListener.highlightSequence(results);
964               }
965             }
966           }
967         }
968         else if (listener instanceof VamsasListener && !handlingVamsasMo)
969         {
970           ((VamsasListener) listener).mouseOverSequence(seq, indexpos,
971                   source);
972         }
973         else if (listener instanceof SecondaryStructureListener)
974         {
975           ((SecondaryStructureListener) listener).mouseOverSequence(seq,
976                   indexpos, seqPos);
977         }
978       }
979     }
980   }
981
982   /**
983    * Send suitable messages to a StructureListener to highlight atoms
984    * corresponding to the given sequence position(s)
985    * 
986    * @param sl
987    * @param seq
988    * @param positions
989    */
990   public void highlightStructure(StructureListener sl, SequenceI seq,
991           int... positions)
992   {
993     if (!sl.isListeningFor(seq))
994     {
995       return;
996     }
997     int atomNo;
998     List<AtomSpec> atoms = new ArrayList<AtomSpec>();
999     for (StructureMapping sm : mappings)
1000     {
1001       if (sm.sequence == seq || sm.sequence == seq.getDatasetSequence()
1002               || (sm.sequence.getDatasetSequence() != null && sm.sequence
1003                       .getDatasetSequence() == seq.getDatasetSequence()))
1004       {
1005         for (int index : positions)
1006         {
1007           atomNo = sm.getAtomNum(index);
1008
1009           if (atomNo > 0)
1010           {
1011             atoms.add(new AtomSpec(sm.pdbfile, sm.pdbchain,
1012                     sm.getPDBResNum(index), atomNo));
1013           }
1014         }
1015       }
1016     }
1017     sl.highlightAtoms(atoms);
1018   }
1019
1020   /**
1021    * true if a mouse over event from an external (ie Vamsas) source is being
1022    * handled
1023    */
1024   boolean handlingVamsasMo = false;
1025
1026   long lastmsg = 0;
1027
1028   /**
1029    * as mouseOverSequence but only route event to SequenceListeners
1030    * 
1031    * @param sequenceI
1032    * @param position
1033    *          in an alignment sequence
1034    */
1035   public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
1036           VamsasSource source)
1037   {
1038     handlingVamsasMo = true;
1039     long msg = sequenceI.hashCode() * (1 + position);
1040     if (lastmsg != msg)
1041     {
1042       lastmsg = msg;
1043       mouseOverSequence(sequenceI, position, -1, source);
1044     }
1045     handlingVamsasMo = false;
1046   }
1047
1048   public Annotation[] colourSequenceFromStructure(SequenceI seq,
1049           String pdbid)
1050   {
1051     return null;
1052     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
1053     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
1054     /*
1055      * Annotation [] annotations = new Annotation[seq.getLength()];
1056      * 
1057      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
1058      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
1059      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
1060      * 
1061      * for (int j = 0; j < mappings.length; j++) {
1062      * 
1063      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
1064      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
1065      * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
1066      * "+mappings[j].pdbfile);
1067      * 
1068      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
1069      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
1070      * 
1071      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
1072      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
1073      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
1074      * mappings[j].pdbfile); }
1075      * 
1076      * annotations[index] = new Annotation("X",null,' ',0,col); } return
1077      * annotations; } } } }
1078      * 
1079      * return annotations;
1080      */
1081   }
1082
1083   public void structureSelectionChanged()
1084   {
1085   }
1086
1087   public void sequenceSelectionChanged()
1088   {
1089   }
1090
1091   public void sequenceColoursChanged(Object source)
1092   {
1093     StructureListener sl;
1094     for (int i = 0; i < listeners.size(); i++)
1095     {
1096       if (listeners.elementAt(i) instanceof StructureListener)
1097       {
1098         sl = (StructureListener) listeners.elementAt(i);
1099         sl.updateColours(source);
1100       }
1101     }
1102   }
1103
1104   public StructureMapping[] getMapping(String pdbfile)
1105   {
1106     List<StructureMapping> tmp = new ArrayList<StructureMapping>();
1107     for (StructureMapping sm : mappings)
1108     {
1109       if (sm.pdbfile.equals(pdbfile))
1110       {
1111         tmp.add(sm);
1112       }
1113     }
1114     return tmp.toArray(new StructureMapping[tmp.size()]);
1115   }
1116
1117   /**
1118    * Returns a readable description of all mappings for the given pdbfile to any
1119    * of the given sequences
1120    * 
1121    * @param pdbfile
1122    * @param seqs
1123    * @return
1124    */
1125   public String printMappings(String pdbfile, List<SequenceI> seqs)
1126   {
1127     if (pdbfile == null || seqs == null || seqs.isEmpty())
1128     {
1129       return "";
1130     }
1131
1132     StringBuilder sb = new StringBuilder(64);
1133     for (StructureMapping sm : mappings)
1134     {
1135       if (sm.pdbfile.equals(pdbfile) && seqs.contains(sm.sequence))
1136       {
1137         sb.append(sm.mappingDetails);
1138         sb.append(NEWLINE);
1139         // separator makes it easier to read multiple mappings
1140         sb.append("=====================");
1141         sb.append(NEWLINE);
1142       }
1143     }
1144     sb.append(NEWLINE);
1145
1146     return sb.toString();
1147   }
1148
1149   /**
1150    * Remove the given mapping
1151    * 
1152    * @param acf
1153    */
1154   public void deregisterMapping(AlignedCodonFrame acf)
1155   {
1156     if (acf != null)
1157     {
1158       boolean removed = seqmappings.remove(acf);
1159       if (removed && seqmappings.isEmpty())
1160       { // debug
1161         System.out.println("All mappings removed");
1162       }
1163     }
1164   }
1165
1166   /**
1167    * Add each of the given codonFrames to the stored set, if not aready present.
1168    * 
1169    * @param mappings
1170    */
1171   public void registerMappings(List<AlignedCodonFrame> mappings)
1172   {
1173     if (mappings != null)
1174     {
1175       for (AlignedCodonFrame acf : mappings)
1176       {
1177         registerMapping(acf);
1178       }
1179     }
1180   }
1181
1182   /**
1183    * Add the given mapping to the stored set, unless already stored.
1184    */
1185   public void registerMapping(AlignedCodonFrame acf)
1186   {
1187     if (acf != null)
1188     {
1189       if (!seqmappings.contains(acf))
1190       {
1191         seqmappings.add(acf);
1192       }
1193     }
1194   }
1195
1196   /**
1197    * Resets this object to its initial state by removing all registered
1198    * listeners, codon mappings, PDB file mappings
1199    */
1200   public void resetAll()
1201   {
1202     if (mappings != null)
1203     {
1204       mappings.clear();
1205     }
1206     if (seqmappings != null)
1207     {
1208       seqmappings.clear();
1209     }
1210     if (sel_listeners != null)
1211     {
1212       sel_listeners.clear();
1213     }
1214     if (listeners != null)
1215     {
1216       listeners.clear();
1217     }
1218     if (commandListeners != null)
1219     {
1220       commandListeners.clear();
1221     }
1222     if (view_listeners != null)
1223     {
1224       view_listeners.clear();
1225     }
1226     if (pdbFileNameId != null)
1227     {
1228       pdbFileNameId.clear();
1229     }
1230     if (pdbIdFileName != null)
1231     {
1232       pdbIdFileName.clear();
1233     }
1234   }
1235
1236   public void addSelectionListener(SelectionListener selecter)
1237   {
1238     if (!sel_listeners.contains(selecter))
1239     {
1240       sel_listeners.add(selecter);
1241     }
1242   }
1243
1244   public void removeSelectionListener(SelectionListener toremove)
1245   {
1246     if (sel_listeners.contains(toremove))
1247     {
1248       sel_listeners.remove(toremove);
1249     }
1250   }
1251
1252   public synchronized void sendSelection(
1253           jalview.datamodel.SequenceGroup selection,
1254           jalview.datamodel.ColumnSelection colsel, HiddenColumns hidden,
1255           SelectionSource source)
1256   {
1257     for (SelectionListener slis : sel_listeners)
1258     {
1259       if (slis != source)
1260       {
1261         slis.selection(selection, colsel, hidden, source);
1262       }
1263     }
1264   }
1265
1266   Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
1267
1268   public synchronized void sendViewPosition(
1269           jalview.api.AlignmentViewPanel source, int startRes, int endRes,
1270           int startSeq, int endSeq)
1271   {
1272
1273     if (view_listeners != null && view_listeners.size() > 0)
1274     {
1275       Enumeration<AlignmentViewPanelListener> listeners = view_listeners
1276               .elements();
1277       while (listeners.hasMoreElements())
1278       {
1279         AlignmentViewPanelListener slis = listeners.nextElement();
1280         if (slis != source)
1281         {
1282           slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
1283         }
1284         ;
1285       }
1286     }
1287   }
1288
1289   /**
1290    * release all references associated with this manager provider
1291    * 
1292    * @param jalviewLite
1293    */
1294   public static void release(StructureSelectionManagerProvider jalviewLite)
1295   {
1296     // synchronized (instances)
1297     {
1298       if (instances == null)
1299       {
1300         return;
1301       }
1302       StructureSelectionManager mnger = (instances.get(jalviewLite));
1303       if (mnger != null)
1304       {
1305         instances.remove(jalviewLite);
1306         try
1307         {
1308           mnger.finalize();
1309         } catch (Throwable x)
1310         {
1311         }
1312       }
1313     }
1314   }
1315
1316   public void registerPDBEntry(PDBEntry pdbentry)
1317   {
1318     if (pdbentry.getFile() != null
1319             && pdbentry.getFile().trim().length() > 0)
1320     {
1321       registerPDBFile(pdbentry.getId(), pdbentry.getFile());
1322     }
1323   }
1324
1325   public void addCommandListener(CommandListener cl)
1326   {
1327     if (!commandListeners.contains(cl))
1328     {
1329       commandListeners.add(cl);
1330     }
1331   }
1332
1333   public boolean hasCommandListener(CommandListener cl)
1334   {
1335     return this.commandListeners.contains(cl);
1336   }
1337
1338   public boolean removeCommandListener(CommandListener l)
1339   {
1340     return commandListeners.remove(l);
1341   }
1342
1343   /**
1344    * Forward a command to any command listeners (except for the command's
1345    * source).
1346    * 
1347    * @param command
1348    *          the command to be broadcast (in its form after being performed)
1349    * @param undo
1350    *          if true, the command was being 'undone'
1351    * @param source
1352    */
1353   public void commandPerformed(CommandI command, boolean undo,
1354           VamsasSource source)
1355   {
1356     for (CommandListener listener : commandListeners)
1357     {
1358       listener.mirrorCommand(command, undo, this, source);
1359     }
1360   }
1361
1362   /**
1363    * Returns a new CommandI representing the given command as mapped to the
1364    * given sequences. If no mapping could be made, or the command is not of a
1365    * mappable kind, returns null.
1366    * 
1367    * @param command
1368    * @param undo
1369    * @param mapTo
1370    * @param gapChar
1371    * @return
1372    */
1373   public CommandI mapCommand(CommandI command, boolean undo,
1374           final AlignmentI mapTo, char gapChar)
1375   {
1376     if (command instanceof EditCommand)
1377     {
1378       return MappingUtils.mapEditCommand((EditCommand) command, undo, mapTo,
1379               gapChar, seqmappings);
1380     }
1381     else if (command instanceof OrderCommand)
1382     {
1383       return MappingUtils.mapOrderCommand((OrderCommand) command, undo,
1384               mapTo, seqmappings);
1385     }
1386     return null;
1387   }
1388
1389   public IProgressIndicator getProgressIndicator()
1390   {
1391     return progressIndicator;
1392   }
1393
1394   public void setProgressIndicator(IProgressIndicator progressIndicator)
1395   {
1396     this.progressIndicator = progressIndicator;
1397   }
1398
1399   public long getProgressSessionId()
1400   {
1401     return progressSessionId;
1402   }
1403
1404   public void setProgressSessionId(long progressSessionId)
1405   {
1406     this.progressSessionId = progressSessionId;
1407   }
1408
1409   public void setProgressBar(String message)
1410   {
1411     if (progressIndicator == null)
1412     {
1413       return;
1414     }
1415     progressIndicator.setProgressBar(message, progressSessionId);
1416   }
1417
1418   public List<AlignedCodonFrame> getSequenceMappings()
1419   {
1420     return seqmappings;
1421   }
1422
1423 }