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