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