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