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