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