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