JAL-4366 1:1 mapping requires exact sequence length match - still not sufficient...
[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       if (isMapUsingSIFTs && seq.isProtein())
602       {
603         if (progress != null)
604         {
605           progress.setProgressBar(
606                   MessageManager
607                           .getString("status.obtaining_mapping_with_sifts"),
608                   progressSessionId);
609         }
610         jalview.datamodel.Mapping sqmpping = maxAlignseq
611                 .getMappingFromS1(false);
612         if (targetChainId != null && !targetChainId.trim().isEmpty())
613         {
614           StructureMapping siftsMapping;
615           try
616           {
617             siftsMapping = getStructureMapping(seq, pdbFile, targetChainId,
618                     pdb, maxChain, sqmpping, maxAlignseq, siftsClient);
619             seqToStrucMapping.add(siftsMapping);
620             maxChain.makeExactMapping(siftsMapping, seq);
621             maxChain.transferRESNUMFeatures(seq, "IEA: SIFTS",
622                     pdb.getId().toLowerCase(Locale.ROOT));
623             maxChain.transferResidueAnnotation(siftsMapping, null);
624             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
625
626           } catch (SiftsException e)
627           {
628             // fall back to NW alignment
629             Console.error(e.getMessage());
630             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
631                     targetChainId, maxChain, pdb, maxAlignseq);
632             seqToStrucMapping.add(nwMapping);
633             maxChain.makeExactMapping(maxAlignseq, seq);
634             maxChain.transferRESNUMFeatures(seq, "IEA:Jalview",
635                     pdb.getId().toLowerCase(Locale.ROOT)); // FIXME: is
636             // this
637             // "IEA:Jalview" ?
638             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
639             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
640           }
641         }
642         else
643         {
644           List<StructureMapping> foundSiftsMappings = new ArrayList<>();
645           for (PDBChain chain : pdb.getChains())
646           {
647             StructureMapping siftsMapping = null;
648             try
649             {
650               siftsMapping = getStructureMapping(seq, pdbFile, chain.id,
651                       pdb, chain, sqmpping, maxAlignseq, siftsClient);
652               foundSiftsMappings.add(siftsMapping);
653               chain.makeExactMapping(siftsMapping, seq);
654               chain.transferRESNUMFeatures(seq, "IEA: SIFTS",
655                       pdb.getId().toLowerCase(Locale.ROOT));// FIXME: is this
656               // "IEA:SIFTS" ?
657               chain.transferResidueAnnotation(siftsMapping, null);
658             } catch (SiftsException e)
659             {
660               jalview.bin.Console.errPrintln(e.getMessage());
661             } catch (Exception e)
662             {
663               jalview.bin.Console.errPrintln(
664                       "Unexpected exception during SIFTS mapping - falling back to NW for this sequence/structure pair");
665               jalview.bin.Console.errPrintln(e.getMessage());
666             }
667           }
668           if (!foundSiftsMappings.isEmpty())
669           {
670             seqToStrucMapping.addAll(foundSiftsMappings);
671             ds.addPDBId(sqmpping.getTo().getAllPDBEntries().get(0));
672           }
673           else
674           {
675             /*
676              * fallback to NeedlemanWunch.
677              */
678             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
679                     maxChainId, maxChain, pdb, maxAlignseq);
680             seqToStrucMapping.add(nwMapping);
681             maxChain.transferRESNUMFeatures(seq, null,
682                     pdb.getId().toLowerCase(Locale.ROOT)); // FIXME: is this
683             // "IEA:Jalview" ?
684             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
685             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
686           }
687         }
688       }
689       else
690       {
691         // Not doing SIFTS
692         // first check if we should use an identity mapping
693         if (idLengthChain != null && maxAlignseq.getS2Coverage() < 0.5)
694         {
695           Console.info(
696                   "Assuming 3Dsi identity mapping between structure and sequence");
697           StructureMapping matchMapping = getIdMappings(seq, pdbFile,
698                   idLengthChain.id, idLengthChain, pdb);
699           seqToStrucMapping.add(matchMapping);
700           ds.addPDBId(idLengthChain.sequence.getAllPDBEntries().get(0));
701           Console.info("Mapping added.");
702         }
703         else
704         {
705           // Construct a needleman wunsch mapping instead.
706           if (progress != null)
707           {
708             progress.setProgressBar(
709                     MessageManager.getString(
710                             "status.obtaining_mapping_with_nw_alignment"),
711                     progressSessionId);
712           }
713           StructureMapping nwMapping = getNWMappings(seq, pdbFile,
714                   maxChainId, maxChain, pdb, maxAlignseq);
715           seqToStrucMapping.add(nwMapping);
716           ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
717         }
718       }
719       if (forStructureView)
720       {
721         for (StructureMapping sm : seqToStrucMapping)
722         {
723           addStructureMapping(sm); // not addAll!
724         }
725       }
726       if (progress != null)
727       {
728         progress.setProgressBar(null, progressSessionId);
729       }
730     }
731     return pdb;
732   }
733
734   /**
735    * check if we need to extract secondary structure from given pdbFile and
736    * transfer to sequences
737    * 
738    * @param pdbFile
739    * @param sequenceArray
740    * @return
741    */
742   private boolean isStructureFileProcessed(String pdbFile,
743           SequenceI[] sequenceArray)
744   {
745     boolean processed = false;
746     if (isPDBFileRegistered(pdbFile))
747     {
748       for (SequenceI sq : sequenceArray)
749       {
750         SequenceI ds = sq;
751         while (ds.getDatasetSequence() != null)
752         {
753           ds = ds.getDatasetSequence();
754         }
755         ;
756         if (ds.getAnnotation() != null)
757         {
758           for (AlignmentAnnotation ala : ds.getAnnotation())
759           {
760             // false if any annotation present from this structure
761             // JBPNote this fails for jmol/chimera view because the *file* is
762             // passed, not the structure data ID -
763             if (PDBfile.isCalcIdForFile(ala, findIdForPDBFile(pdbFile)))
764             {
765               processed = true;
766             }
767           }
768         }
769       }
770     }
771     return processed;
772   }
773
774   public void addStructureMapping(StructureMapping sm)
775   {
776     if (!mappings.contains(sm))
777     {
778       mappings.add(sm);
779     }
780   }
781
782   /**
783    * retrieve a mapping for seq from SIFTs using associated DBRefEntry for
784    * uniprot or PDB
785    * 
786    * @param seq
787    * @param pdbFile
788    * @param targetChainId
789    * @param pdb
790    * @param maxChain
791    * @param sqmpping
792    * @param maxAlignseq
793    * @param siftsClient
794    *          client for retrieval of SIFTS mappings for this structure
795    * @return
796    * @throws SiftsException
797    */
798   private StructureMapping getStructureMapping(SequenceI seq,
799           String pdbFile, String targetChainId, StructureFile pdb,
800           PDBChain maxChain, jalview.datamodel.Mapping sqmpping,
801           AlignSeq maxAlignseq, SiftsClient siftsClient)
802           throws SiftsException
803   {
804     StructureMapping curChainMapping = siftsClient
805             .getSiftsStructureMapping(seq, pdbFile, targetChainId);
806     try
807     {
808       PDBChain chain = pdb.findChain(targetChainId);
809       if (chain != null)
810       {
811         chain.transferResidueAnnotation(curChainMapping, null);
812       }
813     } catch (Exception e)
814     {
815       e.printStackTrace();
816     }
817     return curChainMapping;
818   }
819   
820   /**
821    * construct a mapping based on a pairwise alignment of the sequence and chain
822    * @param seq
823    * @param pdbFile
824    * @param maxChainId
825    * @param maxChain
826    * @param pdb
827    * @param maxAlignseq
828    * @return
829    */
830
831   private StructureMapping getNWMappings(SequenceI seq, String pdbFile,
832           String maxChainId, PDBChain maxChain, StructureFile pdb,
833           AlignSeq maxAlignseq)
834   {
835     final StringBuilder mappingDetails = new StringBuilder(128);
836     mappingDetails.append(NEWLINE)
837             .append("Sequence \u27f7 Structure mapping details");
838     mappingDetails.append(NEWLINE);
839     mappingDetails
840             .append("Method: inferred with Needleman & Wunsch alignment");
841     mappingDetails.append(NEWLINE).append("PDB Sequence is :")
842             .append(NEWLINE).append("Sequence = ")
843             .append(maxChain.sequence.getSequenceAsString());
844     mappingDetails.append(NEWLINE).append("No of residues = ")
845             .append(maxChain.residues.size()).append(NEWLINE)
846             .append(NEWLINE);
847     PrintStream ps = new PrintStream(System.out)
848     {
849       @Override
850       public void print(String x)
851       {
852         mappingDetails.append(x);
853       }
854
855       @Override
856       public void println()
857       {
858         mappingDetails.append(NEWLINE);
859       }
860     };
861
862     maxAlignseq.printAlignment(ps);
863
864     mappingDetails.append(NEWLINE).append("PDB start/end ");
865     mappingDetails.append(String.valueOf(maxAlignseq.seq2start))
866             .append(" ");
867     mappingDetails.append(String.valueOf(maxAlignseq.seq2end));
868     mappingDetails.append(NEWLINE).append("SEQ start/end ");
869     mappingDetails
870             .append(String
871                     .valueOf(maxAlignseq.seq1start + (seq.getStart() - 1)))
872             .append(" ");
873     mappingDetails.append(
874             String.valueOf(maxAlignseq.seq1end + (seq.getStart() - 1)));
875     mappingDetails.append(NEWLINE);
876     maxChain.makeExactMapping(maxAlignseq, seq);
877     jalview.datamodel.Mapping sqmpping = maxAlignseq
878             .getMappingFromS1(false);
879     maxChain.transferRESNUMFeatures(seq, null,
880             pdb.getId().toLowerCase(Locale.ROOT));
881
882     HashMap<Integer, int[]> mapping = new HashMap<>();
883     int resNum = -10000;
884     int index = 0;
885     char insCode = ' ';
886
887     do
888     {
889       Atom tmp = maxChain.atoms.elementAt(index);
890       if ((resNum != tmp.resNumber || insCode != tmp.insCode)
891               && tmp.alignmentMapping != -1)
892       {
893         resNum = tmp.resNumber;
894         insCode = tmp.insCode;
895         if (tmp.alignmentMapping >= -1)
896         {
897           mapping.put(tmp.alignmentMapping + 1,
898                   new int[]
899                   { tmp.resNumber, tmp.atomIndex });
900         }
901       }
902
903       index++;
904     } while (index < maxChain.atoms.size());
905
906     StructureMapping nwMapping = new StructureMapping(seq, pdbFile,
907             pdb.getId(), maxChainId, mapping, mappingDetails.toString());
908     maxChain.transferResidueAnnotation(nwMapping, sqmpping);
909     return nwMapping;
910   }
911   
912   /**
913    * construct a 1:1 mapping using given residue and sequence numbering 
914    * @param seq
915    * @param pdbFile
916    * @param identityChainId
917    * @param identityChain
918    * @param pdb
919    * @return
920    */
921
922   private StructureMapping getIdMappings(SequenceI seq, String pdbFile,
923           String identityChainId, PDBChain identityChain, StructureFile pdb)
924   {
925     final StringBuilder mappingDetails = new StringBuilder(128);
926     mappingDetails.append(NEWLINE)
927             .append("Sequence \u27f7 Structure mapping details");
928     mappingDetails.append(NEWLINE);
929     mappingDetails.append("Method: Matching length 1:1");
930     mappingDetails.append(NEWLINE).append("PDB Sequence is :")
931             .append(NEWLINE).append("Sequence = ")
932             .append(identityChain.sequence.getSequenceAsString());
933     mappingDetails.append(NEWLINE).append("No of residues = ")
934             .append(identityChain.residues.size()).append(NEWLINE)
935             .append(NEWLINE);
936
937     mappingDetails.append(NEWLINE)
938             .append("Aligned Sequence is: " + seq.getDisplayId(true));
939     mappingDetails.append(NEWLINE)
940             .append("Sequence = " + seq.getSequenceAsString());
941
942     int from = Math.max(seq.getStart(),identityChain.sequence.getStart());
943     int to = Math.min(seq.getEnd(), identityChain.sequence.getEnd());
944     jalview.datamodel.Mapping sqmpping = new jalview.datamodel.Mapping(seq,
945             new MapList(new int[]
946             { from,to },
947                     new int[]
948                     { from,to },
949                     1, 1));
950     identityChain.mapChainWith(sqmpping, seq);
951
952     identityChain.transferRESNUMFeatures(seq, null,
953             pdb.getId().toLowerCase(Locale.ROOT));
954
955     // Construct mapping
956     // TODO REFACTOR TO PDBChain as a builder
957     HashMap<Integer, int[]> mapping = new HashMap<>();
958     int resNum = -10000;
959     int index = 0;
960     char insCode = ' ';
961
962     do
963     {
964       Atom tmp = identityChain.atoms.elementAt(index);
965       if ((resNum != tmp.resNumber || insCode != tmp.insCode)
966               && tmp.alignmentMapping != -1)
967       {
968         resNum = tmp.resNumber;
969         insCode = tmp.insCode;
970         if (tmp.alignmentMapping >= -1)
971         {
972           mapping.put(tmp.alignmentMapping + 1,
973                   new int[]
974                   { tmp.resNumber, tmp.atomIndex });
975         }
976       }
977
978       index++;
979     } while (index < identityChain.atoms.size());
980
981     StructureMapping idMapping = new StructureMapping(seq, pdbFile,
982             pdb.getId(), identityChainId, mapping,
983             mappingDetails.toString());
984     identityChain.transferResidueAnnotation(idMapping, sqmpping);
985     return idMapping;
986   }
987
988   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
989   {
990     listeners.removeElement(svl);
991     if (svl instanceof SequenceListener)
992     {
993       for (int i = 0; i < listeners.size(); i++)
994       {
995         if (listeners.elementAt(i) instanceof StructureListener)
996         {
997           ((StructureListener) listeners.elementAt(i))
998                   .releaseReferences(svl);
999         }
1000       }
1001     }
1002
1003     if (pdbfiles == null)
1004     {
1005       return;
1006     }
1007
1008     /*
1009      * Remove mappings to the closed listener's PDB files, but first check if
1010      * another listener is still interested
1011      */
1012     List<String> pdbs = new ArrayList<>(Arrays.asList(pdbfiles));
1013
1014     StructureListener sl;
1015     for (int i = 0; i < listeners.size(); i++)
1016     {
1017       if (listeners.elementAt(i) instanceof StructureListener)
1018       {
1019         sl = (StructureListener) listeners.elementAt(i);
1020         for (String pdbfile : sl.getStructureFiles())
1021         {
1022           pdbs.remove(pdbfile);
1023         }
1024       }
1025     }
1026
1027     /*
1028      * Rebuild the mappings set, retaining only those which are for 'other' PDB
1029      * files
1030      */
1031     if (pdbs.size() > 0)
1032     {
1033       List<StructureMapping> tmp = new ArrayList<>();
1034       for (StructureMapping sm : mappings)
1035       {
1036         if (!pdbs.contains(sm.pdbfile))
1037         {
1038           tmp.add(sm);
1039         }
1040       }
1041
1042       mappings = tmp;
1043     }
1044   }
1045
1046   /**
1047    * hack to highlight a range of positions at once on any structure views
1048    * 
1049    * @param sequenceRef
1050    * @param is
1051    *          - series of int start-end ranges as positions on sequenceRef
1052    * @param i
1053    * @param object
1054    */
1055   public void highlightPositionsOn(SequenceI sequenceRef, int[][] is,
1056           Object source)
1057   {
1058     boolean hasSequenceListeners = handlingVamsasMo
1059             || !seqmappings.isEmpty();
1060     SearchResultsI results = null;
1061     ArrayList<Integer> listOfPositions = new ArrayList<Integer>();
1062     for (int[] s_e : is)
1063     {
1064       for (int p = s_e[0]; p <= s_e[1]; listOfPositions.add(p++))
1065         ;
1066     }
1067     int seqpos[] = new int[listOfPositions.size()];
1068     int i = 0;
1069     for (Integer p : listOfPositions)
1070     {
1071       seqpos[i++] = p;
1072     }
1073
1074     for (i = 0; i < listeners.size(); i++)
1075     {
1076       Object listener = listeners.elementAt(i);
1077       if (listener == source)
1078       {
1079         // TODO listener (e.g. SeqPanel) is never == source (AlignViewport)
1080         // Temporary fudge with SequenceListener.getVamsasSource()
1081         continue;
1082       }
1083       if (listener instanceof StructureListener)
1084       {
1085         highlightStructure((StructureListener) listener, sequenceRef,
1086                 seqpos);
1087       }
1088
1089     }
1090   }
1091
1092   /**
1093    * Propagate mouseover of a single position in a structure
1094    * 
1095    * @param pdbResNum
1096    * @param chain
1097    * @param pdbfile
1098    * @return
1099    */
1100   public String mouseOverStructure(int pdbResNum, String chain,
1101           String pdbfile)
1102   {
1103     AtomSpec atomSpec = new AtomSpec(pdbfile, chain, pdbResNum, 0);
1104     List<AtomSpec> atoms = Collections.singletonList(atomSpec);
1105     return mouseOverStructure(atoms);
1106   }
1107
1108   /**
1109    * Propagate mouseover or selection of multiple positions in a structure
1110    * 
1111    * @param atoms
1112    */
1113   public String mouseOverStructure(List<AtomSpec> atoms)
1114   {
1115     if (listeners == null)
1116     {
1117       // old or prematurely sent event
1118       return null;
1119     }
1120     boolean hasSequenceListener = false;
1121     for (int i = 0; i < listeners.size(); i++)
1122     {
1123       if (listeners.elementAt(i) instanceof SequenceListener)
1124       {
1125         hasSequenceListener = true;
1126       }
1127     }
1128     if (!hasSequenceListener)
1129     {
1130       return null;
1131     }
1132
1133     SearchResultsI results = findAlignmentPositionsForStructurePositions(
1134             atoms);
1135     String result = null;
1136     for (Object li : listeners)
1137     {
1138       if (li instanceof SequenceListener)
1139       {
1140         String s = ((SequenceListener) li).highlightSequence(results);
1141         if (s != null)
1142         {
1143           result = s;
1144         }
1145       }
1146     }
1147     return result;
1148   }
1149
1150   /**
1151    * Constructs a SearchResults object holding regions (if any) in the Jalview
1152    * alignment which have a mapping to the structure viewer positions in the
1153    * supplied list
1154    * 
1155    * @param atoms
1156    * @return
1157    */
1158   public SearchResultsI findAlignmentPositionsForStructurePositions(
1159           List<AtomSpec> atoms)
1160   {
1161     SearchResultsI results = new SearchResults();
1162     for (AtomSpec atom : atoms)
1163     {
1164       SequenceI lastseq = null;
1165       int lastipos = -1;
1166       for (StructureMapping sm : mappings)
1167       {
1168         if (sm.pdbfile.equals(atom.getPdbFile())
1169                 && sm.pdbchain.equals(atom.getChain()))
1170         {
1171           int indexpos = sm.getSeqPos(atom.getPdbResNum());
1172           if (lastipos != indexpos || lastseq != sm.sequence)
1173           {
1174             results.appendResult(sm.sequence, indexpos, indexpos);
1175             lastipos = indexpos;
1176             lastseq = sm.sequence;
1177             // construct highlighted sequence list
1178             for (AlignedCodonFrame acf : seqmappings)
1179             {
1180               acf.markMappedRegion(sm.sequence, indexpos, results);
1181             }
1182           }
1183         }
1184       }
1185     }
1186     return results;
1187   }
1188
1189   /**
1190    * highlight regions associated with a position (indexpos) in seq
1191    * 
1192    * @param seq
1193    *          the sequence that the mouse over occurred on
1194    * @param indexpos
1195    *          the absolute position being mouseovered in seq (0 to seq.length())
1196    * @param seqPos
1197    *          the sequence position (if -1, seq.findPosition is called to
1198    *          resolve the residue number)
1199    */
1200   public void mouseOverSequence(SequenceI seq, int indexpos, int seqPos,
1201           VamsasSource source)
1202   {
1203     boolean hasSequenceListeners = handlingVamsasMo
1204             || !seqmappings.isEmpty();
1205     SearchResultsI results = null;
1206     if (seqPos == -1)
1207     {
1208       seqPos = seq.findPosition(indexpos);
1209     }
1210     for (int i = 0; i < listeners.size(); i++)
1211     {
1212       Object listener = listeners.elementAt(i);
1213       if (listener == source)
1214       {
1215         // TODO listener (e.g. SeqPanel) is never == source (AlignViewport)
1216         // Temporary fudge with SequenceListener.getVamsasSource()
1217         continue;
1218       }
1219       if (listener instanceof StructureListener)
1220       {
1221         highlightStructure((StructureListener) listener, seq, seqPos);
1222       }
1223       else
1224       {
1225         if (listener instanceof SequenceListener)
1226         {
1227           final SequenceListener seqListener = (SequenceListener) listener;
1228           if (hasSequenceListeners
1229                   && seqListener.getVamsasSource() != source)
1230           {
1231             if (relaySeqMappings)
1232             {
1233               if (results == null)
1234               {
1235                 results = MappingUtils.buildSearchResults(seq, seqPos,
1236                         seqmappings);
1237               }
1238               if (handlingVamsasMo)
1239               {
1240                 results.addResult(seq, seqPos, seqPos);
1241
1242               }
1243               if (!results.isEmpty())
1244               {
1245                 seqListener.highlightSequence(results);
1246               }
1247             }
1248           }
1249         }
1250         else if (listener instanceof VamsasListener && !handlingVamsasMo)
1251         {
1252           ((VamsasListener) listener).mouseOverSequence(seq, indexpos,
1253                   source);
1254         }
1255         else if (listener instanceof SecondaryStructureListener)
1256         {
1257           ((SecondaryStructureListener) listener).mouseOverSequence(seq,
1258                   indexpos, seqPos);
1259         }
1260       }
1261     }
1262   }
1263
1264   /**
1265    * Send suitable messages to a StructureListener to highlight atoms
1266    * corresponding to the given sequence position(s)
1267    * 
1268    * @param sl
1269    * @param seq
1270    * @param positions
1271    */
1272   public void highlightStructure(StructureListener sl, SequenceI seq,
1273           int... positions)
1274   {
1275     if (!sl.isListeningFor(seq))
1276     {
1277       return;
1278     }
1279     int atomNo;
1280     List<AtomSpec> atoms = new ArrayList<>();
1281     for (StructureMapping sm : mappings)
1282     {
1283       if (sm.sequence == seq || sm.sequence == seq.getDatasetSequence()
1284               || (sm.sequence.getDatasetSequence() != null && sm.sequence
1285                       .getDatasetSequence() == seq.getDatasetSequence()))
1286       {
1287         for (int index : positions)
1288         {
1289           atomNo = sm.getAtomNum(index);
1290
1291           if (atomNo > 0)
1292           {
1293             atoms.add(new AtomSpec(sm.pdbfile, sm.pdbchain,
1294                     sm.getPDBResNum(index), atomNo));
1295           }
1296         }
1297       }
1298     }
1299     sl.highlightAtoms(atoms);
1300   }
1301
1302   public void highlightStructureRegionsFor(StructureListener sl,
1303           SequenceI[] seqs, int... columns)
1304   {
1305     List<SequenceI> to_highlight = new ArrayList<SequenceI>();
1306     for (SequenceI seq : seqs)
1307     {
1308       if (sl.isListeningFor(seq))
1309       {
1310         to_highlight.add(seq);
1311       }
1312     }
1313     if (to_highlight.size() == 0)
1314     {
1315       return;
1316     }
1317     List<AtomSpec> atoms = new ArrayList<>();
1318     for (SequenceI seq : to_highlight)
1319     {
1320       int atomNo;
1321       for (StructureMapping sm : mappings)
1322       {
1323         if (sm.sequence == seq || sm.sequence == seq.getDatasetSequence()
1324                 || (sm.sequence.getDatasetSequence() != null && sm.sequence
1325                         .getDatasetSequence() == seq.getDatasetSequence()))
1326         {
1327
1328           for (int i = 0; i < columns.length; i += 2)
1329           {
1330             ContiguousI positions = seq.findPositions(columns[i] + 1,
1331                     columns[i + 1] + 1);
1332             if (positions == null)
1333             {
1334               continue;
1335             }
1336             for (int index = positions.getBegin(); index <= positions
1337                     .getEnd(); index++)
1338             {
1339
1340               atomNo = sm.getAtomNum(index);
1341
1342               if (atomNo > 0)
1343               {
1344                 atoms.add(new AtomSpec(sm.pdbfile, sm.pdbchain,
1345                         sm.getPDBResNum(index), atomNo));
1346               }
1347             }
1348           }
1349         }
1350       }
1351       if (atoms.size() > 0)
1352       {
1353         sl.highlightAtoms(atoms);
1354       }
1355     }
1356   }
1357
1358   /**
1359    * true if a mouse over event from an external (ie Vamsas) source is being
1360    * handled
1361    */
1362   boolean handlingVamsasMo = false;
1363
1364   long lastmsg = 0;
1365
1366   /**
1367    * as mouseOverSequence but only route event to SequenceListeners
1368    * 
1369    * @param sequenceI
1370    * @param position
1371    *          in an alignment sequence
1372    */
1373   public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
1374           VamsasSource source)
1375   {
1376     handlingVamsasMo = true;
1377     long msg = sequenceI.hashCode() * (1 + position);
1378     if (lastmsg != msg)
1379     {
1380       lastmsg = msg;
1381       mouseOverSequence(sequenceI, position, -1, source);
1382     }
1383     handlingVamsasMo = false;
1384   }
1385
1386   public Annotation[] colourSequenceFromStructure(SequenceI seq,
1387           String pdbid)
1388   {
1389     return null;
1390     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
1391     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
1392     /*
1393      * Annotation [] annotations = new Annotation[seq.getLength()];
1394      * 
1395      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
1396      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
1397      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
1398      * 
1399      * for (int j = 0; j < mappings.length; j++) {
1400      * 
1401      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
1402      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
1403      * jalview.bin.Console.outPrintln(pdbid+" "+mappings[j].getPdbId() +"
1404      * "+mappings[j].pdbfile);
1405      * 
1406      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
1407      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
1408      * 
1409      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
1410      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
1411      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
1412      * mappings[j].pdbfile); }
1413      * 
1414      * annotations[index] = new Annotation("X",null,' ',0,col); } return
1415      * annotations; } } } }
1416      * 
1417      * return annotations;
1418      */
1419   }
1420
1421   public void structureSelectionChanged()
1422   {
1423   }
1424
1425   public void sequenceSelectionChanged()
1426   {
1427   }
1428
1429   public void sequenceColoursChanged(Object source)
1430   {
1431     StructureListener sl;
1432     for (int i = 0; i < listeners.size(); i++)
1433     {
1434       if (listeners.elementAt(i) instanceof StructureListener)
1435       {
1436         sl = (StructureListener) listeners.elementAt(i);
1437         sl.updateColours(source);
1438       }
1439     }
1440   }
1441
1442   public StructureMapping[] getMapping(String pdbfile)
1443   {
1444     List<StructureMapping> tmp = new ArrayList<>();
1445     for (StructureMapping sm : mappings)
1446     {
1447       if (sm.pdbfile.equals(pdbfile))
1448       {
1449         tmp.add(sm);
1450       }
1451     }
1452     return tmp.toArray(new StructureMapping[tmp.size()]);
1453   }
1454
1455   /**
1456    * Returns a readable description of all mappings for the given pdbfile to any
1457    * of the given sequences
1458    * 
1459    * @param pdbfile
1460    * @param seqs
1461    * @return
1462    */
1463   public String printMappings(String pdbfile, List<SequenceI> seqs)
1464   {
1465     if (pdbfile == null || seqs == null || seqs.isEmpty())
1466     {
1467       return "";
1468     }
1469
1470     StringBuilder sb = new StringBuilder(64);
1471     for (StructureMapping sm : mappings)
1472     {
1473       if (Platform.pathEquals(sm.pdbfile, pdbfile)
1474               && seqs.contains(sm.sequence))
1475       {
1476         sb.append(sm.mappingDetails);
1477         sb.append(NEWLINE);
1478         // separator makes it easier to read multiple mappings
1479         sb.append("=====================");
1480         sb.append(NEWLINE);
1481       }
1482     }
1483     sb.append(NEWLINE);
1484
1485     return sb.toString();
1486   }
1487
1488   /**
1489    * Remove the given mapping
1490    * 
1491    * @param acf
1492    */
1493   public void deregisterMapping(AlignedCodonFrame acf)
1494   {
1495     if (acf != null)
1496     {
1497       boolean removed = seqmappings.remove(acf);
1498       if (removed && seqmappings.isEmpty())
1499       { // debug
1500         jalview.bin.Console.outPrintln("All mappings removed");
1501       }
1502     }
1503   }
1504
1505   /**
1506    * Add each of the given codonFrames to the stored set, if not aready present.
1507    * 
1508    * @param mappings
1509    */
1510   public void registerMappings(List<AlignedCodonFrame> mappings)
1511   {
1512     if (mappings != null)
1513     {
1514       for (AlignedCodonFrame acf : mappings)
1515       {
1516         registerMapping(acf);
1517       }
1518     }
1519   }
1520
1521   /**
1522    * Add the given mapping to the stored set, unless already stored.
1523    */
1524   public void registerMapping(AlignedCodonFrame acf)
1525   {
1526     if (acf != null)
1527     {
1528       if (!seqmappings.contains(acf))
1529       {
1530         seqmappings.add(acf);
1531       }
1532     }
1533   }
1534
1535   /**
1536    * Resets this object to its initial state by removing all registered
1537    * listeners, codon mappings, PDB file mappings
1538    */
1539   public void resetAll()
1540   {
1541     if (mappings != null)
1542     {
1543       mappings.clear();
1544     }
1545     if (seqmappings != null)
1546     {
1547       seqmappings.clear();
1548     }
1549     if (sel_listeners != null)
1550     {
1551       sel_listeners.clear();
1552     }
1553     if (listeners != null)
1554     {
1555       listeners.clear();
1556     }
1557     if (commandListeners != null)
1558     {
1559       commandListeners.clear();
1560     }
1561     if (view_listeners != null)
1562     {
1563       view_listeners.clear();
1564     }
1565     if (pdbFileNameId != null)
1566     {
1567       pdbFileNameId.clear();
1568     }
1569     if (pdbIdFileName != null)
1570     {
1571       pdbIdFileName.clear();
1572     }
1573   }
1574
1575   public void addSelectionListener(SelectionListener selecter)
1576   {
1577     if (!sel_listeners.contains(selecter))
1578     {
1579       sel_listeners.add(selecter);
1580     }
1581   }
1582
1583   public void removeSelectionListener(SelectionListener toremove)
1584   {
1585     if (sel_listeners.contains(toremove))
1586     {
1587       sel_listeners.remove(toremove);
1588     }
1589   }
1590
1591   public synchronized void sendSelection(
1592           jalview.datamodel.SequenceGroup selection,
1593           jalview.datamodel.ColumnSelection colsel, HiddenColumns hidden,
1594           SelectionSource source)
1595   {
1596     for (SelectionListener slis : sel_listeners)
1597     {
1598       if (slis != source)
1599       {
1600         slis.selection(selection, colsel, hidden, source);
1601       }
1602     }
1603   }
1604
1605   Vector<AlignmentViewPanelListener> view_listeners = new Vector<>();
1606
1607   public synchronized void sendViewPosition(
1608           jalview.api.AlignmentViewPanel source, int startRes, int endRes,
1609           int startSeq, int endSeq)
1610   {
1611
1612     if (view_listeners != null && view_listeners.size() > 0)
1613     {
1614       Enumeration<AlignmentViewPanelListener> listeners = view_listeners
1615               .elements();
1616       while (listeners.hasMoreElements())
1617       {
1618         AlignmentViewPanelListener slis = listeners.nextElement();
1619         if (slis != source)
1620         {
1621           slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
1622         }
1623         ;
1624       }
1625     }
1626   }
1627
1628   /**
1629    * release all references associated with this manager provider
1630    * 
1631    * @param jalviewLite
1632    */
1633   public static void release(StructureSelectionManagerProvider jalviewLite)
1634   {
1635     // synchronized (instances)
1636     {
1637       if (instances == null)
1638       {
1639         return;
1640       }
1641       StructureSelectionManager mnger = (instances.get(jalviewLite));
1642       if (mnger != null)
1643       {
1644         instances.remove(jalviewLite);
1645         try
1646         {
1647           /* bsoares 2019-03-20 finalize deprecated, no apparent external
1648            * resources to close
1649            */
1650           // mnger.finalize();
1651         } catch (Throwable x)
1652         {
1653         }
1654       }
1655     }
1656   }
1657
1658   public void registerPDBEntry(PDBEntry pdbentry)
1659   {
1660     if (pdbentry.getFile() != null
1661             && pdbentry.getFile().trim().length() > 0)
1662     {
1663       registerPDBFile(pdbentry.getId(), pdbentry.getFile());
1664     }
1665   }
1666
1667   public void addCommandListener(CommandListener cl)
1668   {
1669     if (!commandListeners.contains(cl))
1670     {
1671       commandListeners.add(cl);
1672     }
1673   }
1674
1675   public boolean hasCommandListener(CommandListener cl)
1676   {
1677     return this.commandListeners.contains(cl);
1678   }
1679
1680   public boolean removeCommandListener(CommandListener l)
1681   {
1682     return commandListeners.remove(l);
1683   }
1684
1685   /**
1686    * Forward a command to any command listeners (except for the command's
1687    * source).
1688    * 
1689    * @param command
1690    *          the command to be broadcast (in its form after being performed)
1691    * @param undo
1692    *          if true, the command was being 'undone'
1693    * @param source
1694    */
1695   public void commandPerformed(CommandI command, boolean undo,
1696           VamsasSource source)
1697   {
1698     for (CommandListener listener : commandListeners)
1699     {
1700       listener.mirrorCommand(command, undo, this, source);
1701     }
1702   }
1703
1704   /**
1705    * Returns a new CommandI representing the given command as mapped to the
1706    * given sequences. If no mapping could be made, or the command is not of a
1707    * mappable kind, returns null.
1708    * 
1709    * @param command
1710    * @param undo
1711    * @param mapTo
1712    * @param gapChar
1713    * @return
1714    */
1715   public CommandI mapCommand(CommandI command, boolean undo,
1716           final AlignmentI mapTo, char gapChar)
1717   {
1718     if (command instanceof EditCommand)
1719     {
1720       return MappingUtils.mapEditCommand((EditCommand) command, undo, mapTo,
1721               gapChar, seqmappings);
1722     }
1723     else if (command instanceof OrderCommand)
1724     {
1725       return MappingUtils.mapOrderCommand((OrderCommand) command, undo,
1726               mapTo, seqmappings);
1727     }
1728     return null;
1729   }
1730
1731   public List<AlignedCodonFrame> getSequenceMappings()
1732   {
1733     return seqmappings;
1734   }
1735
1736   /**
1737    * quick and dirty route to just highlight all structure positions for a range
1738    * of columns
1739    * 
1740    * @param sequencesArray
1741    * @param is
1742    *          start-end columns on sequencesArray
1743    * @param source
1744    *          origin parent AlignmentPanel
1745    */
1746   public void highlightPositionsOnMany(SequenceI[] sequencesArray, int[] is,
1747           Object source)
1748   {
1749     for (int i = 0; i < listeners.size(); i++)
1750     {
1751       Object listener = listeners.elementAt(i);
1752       if (listener == source)
1753       {
1754         // TODO listener (e.g. SeqPanel) is never == source (AlignViewport)
1755         // Temporary fudge with SequenceListener.getVamsasSource()
1756         continue;
1757       }
1758       if (listener instanceof StructureListener)
1759       {
1760         highlightStructureRegionsFor((StructureListener) listener,
1761                 sequencesArray, is);
1762       }
1763     }
1764   }
1765
1766   public Map<String, String> getPdbFileNameIdMap()
1767   {
1768     return pdbFileNameId;
1769   }
1770
1771   public Map<String, String> getPdbIdFileNameMap()
1772   {
1773     return pdbIdFileName;
1774   }
1775
1776 }