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