0e4384164ecf18f494510a886eec5121bee80e85
[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     }
430
431     String targetChainId;
432     for (int s = 0; s < sequenceArray.length; s++)
433     {
434       boolean infChain = true;
435       final SequenceI seq = sequenceArray[s];
436       SequenceI ds = seq;
437       while (ds.getDatasetSequence() != null)
438       {
439         ds = ds.getDatasetSequence();
440       }
441
442       if (targetChainIds != null && targetChainIds[s] != null)
443       {
444         infChain = false;
445         targetChainId = targetChainIds[s];
446       }
447       else if (seq.getName().indexOf("|") > -1)
448       {
449         targetChainId = seq.getName()
450                 .substring(seq.getName().lastIndexOf("|") + 1);
451         if (targetChainId.length() > 1)
452         {
453           if (targetChainId.trim().length() == 0)
454           {
455             targetChainId = " ";
456           }
457           else
458           {
459             // not a valid chain identifier
460             targetChainId = "";
461           }
462         }
463       }
464       else
465       {
466         targetChainId = "";
467       }
468
469       /*
470        * Attempt pairwise alignment of the sequence with each chain in the PDB,
471        * and remember the highest scoring chain
472        */
473       float max = -10;
474       AlignSeq maxAlignseq = null;
475       String maxChainId = " ";
476       PDBChain maxChain = null;
477       boolean first = true;
478       for (PDBChain chain : pdb.getChains())
479       {
480         if (targetChainId.length() > 0 && !targetChainId.equals(chain.id)
481                 && !infChain)
482         {
483           continue; // don't try to map chains don't match.
484         }
485         // TODO: correctly determine sequence type for mixed na/peptide
486         // structures
487         final String type = chain.isNa ? AlignSeq.DNA : AlignSeq.PEP;
488         AlignSeq as = AlignSeq.doGlobalNWAlignment(seq, chain.sequence,
489                 type);
490         // equivalent to:
491         // AlignSeq as = new AlignSeq(sequence[s], chain.sequence, type);
492         // as.calcScoreMatrix();
493         // as.traceAlignment();
494
495         if (first || as.maxscore > max
496                 || (as.maxscore == max && chain.id.equals(targetChainId)))
497         {
498           first = false;
499           maxChain = chain;
500           max = as.maxscore;
501           maxAlignseq = as;
502           maxChainId = chain.id;
503         }
504       }
505       if (maxChain == null)
506       {
507         continue;
508       }
509
510       if (sourceType == DataSourceType.PASTE)
511       {
512         pdbFile = "INLINE" + pdb.getId();
513       }
514
515       List<StructureMapping> seqToStrucMapping = new ArrayList<>();
516       if (isMapUsingSIFTs && seq.isProtein())
517       {
518         if (progress!=null) {
519           progress.setProgressBar(MessageManager
520                 .getString("status.obtaining_mapping_with_sifts"),
521                   progressSessionId);
522         }
523         jalview.datamodel.Mapping sqmpping = maxAlignseq
524                 .getMappingFromS1(false);
525         if (targetChainId != null && !targetChainId.trim().isEmpty())
526         {
527           StructureMapping siftsMapping;
528           try
529           {
530             siftsMapping = getStructureMapping(seq, pdbFile, targetChainId,
531                     pdb, maxChain, sqmpping, maxAlignseq, siftsClient);
532             seqToStrucMapping.add(siftsMapping);
533             maxChain.makeExactMapping(siftsMapping, seq);
534             maxChain.transferRESNUMFeatures(seq, "IEA: SIFTS");// FIXME: is this
535                                                        // "IEA:SIFTS" ?
536             maxChain.transferResidueAnnotation(siftsMapping, null);
537             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
538
539           } catch (SiftsException e)
540           {
541             // fall back to NW alignment
542             System.err.println(e.getMessage());
543             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
544                     targetChainId, maxChain, pdb, maxAlignseq);
545             seqToStrucMapping.add(nwMapping);
546             maxChain.makeExactMapping(maxAlignseq, seq);
547             maxChain.transferRESNUMFeatures(seq, "IEA:Jalview"); // FIXME: is
548                                                                  // this
549                                                         // "IEA:Jalview" ?
550             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
551             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
552           }
553         }
554         else
555         {
556           List<StructureMapping> foundSiftsMappings = new ArrayList<>();
557           for (PDBChain chain : pdb.getChains())
558           {
559             StructureMapping siftsMapping = null;
560             try
561             {
562               siftsMapping = getStructureMapping(seq,
563                       pdbFile, chain.id, pdb, chain, sqmpping, maxAlignseq,
564                       siftsClient);
565               foundSiftsMappings.add(siftsMapping);
566               chain.makeExactMapping(siftsMapping, seq);
567               chain.transferRESNUMFeatures(seq, "IEA: SIFTS");// FIXME: is this
568               // "IEA:SIFTS" ?
569               chain.transferResidueAnnotation(siftsMapping, null);
570             } catch (SiftsException e)
571             {
572               System.err.println(e.getMessage());
573             }
574           }
575           if (!foundSiftsMappings.isEmpty())
576           {
577             seqToStrucMapping.addAll(foundSiftsMappings);
578             ds.addPDBId(sqmpping.getTo().getAllPDBEntries().get(0));
579           }
580           else
581           {
582             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
583                     maxChainId, maxChain, pdb, maxAlignseq);
584             seqToStrucMapping.add(nwMapping);
585             maxChain.transferRESNUMFeatures(seq, null); // FIXME: is this
586                                                         // "IEA:Jalview" ?
587             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
588             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
589           }
590         }
591       }
592       else
593       {
594         if (progress != null)
595         {
596           progress.setProgressBar(MessageManager
597                                   .getString("status.obtaining_mapping_with_nw_alignment"),
598                   progressSessionId);
599         }
600         StructureMapping nwMapping = getNWMappings(seq, pdbFile, maxChainId,
601                 maxChain, pdb, maxAlignseq);
602         seqToStrucMapping.add(nwMapping);
603         ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
604       }
605       if (forStructureView)
606       {
607         mappings.addAll(seqToStrucMapping);
608       }
609       if (progress != null)
610       {
611         progress.setProgressBar(null, progressSessionId);
612       }
613     }
614     return pdb;
615   }
616
617   /**
618    * check if we need to extract secondary structure from given pdbFile and
619    * transfer to sequences
620    * 
621    * @param pdbFile
622    * @param sequenceArray
623    * @return
624    */
625   private boolean isStructureFileProcessed(String pdbFile,
626           SequenceI[] sequenceArray)
627   {
628     boolean parseSecStr = true;
629     if (isPDBFileRegistered(pdbFile))
630     {
631       for (SequenceI sq : sequenceArray)
632       {
633         SequenceI ds = sq;
634         while (ds.getDatasetSequence() != null)
635         {
636           ds = ds.getDatasetSequence();
637         }
638         ;
639         if (ds.getAnnotation() != null)
640         {
641           for (AlignmentAnnotation ala : ds.getAnnotation())
642           {
643             // false if any annotation present from this structure
644             // JBPNote this fails for jmol/chimera view because the *file* is
645             // passed, not the structure data ID -
646             if (PDBfile.isCalcIdForFile(ala, findIdForPDBFile(pdbFile)))
647             {
648               parseSecStr = false;
649             }
650           }
651         }
652       }
653     }
654     return parseSecStr;
655   }
656
657   public void addStructureMapping(StructureMapping sm)
658   {
659     mappings.add(sm);
660   }
661
662   /**
663    * retrieve a mapping for seq from SIFTs using associated DBRefEntry for
664    * uniprot or PDB
665    * 
666    * @param seq
667    * @param pdbFile
668    * @param targetChainId
669    * @param pdb
670    * @param maxChain
671    * @param sqmpping
672    * @param maxAlignseq
673    * @param siftsClient
674    *          client for retrieval of SIFTS mappings for this structure
675    * @return
676    * @throws SiftsException
677    */
678   private StructureMapping getStructureMapping(SequenceI seq,
679           String pdbFile, String targetChainId, StructureFile pdb,
680           PDBChain maxChain, jalview.datamodel.Mapping sqmpping,
681           AlignSeq maxAlignseq, SiftsClient siftsClient) throws SiftsException
682   {
683     StructureMapping curChainMapping = siftsClient
684             .getSiftsStructureMapping(seq, pdbFile, targetChainId);
685     try
686     {
687       PDBChain chain = pdb.findChain(targetChainId);
688       if (chain != null)
689       {
690         chain.transferResidueAnnotation(curChainMapping, null);
691       }
692     } catch (Exception e)
693     {
694       e.printStackTrace();
695     }
696     return curChainMapping;
697   }
698
699   private StructureMapping getNWMappings(SequenceI seq, String pdbFile,
700           String maxChainId, PDBChain maxChain, StructureFile pdb,
701           AlignSeq maxAlignseq)
702   {
703     final StringBuilder mappingDetails = new StringBuilder(128);
704     mappingDetails.append(NEWLINE)
705             .append("Sequence \u27f7 Structure mapping details");
706     mappingDetails.append(NEWLINE);
707     mappingDetails
708             .append("Method: inferred with Needleman & Wunsch alignment");
709     mappingDetails.append(NEWLINE).append("PDB Sequence is :")
710             .append(NEWLINE).append("Sequence = ")
711             .append(maxChain.sequence.getSequenceAsString());
712     mappingDetails.append(NEWLINE).append("No of residues = ")
713             .append(maxChain.residues.size()).append(NEWLINE)
714             .append(NEWLINE);
715     PrintStream ps = new PrintStream(System.out)
716     {
717       @Override
718       public void print(String x)
719       {
720         mappingDetails.append(x);
721       }
722
723       @Override
724       public void println()
725       {
726         mappingDetails.append(NEWLINE);
727       }
728     };
729
730     maxAlignseq.printAlignment(ps);
731
732     mappingDetails.append(NEWLINE).append("PDB start/end ");
733     mappingDetails.append(String.valueOf(maxAlignseq.seq2start))
734             .append(" ");
735     mappingDetails.append(String.valueOf(maxAlignseq.seq2end));
736     mappingDetails.append(NEWLINE).append("SEQ start/end ");
737     mappingDetails
738             .append(String
739                     .valueOf(maxAlignseq.seq1start + (seq.getStart() - 1)))
740             .append(" ");
741     mappingDetails.append(
742             String.valueOf(maxAlignseq.seq1end + (seq.getStart() - 1)));
743     mappingDetails.append(NEWLINE);
744     maxChain.makeExactMapping(maxAlignseq, seq);
745     jalview.datamodel.Mapping sqmpping = maxAlignseq
746             .getMappingFromS1(false);
747     maxChain.transferRESNUMFeatures(seq, null);
748
749     HashMap<Integer, int[]> mapping = new HashMap<>();
750     int resNum = -10000;
751     int index = 0;
752     char insCode = ' ';
753
754     do
755     {
756       Atom tmp = maxChain.atoms.elementAt(index);
757       if ((resNum != tmp.resNumber || insCode != tmp.insCode)
758               && tmp.alignmentMapping != -1)
759       {
760         resNum = tmp.resNumber;
761         insCode = tmp.insCode;
762         if (tmp.alignmentMapping >= -1)
763         {
764           mapping.put(tmp.alignmentMapping + 1,
765                   new int[]
766                   { tmp.resNumber, tmp.atomIndex });
767         }
768       }
769
770       index++;
771     } while (index < maxChain.atoms.size());
772
773     StructureMapping nwMapping = new StructureMapping(seq, pdbFile,
774             pdb.getId(), maxChainId, mapping, mappingDetails.toString());
775     maxChain.transferResidueAnnotation(nwMapping, sqmpping);
776     return nwMapping;
777   }
778
779   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
780   {
781     listeners.removeElement(svl);
782     if (svl instanceof SequenceListener)
783     {
784       for (int i = 0; i < listeners.size(); i++)
785       {
786         if (listeners.elementAt(i) instanceof StructureListener)
787         {
788           ((StructureListener) listeners.elementAt(i))
789                   .releaseReferences(svl);
790         }
791       }
792     }
793
794     if (pdbfiles == null)
795     {
796       return;
797     }
798
799     /*
800      * Remove mappings to the closed listener's PDB files, but first check if
801      * another listener is still interested
802      */
803     List<String> pdbs = new ArrayList<>(Arrays.asList(pdbfiles));
804
805     StructureListener sl;
806     for (int i = 0; i < listeners.size(); i++)
807     {
808       if (listeners.elementAt(i) instanceof StructureListener)
809       {
810         sl = (StructureListener) listeners.elementAt(i);
811         for (String pdbfile : sl.getStructureFiles())
812         {
813           pdbs.remove(pdbfile);
814         }
815       }
816     }
817
818     /*
819      * Rebuild the mappings set, retaining only those which are for 'other' PDB
820      * files
821      */
822     if (pdbs.size() > 0)
823     {
824       List<StructureMapping> tmp = new ArrayList<>();
825       for (StructureMapping sm : mappings)
826       {
827         if (!pdbs.contains(sm.pdbfile))
828         {
829           tmp.add(sm);
830         }
831       }
832
833       mappings = tmp;
834     }
835   }
836
837   /**
838    * Propagate mouseover of a single position in a structure
839    * 
840    * @param pdbResNum
841    * @param chain
842    * @param pdbfile
843    */
844   public void mouseOverStructure(int pdbResNum, String chain,
845           String pdbfile)
846   {
847     AtomSpec atomSpec = new AtomSpec(pdbfile, chain, pdbResNum, 0);
848     List<AtomSpec> atoms = Collections.singletonList(atomSpec);
849     mouseOverStructure(atoms);
850   }
851
852   /**
853    * Propagate mouseover or selection of multiple positions in a structure
854    * 
855    * @param atoms
856    */
857   public void mouseOverStructure(List<AtomSpec> atoms)
858   {
859     if (listeners == null)
860     {
861       // old or prematurely sent event
862       return;
863     }
864     boolean hasSequenceListener = false;
865     for (int i = 0; i < listeners.size(); i++)
866     {
867       if (listeners.elementAt(i) instanceof SequenceListener)
868       {
869         hasSequenceListener = true;
870       }
871     }
872     if (!hasSequenceListener)
873     {
874       return;
875     }
876
877     SearchResultsI results = findAlignmentPositionsForStructurePositions(
878             atoms);
879     for (Object li : listeners)
880     {
881       if (li instanceof SequenceListener)
882       {
883         ((SequenceListener) li).highlightSequence(results);
884       }
885     }
886   }
887
888   /**
889    * Constructs a SearchResults object holding regions (if any) in the Jalview
890    * alignment which have a mapping to the structure viewer positions in the
891    * supplied list
892    * 
893    * @param atoms
894    * @return
895    */
896   public SearchResultsI findAlignmentPositionsForStructurePositions(
897           List<AtomSpec> atoms)
898   {
899     SearchResultsI results = new SearchResults();
900     for (AtomSpec atom : atoms)
901     {
902       SequenceI lastseq = null;
903       int lastipos = -1;
904       for (StructureMapping sm : mappings)
905       {
906         if (sm.pdbfile.equals(atom.getPdbFile())
907                 && sm.pdbchain.equals(atom.getChain()))
908         {
909           int indexpos = sm.getSeqPos(atom.getPdbResNum());
910           if (lastipos != indexpos || lastseq != sm.sequence)
911           {
912             results.addResult(sm.sequence, indexpos, indexpos);
913             lastipos = indexpos;
914             lastseq = sm.sequence;
915             // construct highlighted sequence list
916             for (AlignedCodonFrame acf : seqmappings)
917             {
918               acf.markMappedRegion(sm.sequence, indexpos, results);
919             }
920           }
921         }
922       }
923     }
924     return results;
925   }
926
927   /**
928    * highlight regions associated with a position (indexpos) in seq
929    * 
930    * @param seq
931    *          the sequence that the mouse over occurred on
932    * @param indexpos
933    *          the absolute position being mouseovered in seq (0 to seq.length())
934    * @param seqPos
935    *          the sequence position (if -1, seq.findPosition is called to
936    *          resolve the residue number)
937    */
938   public void mouseOverSequence(SequenceI seq, int indexpos, int seqPos,
939           VamsasSource source)
940   {
941     boolean hasSequenceListeners = handlingVamsasMo
942             || !seqmappings.isEmpty();
943     SearchResultsI results = null;
944     if (seqPos == -1)
945     {
946       seqPos = seq.findPosition(indexpos);
947     }
948     for (int i = 0; i < listeners.size(); i++)
949     {
950       Object listener = listeners.elementAt(i);
951       if (listener == source)
952       {
953         // TODO listener (e.g. SeqPanel) is never == source (AlignViewport)
954         // Temporary fudge with SequenceListener.getVamsasSource()
955         continue;
956       }
957       if (listener instanceof StructureListener)
958       {
959         highlightStructure((StructureListener) listener, seq, seqPos);
960       }
961       else
962       {
963         if (listener instanceof SequenceListener)
964         {
965           final SequenceListener seqListener = (SequenceListener) listener;
966           if (hasSequenceListeners
967                   && seqListener.getVamsasSource() != source)
968           {
969             if (relaySeqMappings)
970             {
971               if (results == null)
972               {
973                 results = MappingUtils.buildSearchResults(seq, seqPos,
974                         seqmappings);
975               }
976               if (handlingVamsasMo)
977               {
978                 results.addResult(seq, seqPos, seqPos);
979
980               }
981               if (!results.isEmpty())
982               {
983                 seqListener.highlightSequence(results);
984               }
985             }
986           }
987         }
988         else if (listener instanceof VamsasListener && !handlingVamsasMo)
989         {
990           ((VamsasListener) listener).mouseOverSequence(seq, indexpos,
991                   source);
992         }
993         else if (listener instanceof SecondaryStructureListener)
994         {
995           ((SecondaryStructureListener) listener).mouseOverSequence(seq,
996                   indexpos, seqPos);
997         }
998       }
999     }
1000   }
1001
1002   /**
1003    * Send suitable messages to a StructureListener to highlight atoms
1004    * corresponding to the given sequence position(s)
1005    * 
1006    * @param sl
1007    * @param seq
1008    * @param positions
1009    */
1010   public void highlightStructure(StructureListener sl, SequenceI seq,
1011           int... positions)
1012   {
1013     if (!sl.isListeningFor(seq))
1014     {
1015       return;
1016     }
1017     int atomNo;
1018     List<AtomSpec> atoms = new ArrayList<>();
1019     for (StructureMapping sm : mappings)
1020     {
1021       if (sm.sequence == seq || sm.sequence == seq.getDatasetSequence()
1022               || (sm.sequence.getDatasetSequence() != null && sm.sequence
1023                       .getDatasetSequence() == seq.getDatasetSequence()))
1024       {
1025         for (int index : positions)
1026         {
1027           atomNo = sm.getAtomNum(index);
1028
1029           if (atomNo > 0)
1030           {
1031             atoms.add(new AtomSpec(sm.pdbfile, sm.pdbchain,
1032                     sm.getPDBResNum(index), atomNo));
1033           }
1034         }
1035       }
1036     }
1037     sl.highlightAtoms(atoms);
1038   }
1039
1040   /**
1041    * true if a mouse over event from an external (ie Vamsas) source is being
1042    * handled
1043    */
1044   boolean handlingVamsasMo = false;
1045
1046   long lastmsg = 0;
1047
1048   /**
1049    * as mouseOverSequence but only route event to SequenceListeners
1050    * 
1051    * @param sequenceI
1052    * @param position
1053    *          in an alignment sequence
1054    */
1055   public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
1056           VamsasSource source)
1057   {
1058     handlingVamsasMo = true;
1059     long msg = sequenceI.hashCode() * (1 + position);
1060     if (lastmsg != msg)
1061     {
1062       lastmsg = msg;
1063       mouseOverSequence(sequenceI, position, -1, source);
1064     }
1065     handlingVamsasMo = false;
1066   }
1067
1068   public Annotation[] colourSequenceFromStructure(SequenceI seq,
1069           String pdbid)
1070   {
1071     return null;
1072     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
1073     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
1074     /*
1075      * Annotation [] annotations = new Annotation[seq.getLength()];
1076      * 
1077      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
1078      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
1079      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
1080      * 
1081      * for (int j = 0; j < mappings.length; j++) {
1082      * 
1083      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
1084      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
1085      * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
1086      * "+mappings[j].pdbfile);
1087      * 
1088      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
1089      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
1090      * 
1091      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
1092      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
1093      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
1094      * mappings[j].pdbfile); }
1095      * 
1096      * annotations[index] = new Annotation("X",null,' ',0,col); } return
1097      * annotations; } } } }
1098      * 
1099      * return annotations;
1100      */
1101   }
1102
1103   public void structureSelectionChanged()
1104   {
1105   }
1106
1107   public void sequenceSelectionChanged()
1108   {
1109   }
1110
1111   public void sequenceColoursChanged(Object source)
1112   {
1113     StructureListener sl;
1114     for (int i = 0; i < listeners.size(); i++)
1115     {
1116       if (listeners.elementAt(i) instanceof StructureListener)
1117       {
1118         sl = (StructureListener) listeners.elementAt(i);
1119         sl.updateColours(source);
1120       }
1121     }
1122   }
1123
1124   public StructureMapping[] getMapping(String pdbfile)
1125   {
1126     List<StructureMapping> tmp = new ArrayList<>();
1127     for (StructureMapping sm : mappings)
1128     {
1129       if (sm.pdbfile.equals(pdbfile))
1130       {
1131         tmp.add(sm);
1132       }
1133     }
1134     return tmp.toArray(new StructureMapping[tmp.size()]);
1135   }
1136
1137   /**
1138    * Returns a readable description of all mappings for the given pdbfile to any
1139    * of the given sequences
1140    * 
1141    * @param pdbfile
1142    * @param seqs
1143    * @return
1144    */
1145   public String printMappings(String pdbfile, List<SequenceI> seqs)
1146   {
1147     if (pdbfile == null || seqs == null || seqs.isEmpty())
1148     {
1149       return "";
1150     }
1151
1152     StringBuilder sb = new StringBuilder(64);
1153     for (StructureMapping sm : mappings)
1154     {
1155       if (sm.pdbfile.equals(pdbfile) && seqs.contains(sm.sequence))
1156       {
1157         sb.append(sm.mappingDetails);
1158         sb.append(NEWLINE);
1159         // separator makes it easier to read multiple mappings
1160         sb.append("=====================");
1161         sb.append(NEWLINE);
1162       }
1163     }
1164     sb.append(NEWLINE);
1165
1166     return sb.toString();
1167   }
1168
1169   /**
1170    * Remove the given mapping
1171    * 
1172    * @param acf
1173    */
1174   public void deregisterMapping(AlignedCodonFrame acf)
1175   {
1176     if (acf != null)
1177     {
1178       boolean removed = seqmappings.remove(acf);
1179       if (removed && seqmappings.isEmpty())
1180       { // debug
1181         System.out.println("All mappings removed");
1182       }
1183     }
1184   }
1185
1186   /**
1187    * Add each of the given codonFrames to the stored set, if not aready present.
1188    * 
1189    * @param mappings
1190    */
1191   public void registerMappings(List<AlignedCodonFrame> mappings)
1192   {
1193     if (mappings != null)
1194     {
1195       for (AlignedCodonFrame acf : mappings)
1196       {
1197         registerMapping(acf);
1198       }
1199     }
1200   }
1201
1202   /**
1203    * Add the given mapping to the stored set, unless already stored.
1204    */
1205   public void registerMapping(AlignedCodonFrame acf)
1206   {
1207     if (acf != null)
1208     {
1209       if (!seqmappings.contains(acf))
1210       {
1211         seqmappings.add(acf);
1212       }
1213     }
1214   }
1215
1216   /**
1217    * Resets this object to its initial state by removing all registered
1218    * listeners, codon mappings, PDB file mappings
1219    */
1220   public void resetAll()
1221   {
1222     if (mappings != null)
1223     {
1224       mappings.clear();
1225     }
1226     if (seqmappings != null)
1227     {
1228       seqmappings.clear();
1229     }
1230     if (sel_listeners != null)
1231     {
1232       sel_listeners.clear();
1233     }
1234     if (listeners != null)
1235     {
1236       listeners.clear();
1237     }
1238     if (commandListeners != null)
1239     {
1240       commandListeners.clear();
1241     }
1242     if (view_listeners != null)
1243     {
1244       view_listeners.clear();
1245     }
1246     if (pdbFileNameId != null)
1247     {
1248       pdbFileNameId.clear();
1249     }
1250     if (pdbIdFileName != null)
1251     {
1252       pdbIdFileName.clear();
1253     }
1254   }
1255
1256   public void addSelectionListener(SelectionListener selecter)
1257   {
1258     if (!sel_listeners.contains(selecter))
1259     {
1260       sel_listeners.add(selecter);
1261     }
1262   }
1263
1264   public void removeSelectionListener(SelectionListener toremove)
1265   {
1266     if (sel_listeners.contains(toremove))
1267     {
1268       sel_listeners.remove(toremove);
1269     }
1270   }
1271
1272   public synchronized void sendSelection(
1273           jalview.datamodel.SequenceGroup selection,
1274           jalview.datamodel.ColumnSelection colsel, HiddenColumns hidden,
1275           SelectionSource source)
1276   {
1277     for (SelectionListener slis : sel_listeners)
1278     {
1279       if (slis != source)
1280       {
1281         slis.selection(selection, colsel, hidden, source);
1282       }
1283     }
1284   }
1285
1286   Vector<AlignmentViewPanelListener> view_listeners = new Vector<>();
1287
1288   public synchronized void sendViewPosition(
1289           jalview.api.AlignmentViewPanel source, int startRes, int endRes,
1290           int startSeq, int endSeq)
1291   {
1292
1293     if (view_listeners != null && view_listeners.size() > 0)
1294     {
1295       Enumeration<AlignmentViewPanelListener> listeners = view_listeners
1296               .elements();
1297       while (listeners.hasMoreElements())
1298       {
1299         AlignmentViewPanelListener slis = listeners.nextElement();
1300         if (slis != source)
1301         {
1302           slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
1303         }
1304         ;
1305       }
1306     }
1307   }
1308
1309   /**
1310    * release all references associated with this manager provider
1311    * 
1312    * @param jalviewLite
1313    */
1314   public static void release(StructureSelectionManagerProvider jalviewLite)
1315   {
1316     // synchronized (instances)
1317     {
1318       if (instances == null)
1319       {
1320         return;
1321       }
1322       StructureSelectionManager mnger = (instances.get(jalviewLite));
1323       if (mnger != null)
1324       {
1325         instances.remove(jalviewLite);
1326         try
1327         {
1328           mnger.finalize();
1329         } catch (Throwable x)
1330         {
1331         }
1332       }
1333     }
1334   }
1335
1336   public void registerPDBEntry(PDBEntry pdbentry)
1337   {
1338     if (pdbentry.getFile() != null
1339             && pdbentry.getFile().trim().length() > 0)
1340     {
1341       registerPDBFile(pdbentry.getId(), pdbentry.getFile());
1342     }
1343   }
1344
1345   public void addCommandListener(CommandListener cl)
1346   {
1347     if (!commandListeners.contains(cl))
1348     {
1349       commandListeners.add(cl);
1350     }
1351   }
1352
1353   public boolean hasCommandListener(CommandListener cl)
1354   {
1355     return this.commandListeners.contains(cl);
1356   }
1357
1358   public boolean removeCommandListener(CommandListener l)
1359   {
1360     return commandListeners.remove(l);
1361   }
1362
1363   /**
1364    * Forward a command to any command listeners (except for the command's
1365    * source).
1366    * 
1367    * @param command
1368    *          the command to be broadcast (in its form after being performed)
1369    * @param undo
1370    *          if true, the command was being 'undone'
1371    * @param source
1372    */
1373   public void commandPerformed(CommandI command, boolean undo,
1374           VamsasSource source)
1375   {
1376     for (CommandListener listener : commandListeners)
1377     {
1378       listener.mirrorCommand(command, undo, this, source);
1379     }
1380   }
1381
1382   /**
1383    * Returns a new CommandI representing the given command as mapped to the
1384    * given sequences. If no mapping could be made, or the command is not of a
1385    * mappable kind, returns null.
1386    * 
1387    * @param command
1388    * @param undo
1389    * @param mapTo
1390    * @param gapChar
1391    * @return
1392    */
1393   public CommandI mapCommand(CommandI command, boolean undo,
1394           final AlignmentI mapTo, char gapChar)
1395   {
1396     if (command instanceof EditCommand)
1397     {
1398       return MappingUtils.mapEditCommand((EditCommand) command, undo, mapTo,
1399               gapChar, seqmappings);
1400     }
1401     else if (command instanceof OrderCommand)
1402     {
1403       return MappingUtils.mapOrderCommand((OrderCommand) command, undo,
1404               mapTo, seqmappings);
1405     }
1406     return null;
1407   }
1408
1409   public List<AlignedCodonFrame> getSequenceMappings()
1410   {
1411     return seqmappings;
1412   }
1413
1414 }