34ca6ba50c716ee020778855fb8356a725832d04
[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, parseSecStr, parseSecStr);
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 (instances == null)
1335       {
1336         return;
1337       }
1338       StructureSelectionManager mnger = (instances.get(jalviewLite));
1339       if (mnger != null)
1340       {
1341         instances.remove(jalviewLite);
1342         try
1343         {
1344           mnger.finalize();
1345         } catch (Throwable x)
1346         {
1347         }
1348       }
1349     }
1350   }
1351
1352   public void registerPDBEntry(PDBEntry pdbentry)
1353   {
1354     if (pdbentry.getFile() != null
1355             && pdbentry.getFile().trim().length() > 0)
1356     {
1357       registerPDBFile(pdbentry.getId(), pdbentry.getFile());
1358     }
1359   }
1360
1361   public void addCommandListener(CommandListener cl)
1362   {
1363     if (!commandListeners.contains(cl))
1364     {
1365       commandListeners.add(cl);
1366     }
1367   }
1368
1369   public boolean hasCommandListener(CommandListener cl)
1370   {
1371     return this.commandListeners.contains(cl);
1372   }
1373
1374   public boolean removeCommandListener(CommandListener l)
1375   {
1376     return commandListeners.remove(l);
1377   }
1378
1379   /**
1380    * Forward a command to any command listeners (except for the command's
1381    * source).
1382    * 
1383    * @param command
1384    *          the command to be broadcast (in its form after being performed)
1385    * @param undo
1386    *          if true, the command was being 'undone'
1387    * @param source
1388    */
1389   public void commandPerformed(CommandI command, boolean undo,
1390           VamsasSource source)
1391   {
1392     for (CommandListener listener : commandListeners)
1393     {
1394       listener.mirrorCommand(command, undo, this, source);
1395     }
1396   }
1397
1398   /**
1399    * Returns a new CommandI representing the given command as mapped to the
1400    * given sequences. If no mapping could be made, or the command is not of a
1401    * mappable kind, returns null.
1402    * 
1403    * @param command
1404    * @param undo
1405    * @param mapTo
1406    * @param gapChar
1407    * @return
1408    */
1409   public CommandI mapCommand(CommandI command, boolean undo,
1410           final AlignmentI mapTo, char gapChar)
1411   {
1412     if (command instanceof EditCommand)
1413     {
1414       return MappingUtils.mapEditCommand((EditCommand) command, undo, mapTo,
1415               gapChar, seqmappings);
1416     }
1417     else if (command instanceof OrderCommand)
1418     {
1419       return MappingUtils.mapOrderCommand((OrderCommand) command, undo,
1420               mapTo, seqmappings);
1421     }
1422     return null;
1423   }
1424
1425   public List<AlignedCodonFrame> getSequenceMappings()
1426   {
1427     return seqmappings;
1428   }
1429
1430 }