JAL-2781 use SIFTs mapping rather than maxChain AlignSeq to propagate annotation...
[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   private SiftsClient siftsClient = null;
78
79   /*
80    * Set of any registered mappings between (dataset) sequences.
81    */
82   private List<AlignedCodonFrame> seqmappings = new ArrayList<>();
83
84   private List<CommandListener> commandListeners = new ArrayList<>();
85
86   private List<SelectionListener> sel_listeners = new ArrayList<>();
87
88   /**
89    * @return true if will try to use external services for processing secondary
90    *         structure
91    */
92   public boolean isSecStructServices()
93   {
94     return secStructServices;
95   }
96
97   /**
98    * control use of external services for processing secondary structure
99    * 
100    * @param secStructServices
101    */
102   public void setSecStructServices(boolean secStructServices)
103   {
104     this.secStructServices = secStructServices;
105   }
106
107   /**
108    * flag controlling addition of any kind of structural annotation
109    * 
110    * @return true if temperature factor annotation will be added
111    */
112   public boolean isAddTempFacAnnot()
113   {
114     return addTempFacAnnot;
115   }
116
117   /**
118    * set flag controlling addition of structural annotation
119    * 
120    * @param addTempFacAnnot
121    */
122   public void setAddTempFacAnnot(boolean addTempFacAnnot)
123   {
124     this.addTempFacAnnot = addTempFacAnnot;
125   }
126
127   /**
128    * 
129    * @return if true, the structure manager will attempt to add secondary
130    *         structure lines for unannotated sequences
131    */
132
133   public boolean isProcessSecondaryStructure()
134   {
135     return processSecondaryStructure;
136   }
137
138   /**
139    * Control whether structure manager will try to annotate mapped sequences
140    * with secondary structure from PDB data.
141    * 
142    * @param enable
143    */
144   public void setProcessSecondaryStructure(boolean enable)
145   {
146     processSecondaryStructure = enable;
147   }
148
149   /**
150    * debug function - write all mappings to stdout
151    */
152   public void reportMapping()
153   {
154     if (mappings.isEmpty())
155     {
156       System.err.println("reportMapping: No PDB/Sequence mappings.");
157     }
158     else
159     {
160       System.err.println(
161               "reportMapping: There are " + mappings.size() + " mappings.");
162       int i = 0;
163       for (StructureMapping sm : mappings)
164       {
165         System.err.println("mapping " + i++ + " : " + sm.pdbfile);
166       }
167     }
168   }
169
170   /**
171    * map between the PDB IDs (or structure identifiers) used by Jalview and the
172    * absolute filenames for PDB data that corresponds to it
173    */
174   Map<String, String> pdbIdFileName = new HashMap<>();
175
176   Map<String, String> pdbFileNameId = new HashMap<>();
177
178   public void registerPDBFile(String idForFile, String absoluteFile)
179   {
180     pdbIdFileName.put(idForFile, absoluteFile);
181     pdbFileNameId.put(absoluteFile, idForFile);
182   }
183
184   public String findIdForPDBFile(String idOrFile)
185   {
186     String id = pdbFileNameId.get(idOrFile);
187     return id;
188   }
189
190   public String findFileForPDBId(String idOrFile)
191   {
192     String id = pdbIdFileName.get(idOrFile);
193     return id;
194   }
195
196   public boolean isPDBFileRegistered(String idOrFile)
197   {
198     return pdbFileNameId.containsKey(idOrFile)
199             || pdbIdFileName.containsKey(idOrFile);
200   }
201
202   private static StructureSelectionManager nullProvider = null;
203
204   public static StructureSelectionManager getStructureSelectionManager(
205           StructureSelectionManagerProvider context)
206   {
207     if (context == null)
208     {
209       if (nullProvider == null)
210       {
211         if (instances != null)
212         {
213           throw new Error(MessageManager.getString(
214                   "error.implementation_error_structure_selection_manager_null"),
215                   new NullPointerException(MessageManager
216                           .getString("exception.ssm_context_is_null")));
217         }
218         else
219         {
220           nullProvider = new StructureSelectionManager();
221         }
222         return nullProvider;
223       }
224     }
225     if (instances == null)
226     {
227       instances = new java.util.IdentityHashMap<>();
228     }
229     StructureSelectionManager instance = instances.get(context);
230     if (instance == null)
231     {
232       if (nullProvider != null)
233       {
234         instance = nullProvider;
235       }
236       else
237       {
238         instance = new StructureSelectionManager();
239       }
240       instances.put(context, instance);
241     }
242     return instance;
243   }
244
245   /**
246    * flag controlling whether SeqMappings are relayed from received sequence
247    * mouse over events to other sequences
248    */
249   boolean relaySeqMappings = true;
250
251   /**
252    * Enable or disable relay of seqMapping events to other sequences. You might
253    * want to do this if there are many sequence mappings and the host computer
254    * is slow
255    * 
256    * @param relay
257    */
258   public void setRelaySeqMappings(boolean relay)
259   {
260     relaySeqMappings = relay;
261   }
262
263   /**
264    * get the state of the relay seqMappings flag.
265    * 
266    * @return true if sequence mouse overs are being relayed to other mapped
267    *         sequences
268    */
269   public boolean isRelaySeqMappingsEnabled()
270   {
271     return relaySeqMappings;
272   }
273
274   Vector listeners = new Vector();
275
276   /**
277    * register a listener for alignment sequence mouseover events
278    * 
279    * @param svl
280    */
281   public void addStructureViewerListener(Object svl)
282   {
283     if (!listeners.contains(svl))
284     {
285       listeners.addElement(svl);
286     }
287   }
288
289   /**
290    * Returns the file name for a mapped PDB id (or null if not mapped).
291    * 
292    * @param pdbid
293    * @return
294    */
295   public String alreadyMappedToFile(String pdbid)
296   {
297     for (StructureMapping sm : mappings)
298     {
299       if (sm.getPdbId().equals(pdbid))
300       {
301         return sm.pdbfile;
302       }
303     }
304     return null;
305   }
306
307   /**
308    * Import structure data and register a structure mapping for broadcasting
309    * colouring, mouseovers and selection events (convenience wrapper).
310    * 
311    * @param sequence
312    *          - one or more sequences to be mapped to pdbFile
313    * @param targetChains
314    *          - optional chain specification for mapping each sequence to pdb
315    *          (may be nill, individual elements may be nill)
316    * @param pdbFile
317    *          - structure data resource
318    * @param protocol
319    *          - how to resolve data from resource
320    * @return null or the structure data parsed as a pdb file
321    */
322   synchronized public StructureFile setMapping(SequenceI[] sequence,
323           String[] targetChains, String pdbFile, DataSourceType protocol, 
324           IProgressIndicator progress)
325   {
326     return computeMapping(true, sequence, targetChains, pdbFile, protocol,
327             progress);
328   }
329
330   /**
331    * create sequence structure mappings between each sequence and the given
332    * pdbFile (retrieved via the given protocol).
333    * 
334    * @param forStructureView
335    *          when true, record the mapping for use in mouseOvers
336    * 
337    * @param sequenceArray
338    *          - one or more sequences to be mapped to pdbFile
339    * @param targetChainIds
340    *          - optional chain specification for mapping each sequence to pdb
341    *          (may be nill, individual elements may be nill) - JBPNote: JAL-2693
342    *          - this should be List<List<String>>, empty lists indicate no
343    *          predefined mappings
344    * @param pdbFile
345    *          - structure data resource
346    * @param sourceType
347    *          - how to resolve data from resource
348    * @return null or the structure data parsed as a pdb file
349    */
350   synchronized public StructureFile setMapping(boolean forStructureView,
351           SequenceI[] sequenceArray, String[] targetChainIds,
352           String pdbFile, DataSourceType sourceType)
353   {
354     return computeMapping(forStructureView, sequenceArray, targetChainIds,
355             pdbFile, sourceType, null);
356   }
357
358   synchronized public StructureFile computeMapping(
359           boolean forStructureView, SequenceI[] sequenceArray,
360           String[] targetChainIds, String pdbFile, DataSourceType sourceType,
361           IProgressIndicator progress)
362   {
363     long progressSessionId = System.currentTimeMillis() * 3;
364     /*
365      * There will be better ways of doing this in the future, for now we'll use
366      * the tried and tested MCview pdb mapping
367      */
368     boolean parseSecStr = processSecondaryStructure;
369     if (isPDBFileRegistered(pdbFile))
370     {
371       for (SequenceI sq : sequenceArray)
372       {
373         SequenceI ds = sq;
374         while (ds.getDatasetSequence() != null)
375         {
376           ds = ds.getDatasetSequence();
377         }
378         ;
379         if (ds.getAnnotation() != null)
380         {
381           for (AlignmentAnnotation ala : ds.getAnnotation())
382           {
383             // false if any annotation present from this structure
384             // JBPNote this fails for jmol/chimera view because the *file* is
385             // passed, not the structure data ID -
386             if (PDBfile.isCalcIdForFile(ala, findIdForPDBFile(pdbFile)))
387             {
388               parseSecStr = false;
389             }
390           }
391         }
392       }
393     }
394     StructureFile pdb = null;
395     boolean isMapUsingSIFTs = SiftsSettings.isMapWithSifts();
396     try
397     {
398       sourceType = AppletFormatAdapter.checkProtocol(pdbFile);
399       pdb = new JmolParser(pdbFile, sourceType);
400
401       if (pdb.getId() != null && pdb.getId().trim().length() > 0
402               && DataSourceType.FILE == sourceType)
403       {
404         registerPDBFile(pdb.getId().trim(), pdbFile);
405       }
406       // if PDBId is unavailable then skip SIFTS mapping execution path
407       isMapUsingSIFTs = isMapUsingSIFTs && pdb.isPPDBIdAvailable();
408
409     } catch (Exception ex)
410     {
411       ex.printStackTrace();
412       return null;
413     }
414
415     try
416     {
417       if (isMapUsingSIFTs)
418       {
419         siftsClient = new SiftsClient(pdb);
420       }
421     } catch (SiftsException e)
422     {
423       isMapUsingSIFTs = false;
424       e.printStackTrace();
425     }
426
427     String targetChainId;
428     for (int s = 0; s < sequenceArray.length; s++)
429     {
430       boolean infChain = true;
431       final SequenceI seq = sequenceArray[s];
432       SequenceI ds = seq;
433       while (ds.getDatasetSequence() != null)
434       {
435         ds = ds.getDatasetSequence();
436       }
437
438       if (targetChainIds != null && targetChainIds[s] != null)
439       {
440         infChain = false;
441         targetChainId = targetChainIds[s];
442       }
443       else if (seq.getName().indexOf("|") > -1)
444       {
445         targetChainId = seq.getName()
446                 .substring(seq.getName().lastIndexOf("|") + 1);
447         if (targetChainId.length() > 1)
448         {
449           if (targetChainId.trim().length() == 0)
450           {
451             targetChainId = " ";
452           }
453           else
454           {
455             // not a valid chain identifier
456             targetChainId = "";
457           }
458         }
459       }
460       else
461       {
462         targetChainId = "";
463       }
464
465       /*
466        * Attempt pairwise alignment of the sequence with each chain in the PDB,
467        * and remember the highest scoring chain
468        */
469       float max = -10;
470       AlignSeq maxAlignseq = null;
471       String maxChainId = " ";
472       PDBChain maxChain = null;
473       boolean first = true;
474       for (PDBChain chain : pdb.getChains())
475       {
476         if (targetChainId.length() > 0 && !targetChainId.equals(chain.id)
477                 && !infChain)
478         {
479           continue; // don't try to map chains don't match.
480         }
481         // TODO: correctly determine sequence type for mixed na/peptide
482         // structures
483         final String type = chain.isNa ? AlignSeq.DNA : AlignSeq.PEP;
484         AlignSeq as = AlignSeq.doGlobalNWAlignment(seq, chain.sequence,
485                 type);
486         // equivalent to:
487         // AlignSeq as = new AlignSeq(sequence[s], chain.sequence, type);
488         // as.calcScoreMatrix();
489         // as.traceAlignment();
490
491         if (first || as.maxscore > max
492                 || (as.maxscore == max && chain.id.equals(targetChainId)))
493         {
494           first = false;
495           maxChain = chain;
496           max = as.maxscore;
497           maxAlignseq = as;
498           maxChainId = chain.id;
499         }
500       }
501       if (maxChain == null)
502       {
503         continue;
504       }
505
506       if (sourceType == DataSourceType.PASTE)
507       {
508         pdbFile = "INLINE" + pdb.getId();
509       }
510
511       List<StructureMapping> seqToStrucMapping = new ArrayList<>();
512       if (isMapUsingSIFTs && seq.isProtein())
513       {
514         if (progress!=null) {
515           progress.setProgressBar(MessageManager
516                 .getString("status.obtaining_mapping_with_sifts"),
517                   progressSessionId);
518         }
519         jalview.datamodel.Mapping sqmpping = maxAlignseq
520                 .getMappingFromS1(false);
521         if (targetChainId != null && !targetChainId.trim().isEmpty())
522         {
523           StructureMapping siftsMapping;
524           try
525           {
526             siftsMapping = getStructureMapping(seq, pdbFile, targetChainId,
527                     pdb, maxChain, sqmpping, maxAlignseq);
528             seqToStrucMapping.add(siftsMapping);
529             maxChain.makeExactMapping(siftsMapping, seq);
530             maxChain.transferRESNUMFeatures(seq, "IEA: SIFTS");// FIXME: is this
531                                                        // "IEA:SIFTS" ?
532             maxChain.transferResidueAnnotation(siftsMapping, null);
533             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
534
535           } catch (SiftsException e)
536           {
537             // fall back to NW alignment
538             System.err.println(e.getMessage());
539             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
540                     targetChainId, maxChain, pdb, maxAlignseq);
541             seqToStrucMapping.add(nwMapping);
542             maxChain.makeExactMapping(maxAlignseq, seq);
543             maxChain.transferRESNUMFeatures(seq, "IEA:Jalview"); // FIXME: is
544                                                                  // this
545                                                         // "IEA:Jalview" ?
546             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
547             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
548           }
549         }
550         else
551         {
552           List<StructureMapping> foundSiftsMappings = new ArrayList<>();
553           for (PDBChain chain : pdb.getChains())
554           {
555             StructureMapping siftsMapping = null;
556             try
557             {
558               siftsMapping = getStructureMapping(seq,
559                       pdbFile, chain.id, pdb, chain, sqmpping, maxAlignseq);
560               foundSiftsMappings.add(siftsMapping);
561               chain.makeExactMapping(siftsMapping, seq);
562               chain.transferRESNUMFeatures(seq, "IEA: SIFTS");// FIXME: is this
563               // "IEA:SIFTS" ?
564               chain.transferResidueAnnotation(siftsMapping, null);
565             } catch (SiftsException e)
566             {
567               System.err.println(e.getMessage());
568             }
569           }
570           if (!foundSiftsMappings.isEmpty())
571           {
572             seqToStrucMapping.addAll(foundSiftsMappings);
573             ds.addPDBId(sqmpping.getTo().getAllPDBEntries().get(0));
574           }
575           else
576           {
577             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
578                     maxChainId, maxChain, pdb, maxAlignseq);
579             seqToStrucMapping.add(nwMapping);
580             maxChain.transferRESNUMFeatures(seq, null); // FIXME: is this
581                                                         // "IEA:Jalview" ?
582             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
583             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
584           }
585         }
586       }
587       else
588       {
589         if (progress != null)
590         {
591           progress.setProgressBar(MessageManager
592                                   .getString("status.obtaining_mapping_with_nw_alignment"),
593                   progressSessionId);
594         }
595         StructureMapping nwMapping = getNWMappings(seq, pdbFile, maxChainId,
596                 maxChain, pdb, maxAlignseq);
597         seqToStrucMapping.add(nwMapping);
598         ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
599       }
600       if (forStructureView)
601       {
602         mappings.addAll(seqToStrucMapping);
603       }
604       if (progress != null)
605       {
606         progress.setProgressBar(null, progressSessionId);
607       }
608     }
609     return pdb;
610   }
611
612   public void addStructureMapping(StructureMapping sm)
613   {
614     mappings.add(sm);
615   }
616
617   /**
618    * retrieve a mapping for seq from SIFTs using associated DBRefEntry for
619    * uniprot or PDB
620    * 
621    * @param seq
622    * @param pdbFile
623    * @param targetChainId
624    * @param pdb
625    * @param maxChain
626    * @param sqmpping
627    * @param maxAlignseq
628    * @return
629    * @throws SiftsException
630    */
631   private StructureMapping getStructureMapping(SequenceI seq,
632           String pdbFile, String targetChainId, StructureFile pdb,
633           PDBChain maxChain, jalview.datamodel.Mapping sqmpping,
634           AlignSeq maxAlignseq) throws SiftsException
635   {
636     StructureMapping curChainMapping = siftsClient
637             .getSiftsStructureMapping(seq, pdbFile, targetChainId);
638     try
639     {
640       PDBChain chain = pdb.findChain(targetChainId);
641       if (chain != null)
642       {
643         chain.transferResidueAnnotation(curChainMapping, null);
644       }
645     } catch (Exception e)
646     {
647       e.printStackTrace();
648     }
649     return curChainMapping;
650   }
651
652   private StructureMapping getNWMappings(SequenceI seq, String pdbFile,
653           String maxChainId, PDBChain maxChain, StructureFile pdb,
654           AlignSeq maxAlignseq)
655   {
656     final StringBuilder mappingDetails = new StringBuilder(128);
657     mappingDetails.append(NEWLINE)
658             .append("Sequence \u27f7 Structure mapping details");
659     mappingDetails.append(NEWLINE);
660     mappingDetails
661             .append("Method: inferred with Needleman & Wunsch alignment");
662     mappingDetails.append(NEWLINE).append("PDB Sequence is :")
663             .append(NEWLINE).append("Sequence = ")
664             .append(maxChain.sequence.getSequenceAsString());
665     mappingDetails.append(NEWLINE).append("No of residues = ")
666             .append(maxChain.residues.size()).append(NEWLINE)
667             .append(NEWLINE);
668     PrintStream ps = new PrintStream(System.out)
669     {
670       @Override
671       public void print(String x)
672       {
673         mappingDetails.append(x);
674       }
675
676       @Override
677       public void println()
678       {
679         mappingDetails.append(NEWLINE);
680       }
681     };
682
683     maxAlignseq.printAlignment(ps);
684
685     mappingDetails.append(NEWLINE).append("PDB start/end ");
686     mappingDetails.append(String.valueOf(maxAlignseq.seq2start))
687             .append(" ");
688     mappingDetails.append(String.valueOf(maxAlignseq.seq2end));
689     mappingDetails.append(NEWLINE).append("SEQ start/end ");
690     mappingDetails
691             .append(String
692                     .valueOf(maxAlignseq.seq1start + (seq.getStart() - 1)))
693             .append(" ");
694     mappingDetails.append(
695             String.valueOf(maxAlignseq.seq1end + (seq.getStart() - 1)));
696     mappingDetails.append(NEWLINE);
697     maxChain.makeExactMapping(maxAlignseq, seq);
698     jalview.datamodel.Mapping sqmpping = maxAlignseq
699             .getMappingFromS1(false);
700     maxChain.transferRESNUMFeatures(seq, null);
701
702     HashMap<Integer, int[]> mapping = new HashMap<>();
703     int resNum = -10000;
704     int index = 0;
705     char insCode = ' ';
706
707     do
708     {
709       Atom tmp = maxChain.atoms.elementAt(index);
710       if ((resNum != tmp.resNumber || insCode != tmp.insCode)
711               && tmp.alignmentMapping != -1)
712       {
713         resNum = tmp.resNumber;
714         insCode = tmp.insCode;
715         if (tmp.alignmentMapping >= -1)
716         {
717           mapping.put(tmp.alignmentMapping + 1,
718                   new int[]
719                   { tmp.resNumber, tmp.atomIndex });
720         }
721       }
722
723       index++;
724     } while (index < maxChain.atoms.size());
725
726     StructureMapping nwMapping = new StructureMapping(seq, pdbFile,
727             pdb.getId(), maxChainId, mapping, mappingDetails.toString());
728     maxChain.transferResidueAnnotation(nwMapping, sqmpping);
729     return nwMapping;
730   }
731
732   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
733   {
734     listeners.removeElement(svl);
735     if (svl instanceof SequenceListener)
736     {
737       for (int i = 0; i < listeners.size(); i++)
738       {
739         if (listeners.elementAt(i) instanceof StructureListener)
740         {
741           ((StructureListener) listeners.elementAt(i))
742                   .releaseReferences(svl);
743         }
744       }
745     }
746
747     if (pdbfiles == null)
748     {
749       return;
750     }
751
752     /*
753      * Remove mappings to the closed listener's PDB files, but first check if
754      * another listener is still interested
755      */
756     List<String> pdbs = new ArrayList<>(Arrays.asList(pdbfiles));
757
758     StructureListener sl;
759     for (int i = 0; i < listeners.size(); i++)
760     {
761       if (listeners.elementAt(i) instanceof StructureListener)
762       {
763         sl = (StructureListener) listeners.elementAt(i);
764         for (String pdbfile : sl.getStructureFiles())
765         {
766           pdbs.remove(pdbfile);
767         }
768       }
769     }
770
771     /*
772      * Rebuild the mappings set, retaining only those which are for 'other' PDB
773      * files
774      */
775     if (pdbs.size() > 0)
776     {
777       List<StructureMapping> tmp = new ArrayList<>();
778       for (StructureMapping sm : mappings)
779       {
780         if (!pdbs.contains(sm.pdbfile))
781         {
782           tmp.add(sm);
783         }
784       }
785
786       mappings = tmp;
787     }
788   }
789
790   /**
791    * Propagate mouseover of a single position in a structure
792    * 
793    * @param pdbResNum
794    * @param chain
795    * @param pdbfile
796    */
797   public void mouseOverStructure(int pdbResNum, String chain,
798           String pdbfile)
799   {
800     AtomSpec atomSpec = new AtomSpec(pdbfile, chain, pdbResNum, 0);
801     List<AtomSpec> atoms = Collections.singletonList(atomSpec);
802     mouseOverStructure(atoms);
803   }
804
805   /**
806    * Propagate mouseover or selection of multiple positions in a structure
807    * 
808    * @param atoms
809    */
810   public void mouseOverStructure(List<AtomSpec> atoms)
811   {
812     if (listeners == null)
813     {
814       // old or prematurely sent event
815       return;
816     }
817     boolean hasSequenceListener = false;
818     for (int i = 0; i < listeners.size(); i++)
819     {
820       if (listeners.elementAt(i) instanceof SequenceListener)
821       {
822         hasSequenceListener = true;
823       }
824     }
825     if (!hasSequenceListener)
826     {
827       return;
828     }
829
830     SearchResultsI results = findAlignmentPositionsForStructurePositions(
831             atoms);
832     for (Object li : listeners)
833     {
834       if (li instanceof SequenceListener)
835       {
836         ((SequenceListener) li).highlightSequence(results);
837       }
838     }
839   }
840
841   /**
842    * Constructs a SearchResults object holding regions (if any) in the Jalview
843    * alignment which have a mapping to the structure viewer positions in the
844    * supplied list
845    * 
846    * @param atoms
847    * @return
848    */
849   public SearchResultsI findAlignmentPositionsForStructurePositions(
850           List<AtomSpec> atoms)
851   {
852     SearchResultsI results = new SearchResults();
853     for (AtomSpec atom : atoms)
854     {
855       SequenceI lastseq = null;
856       int lastipos = -1;
857       for (StructureMapping sm : mappings)
858       {
859         if (sm.pdbfile.equals(atom.getPdbFile())
860                 && sm.pdbchain.equals(atom.getChain()))
861         {
862           int indexpos = sm.getSeqPos(atom.getPdbResNum());
863           if (lastipos != indexpos || lastseq != sm.sequence)
864           {
865             results.addResult(sm.sequence, indexpos, indexpos);
866             lastipos = indexpos;
867             lastseq = sm.sequence;
868             // construct highlighted sequence list
869             for (AlignedCodonFrame acf : seqmappings)
870             {
871               acf.markMappedRegion(sm.sequence, indexpos, results);
872             }
873           }
874         }
875       }
876     }
877     return results;
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<>();
972     for (StructureMapping sm : mappings)
973     {
974       if (sm.sequence == seq || sm.sequence == seq.getDatasetSequence()
975               || (sm.sequence.getDatasetSequence() != null && sm.sequence
976                       .getDatasetSequence() == seq.getDatasetSequence()))
977       {
978         for (int index : positions)
979         {
980           atomNo = sm.getAtomNum(index);
981
982           if (atomNo > 0)
983           {
984             atoms.add(new AtomSpec(sm.pdbfile, sm.pdbchain,
985                     sm.getPDBResNum(index), atomNo));
986           }
987         }
988       }
989     }
990     sl.highlightAtoms(atoms);
991   }
992
993   /**
994    * true if a mouse over event from an external (ie Vamsas) source is being
995    * handled
996    */
997   boolean handlingVamsasMo = false;
998
999   long lastmsg = 0;
1000
1001   /**
1002    * as mouseOverSequence but only route event to SequenceListeners
1003    * 
1004    * @param sequenceI
1005    * @param position
1006    *          in an alignment sequence
1007    */
1008   public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
1009           VamsasSource source)
1010   {
1011     handlingVamsasMo = true;
1012     long msg = sequenceI.hashCode() * (1 + position);
1013     if (lastmsg != msg)
1014     {
1015       lastmsg = msg;
1016       mouseOverSequence(sequenceI, position, -1, source);
1017     }
1018     handlingVamsasMo = false;
1019   }
1020
1021   public Annotation[] colourSequenceFromStructure(SequenceI seq,
1022           String pdbid)
1023   {
1024     return null;
1025     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
1026     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
1027     /*
1028      * Annotation [] annotations = new Annotation[seq.getLength()];
1029      * 
1030      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
1031      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
1032      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
1033      * 
1034      * for (int j = 0; j < mappings.length; j++) {
1035      * 
1036      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
1037      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
1038      * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
1039      * "+mappings[j].pdbfile);
1040      * 
1041      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
1042      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
1043      * 
1044      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
1045      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
1046      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
1047      * mappings[j].pdbfile); }
1048      * 
1049      * annotations[index] = new Annotation("X",null,' ',0,col); } return
1050      * annotations; } } } }
1051      * 
1052      * return annotations;
1053      */
1054   }
1055
1056   public void structureSelectionChanged()
1057   {
1058   }
1059
1060   public void sequenceSelectionChanged()
1061   {
1062   }
1063
1064   public void sequenceColoursChanged(Object source)
1065   {
1066     StructureListener sl;
1067     for (int i = 0; i < listeners.size(); i++)
1068     {
1069       if (listeners.elementAt(i) instanceof StructureListener)
1070       {
1071         sl = (StructureListener) listeners.elementAt(i);
1072         sl.updateColours(source);
1073       }
1074     }
1075   }
1076
1077   public StructureMapping[] getMapping(String pdbfile)
1078   {
1079     List<StructureMapping> tmp = new ArrayList<>();
1080     for (StructureMapping sm : mappings)
1081     {
1082       if (sm.pdbfile.equals(pdbfile))
1083       {
1084         tmp.add(sm);
1085       }
1086     }
1087     return tmp.toArray(new StructureMapping[tmp.size()]);
1088   }
1089
1090   /**
1091    * Returns a readable description of all mappings for the given pdbfile to any
1092    * of the given sequences
1093    * 
1094    * @param pdbfile
1095    * @param seqs
1096    * @return
1097    */
1098   public String printMappings(String pdbfile, List<SequenceI> seqs)
1099   {
1100     if (pdbfile == null || seqs == null || seqs.isEmpty())
1101     {
1102       return "";
1103     }
1104
1105     StringBuilder sb = new StringBuilder(64);
1106     for (StructureMapping sm : mappings)
1107     {
1108       if (sm.pdbfile.equals(pdbfile) && seqs.contains(sm.sequence))
1109       {
1110         sb.append(sm.mappingDetails);
1111         sb.append(NEWLINE);
1112         // separator makes it easier to read multiple mappings
1113         sb.append("=====================");
1114         sb.append(NEWLINE);
1115       }
1116     }
1117     sb.append(NEWLINE);
1118
1119     return sb.toString();
1120   }
1121
1122   /**
1123    * Remove the given mapping
1124    * 
1125    * @param acf
1126    */
1127   public void deregisterMapping(AlignedCodonFrame acf)
1128   {
1129     if (acf != null)
1130     {
1131       boolean removed = seqmappings.remove(acf);
1132       if (removed && seqmappings.isEmpty())
1133       { // debug
1134         System.out.println("All mappings removed");
1135       }
1136     }
1137   }
1138
1139   /**
1140    * Add each of the given codonFrames to the stored set, if not aready present.
1141    * 
1142    * @param mappings
1143    */
1144   public void registerMappings(List<AlignedCodonFrame> mappings)
1145   {
1146     if (mappings != null)
1147     {
1148       for (AlignedCodonFrame acf : mappings)
1149       {
1150         registerMapping(acf);
1151       }
1152     }
1153   }
1154
1155   /**
1156    * Add the given mapping to the stored set, unless already stored.
1157    */
1158   public void registerMapping(AlignedCodonFrame acf)
1159   {
1160     if (acf != null)
1161     {
1162       if (!seqmappings.contains(acf))
1163       {
1164         seqmappings.add(acf);
1165       }
1166     }
1167   }
1168
1169   /**
1170    * Resets this object to its initial state by removing all registered
1171    * listeners, codon mappings, PDB file mappings
1172    */
1173   public void resetAll()
1174   {
1175     if (mappings != null)
1176     {
1177       mappings.clear();
1178     }
1179     if (seqmappings != null)
1180     {
1181       seqmappings.clear();
1182     }
1183     if (sel_listeners != null)
1184     {
1185       sel_listeners.clear();
1186     }
1187     if (listeners != null)
1188     {
1189       listeners.clear();
1190     }
1191     if (commandListeners != null)
1192     {
1193       commandListeners.clear();
1194     }
1195     if (view_listeners != null)
1196     {
1197       view_listeners.clear();
1198     }
1199     if (pdbFileNameId != null)
1200     {
1201       pdbFileNameId.clear();
1202     }
1203     if (pdbIdFileName != null)
1204     {
1205       pdbIdFileName.clear();
1206     }
1207   }
1208
1209   public void addSelectionListener(SelectionListener selecter)
1210   {
1211     if (!sel_listeners.contains(selecter))
1212     {
1213       sel_listeners.add(selecter);
1214     }
1215   }
1216
1217   public void removeSelectionListener(SelectionListener toremove)
1218   {
1219     if (sel_listeners.contains(toremove))
1220     {
1221       sel_listeners.remove(toremove);
1222     }
1223   }
1224
1225   public synchronized void sendSelection(
1226           jalview.datamodel.SequenceGroup selection,
1227           jalview.datamodel.ColumnSelection colsel, HiddenColumns hidden,
1228           SelectionSource source)
1229   {
1230     for (SelectionListener slis : sel_listeners)
1231     {
1232       if (slis != source)
1233       {
1234         slis.selection(selection, colsel, hidden, source);
1235       }
1236     }
1237   }
1238
1239   Vector<AlignmentViewPanelListener> view_listeners = new Vector<>();
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, mapTo,
1352               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 List<AlignedCodonFrame> getSequenceMappings()
1363   {
1364     return seqmappings;
1365   }
1366
1367 }