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