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