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