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