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