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