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