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