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