bda269c8bd8f700e598334a94a25ff228c919ae1
[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.SearchResultsI;
35 import jalview.datamodel.SequenceI;
36 import jalview.ext.jmol.JmolParser;
37 import jalview.gui.IProgressIndicator;
38 import jalview.io.DataSourceType;
39 import jalview.io.StructureFile;
40 import jalview.util.MappingUtils;
41 import jalview.util.MessageManager;
42 import jalview.ws.phyre2.Phyre2Client;
43 import jalview.ws.sifts.SiftsClient;
44 import jalview.ws.sifts.SiftsException;
45 import jalview.ws.sifts.SiftsSettings;
46
47 import java.io.PrintStream;
48 import java.util.ArrayList;
49 import java.util.Arrays;
50 import java.util.Collections;
51 import java.util.Enumeration;
52 import java.util.HashMap;
53 import java.util.IdentityHashMap;
54 import java.util.List;
55 import java.util.Map;
56 import java.util.Vector;
57
58 import MCview.Atom;
59 import MCview.PDBChain;
60 import MCview.PDBfile;
61
62 public class StructureSelectionManager
63 {
64   public final static String NEWLINE = System.lineSeparator();
65
66   static IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> instances;
67
68   private List<StructureMapping> mappings = new ArrayList<StructureMapping>();
69
70   private boolean processSecondaryStructure = false;
71
72   private boolean secStructServices = false;
73
74   private boolean addTempFacAnnot = false;
75
76   private IProgressIndicator progressIndicator;
77
78   private SiftsClient siftsClient = null;
79
80   private long progressSessionId;
81
82   private boolean mappingForPhyre2Model;
83
84   /*
85    * Set of any registered mappings between (dataset) sequences.
86    */
87   private List<AlignedCodonFrame> seqmappings = new ArrayList<AlignedCodonFrame>();
88
89   private List<CommandListener> commandListeners = new ArrayList<CommandListener>();
90
91   private List<SelectionListener> sel_listeners = new ArrayList<SelectionListener>();
92
93   /**
94    * @return true if will try to use external services for processing secondary
95    *         structure
96    */
97   public boolean isSecStructServices()
98   {
99     return secStructServices;
100   }
101
102   /**
103    * control use of external services for processing secondary structure
104    * 
105    * @param secStructServices
106    */
107   public void setSecStructServices(boolean secStructServices)
108   {
109     this.secStructServices = secStructServices;
110   }
111
112   /**
113    * flag controlling addition of any kind of structural annotation
114    * 
115    * @return true if temperature factor annotation will be added
116    */
117   public boolean isAddTempFacAnnot()
118   {
119     return addTempFacAnnot;
120   }
121
122   /**
123    * set flag controlling addition of structural annotation
124    * 
125    * @param addTempFacAnnot
126    */
127   public void setAddTempFacAnnot(boolean addTempFacAnnot)
128   {
129     this.addTempFacAnnot = addTempFacAnnot;
130   }
131
132   /**
133    * 
134    * @return if true, the structure manager will attempt to add secondary
135    *         structure lines for unannotated sequences
136    */
137
138   public boolean isProcessSecondaryStructure()
139   {
140     return processSecondaryStructure;
141   }
142
143   /**
144    * Control whether structure manager will try to annotate mapped sequences
145    * with secondary structure from PDB data.
146    * 
147    * @param enable
148    */
149   public void setProcessSecondaryStructure(boolean enable)
150   {
151     processSecondaryStructure = enable;
152   }
153
154   /**
155    * debug function - write all mappings to stdout
156    */
157   public void reportMapping()
158   {
159     if (mappings.isEmpty())
160     {
161       System.err.println("reportMapping: No PDB/Sequence mappings.");
162     }
163     else
164     {
165       System.err.println("reportMapping: There are " + mappings.size()
166               + " mappings.");
167       int i = 0;
168       for (StructureMapping sm : mappings)
169       {
170         System.err.println("mapping " + i++ + " : " + sm.pdbfile);
171       }
172     }
173   }
174
175   /**
176    * map between the PDB IDs (or structure identifiers) used by Jalview and the
177    * absolute filenames for PDB data that corresponds to it
178    */
179   Map<String, String> pdbIdFileName = new HashMap<String, String>();
180
181   Map<String, String> pdbFileNameId = new HashMap<String, String>();
182
183   public void registerPDBFile(String idForFile, String absoluteFile)
184   {
185     pdbIdFileName.put(idForFile, absoluteFile);
186     pdbFileNameId.put(absoluteFile, idForFile);
187   }
188
189   public String findIdForPDBFile(String idOrFile)
190   {
191     String id = pdbFileNameId.get(idOrFile);
192     return id;
193   }
194
195   public String findFileForPDBId(String idOrFile)
196   {
197     String id = pdbIdFileName.get(idOrFile);
198     return id;
199   }
200
201   public boolean isPDBFileRegistered(String idOrFile)
202   {
203     return pdbFileNameId.containsKey(idOrFile)
204             || pdbIdFileName.containsKey(idOrFile);
205   }
206
207   private static StructureSelectionManager nullProvider = null;
208
209   public static StructureSelectionManager getStructureSelectionManager(
210           StructureSelectionManagerProvider context)
211   {
212     if (context == null)
213     {
214       if (nullProvider == null)
215       {
216         if (instances != null)
217         {
218           throw new Error(
219                   MessageManager
220                           .getString("error.implementation_error_structure_selection_manager_null"),
221                   new NullPointerException(MessageManager
222                           .getString("exception.ssm_context_is_null")));
223         }
224         else
225         {
226           nullProvider = new StructureSelectionManager();
227         }
228         return nullProvider;
229       }
230     }
231     if (instances == null)
232     {
233       instances = new java.util.IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager>();
234     }
235     StructureSelectionManager instance = instances.get(context);
236     if (instance == null)
237     {
238       if (nullProvider != null)
239       {
240         instance = nullProvider;
241       }
242       else
243       {
244         instance = new StructureSelectionManager();
245       }
246       instances.put(context, instance);
247     }
248     return instance;
249   }
250
251   /**
252    * flag controlling whether SeqMappings are relayed from received sequence
253    * mouse over events to other sequences
254    */
255   boolean relaySeqMappings = true;
256
257   /**
258    * Enable or disable relay of seqMapping events to other sequences. You might
259    * want to do this if there are many sequence mappings and the host computer
260    * is slow
261    * 
262    * @param relay
263    */
264   public void setRelaySeqMappings(boolean relay)
265   {
266     relaySeqMappings = relay;
267   }
268
269   /**
270    * get the state of the relay seqMappings flag.
271    * 
272    * @return true if sequence mouse overs are being relayed to other mapped
273    *         sequences
274    */
275   public boolean isRelaySeqMappingsEnabled()
276   {
277     return relaySeqMappings;
278   }
279
280   Vector listeners = new Vector();
281
282   /**
283    * register a listener for alignment sequence mouseover events
284    * 
285    * @param svl
286    */
287   public void addStructureViewerListener(Object svl)
288   {
289     if (!listeners.contains(svl))
290     {
291       listeners.addElement(svl);
292     }
293   }
294
295   /**
296    * Returns the file name for a mapped PDB id (or null if not mapped).
297    * 
298    * @param pdbid
299    * @return
300    */
301   public String alreadyMappedToFile(String pdbid)
302   {
303     for (StructureMapping sm : mappings)
304     {
305       if (sm.getPdbId().equals(pdbid))
306       {
307         return sm.pdbfile;
308       }
309     }
310     return null;
311   }
312
313   /**
314    * Import structure data and register a structure mapping for broadcasting
315    * colouring, mouseovers and selection events (convenience wrapper).
316    * 
317    * @param sequence
318    *          - one or more sequences to be mapped to pdbFile
319    * @param targetChains
320    *          - optional chain specification for mapping each sequence to pdb
321    *          (may be nill, individual elements may be nill)
322    * @param pdbFile
323    *          - structure data resource
324    * @param protocol
325    *          - how to resolve data from resource
326    * @return null or the structure data parsed as a pdb file
327    */
328   synchronized public StructureFile setMapping(SequenceI[] sequence,
329           String[] targetChains, String pdbFile, DataSourceType protocol)
330   {
331     return setMapping(true, sequence, targetChains, pdbFile, protocol);
332   }
333
334   /**
335    * create sequence structure mappings between each sequence and the given
336    * pdbFile (retrieved via the given protocol).
337    * 
338    * @param forStructureView
339    *          when true, record the mapping for use in mouseOvers
340    * 
341    * @param sequenceArray
342    *          - one or more sequences to be mapped to pdbFile
343    * @param targetChainIds
344    *          - optional chain specification for mapping each sequence to pdb
345    *          (may be nill, individual elements may be nill)
346    * @param pdbFile
347    *          - structure data resource
348    * @param 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       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       int 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 (!isMappingForPhyre2Model() && 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           } catch (Exception e)
537           {
538             e.printStackTrace();
539           }
540         }
541         else
542         {
543           List<StructureMapping> foundSiftsMappings = new ArrayList<StructureMapping>();
544           for (PDBChain chain : pdb.getChains())
545           {
546             try
547             {
548               StructureMapping siftsMapping = getStructureMapping(seq,
549                       pdbFile, chain.id, pdb, chain, sqmpping, maxAlignseq);
550               foundSiftsMappings.add(siftsMapping);
551             } catch (SiftsException e)
552             {
553               System.err.println(e.getMessage());
554             } catch (Exception e)
555             {
556               e.printStackTrace();
557             }
558           }
559           if (!foundSiftsMappings.isEmpty())
560           {
561             seqToStrucMapping.addAll(foundSiftsMappings);
562             maxChain.makeExactMapping(maxAlignseq, seq);
563             maxChain.transferRESNUMFeatures(seq, null);// FIXME: is this
564                                                        // "IEA:SIFTS" ?
565             maxChain.transferResidueAnnotation(foundSiftsMappings.get(0),
566                     sqmpping);
567             ds.addPDBId(sqmpping.getTo().getAllPDBEntries().get(0));
568           }
569           else
570           {
571             StructureMapping nwMapping = getNWMappings(seq, pdbFile,
572                     maxChainId, maxChain, pdb, maxAlignseq);
573             seqToStrucMapping.add(nwMapping);
574             maxChain.transferRESNUMFeatures(seq, null); // FIXME: is this
575                                                         // "IEA:Jalview" ?
576             maxChain.transferResidueAnnotation(nwMapping, sqmpping);
577             ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
578           }
579         }
580       }
581       else if (isMappingForPhyre2Model())
582       {
583         setProgressBar(null);
584         setProgressBar(MessageManager
585                 .getString("status.obtaining_mapping_with_phyre2_template_alignment"));
586         StructureMapping phyre2ModelMapping = new Phyre2Client(pdb)
587                 .getStructureMapping(seq, pdbFile, " ");
588
589         seqToStrucMapping.add(phyre2ModelMapping);
590         ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
591       }
592       else
593       {
594         setProgressBar(null);
595         setProgressBar(MessageManager
596                 .getString("status.obtaining_mapping_with_nw_alignment"));
597         StructureMapping nwMapping = getNWMappings(seq, pdbFile,
598                 maxChainId, maxChain, pdb, maxAlignseq);
599         seqToStrucMapping.add(nwMapping);
600         ds.addPDBId(maxChain.sequence.getAllPDBEntries().get(0));
601
602       }
603
604       if (forStructureView)
605       {
606         mappings.addAll(seqToStrucMapping);
607       }
608     }
609     return pdb;
610   }
611
612   private boolean isCIFFile(String filename)
613   {
614     String fileExt = filename.substring(filename.lastIndexOf(".") + 1,
615             filename.length());
616     return "cif".equalsIgnoreCase(fileExt);
617   }
618
619   /**
620    * retrieve a mapping for seq from SIFTs using associated DBRefEntry for
621    * uniprot or PDB
622    * 
623    * @param seq
624    * @param pdbFile
625    * @param targetChainId
626    * @param pdb
627    * @param maxChain
628    * @param sqmpping
629    * @param maxAlignseq
630    * @return
631    * @throws SiftsException
632    */
633   private StructureMapping getStructureMapping(SequenceI seq,
634           String pdbFile, String targetChainId, StructureFile pdb,
635           PDBChain maxChain, jalview.datamodel.Mapping sqmpping,
636           AlignSeq maxAlignseq) throws Exception
637   {
638     StructureMapping curChainMapping = siftsClient
639             .getStructureMapping(seq, pdbFile, targetChainId);
640     try
641     {
642       PDBChain chain = pdb.findChain(targetChainId);
643       if (chain != null)
644       {
645         chain.transferResidueAnnotation(curChainMapping, sqmpping);
646       }
647     } catch (Exception e)
648     {
649       e.printStackTrace();
650     }
651     return curChainMapping;
652   }
653
654   private StructureMapping getNWMappings(SequenceI seq, String pdbFile,
655           String maxChainId, PDBChain maxChain, StructureFile pdb,
656           AlignSeq maxAlignseq)
657   {
658     final StringBuilder mappingDetails = new StringBuilder(128);
659     mappingDetails.append(NEWLINE).append(
660             "Sequence \u27f7 Structure mapping details");
661     mappingDetails.append(NEWLINE);
662     mappingDetails
663             .append("Method: inferred with Needleman & Wunsch alignment");
664     mappingDetails.append(NEWLINE).append("PDB Sequence is :")
665             .append(NEWLINE).append("Sequence = ")
666             .append(maxChain.sequence.getSequenceAsString());
667     mappingDetails.append(NEWLINE).append("No of residues = ")
668             .append(maxChain.residues.size()).append(NEWLINE)
669             .append(NEWLINE);
670     PrintStream ps = new PrintStream(System.out)
671     {
672       @Override
673       public void print(String x)
674       {
675         mappingDetails.append(x);
676       }
677
678       @Override
679       public void println()
680       {
681         mappingDetails.append(NEWLINE);
682       }
683     };
684
685     maxAlignseq.printAlignment(ps);
686
687     mappingDetails.append(NEWLINE).append("PDB start/end ");
688     mappingDetails.append(String.valueOf(maxAlignseq.seq2start))
689             .append(" ");
690     mappingDetails.append(String.valueOf(maxAlignseq.seq2end));
691     mappingDetails.append(NEWLINE).append("SEQ start/end ");
692     mappingDetails.append(
693             String.valueOf(maxAlignseq.seq1start + (seq.getStart() - 1)))
694             .append(" ");
695     mappingDetails.append(String.valueOf(maxAlignseq.seq1end
696             + (seq.getStart() - 1)));
697     mappingDetails.append(NEWLINE);
698     maxChain.makeExactMapping(maxAlignseq, seq);
699     jalview.datamodel.Mapping sqmpping = maxAlignseq
700             .getMappingFromS1(false);
701     maxChain.transferRESNUMFeatures(seq, null);
702
703     HashMap<Integer, int[]> mapping = new HashMap<Integer, int[]>();
704     int resNum = -10000;
705     int index = 0;
706     char insCode = ' ';
707
708     do
709     {
710       Atom tmp = maxChain.atoms.elementAt(index);
711       if ((resNum != tmp.resNumber || insCode != tmp.insCode)
712               && tmp.alignmentMapping != -1)
713       {
714         resNum = tmp.resNumber;
715         insCode = tmp.insCode;
716         if (tmp.alignmentMapping >= -1)
717         {
718           mapping.put(tmp.alignmentMapping + 1, new int[] { tmp.resNumber,
719               tmp.atomIndex });
720         }
721       }
722
723       index++;
724     } while (index < maxChain.atoms.size());
725
726     StructureMapping nwMapping = new StructureMapping(seq, pdbFile,
727             pdb.getId(), maxChainId, mapping, mappingDetails.toString());
728     maxChain.transferResidueAnnotation(nwMapping, sqmpping);
729     return nwMapping;
730   }
731
732   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
733   {
734     listeners.removeElement(svl);
735     if (svl instanceof SequenceListener)
736     {
737       for (int i = 0; i < listeners.size(); i++)
738       {
739         if (listeners.elementAt(i) instanceof StructureListener)
740         {
741           ((StructureListener) listeners.elementAt(i))
742                   .releaseReferences(svl);
743         }
744       }
745     }
746
747     if (pdbfiles == null)
748     {
749       return;
750     }
751
752     /*
753      * Remove mappings to the closed listener's PDB files, but first check if
754      * another listener is still interested
755      */
756     List<String> pdbs = new ArrayList<String>(Arrays.asList(pdbfiles));
757
758     StructureListener sl;
759     for (int i = 0; i < listeners.size(); i++)
760     {
761       if (listeners.elementAt(i) instanceof StructureListener)
762       {
763         sl = (StructureListener) listeners.elementAt(i);
764         for (String pdbfile : sl.getPdbFile())
765         {
766           pdbs.remove(pdbfile);
767         }
768       }
769     }
770
771     /*
772      * Rebuild the mappings set, retaining only those which are for 'other' PDB
773      * files
774      */
775     if (pdbs.size() > 0)
776     {
777       List<StructureMapping> tmp = new ArrayList<StructureMapping>();
778       for (StructureMapping sm : mappings)
779       {
780         if (!pdbs.contains(sm.pdbfile))
781         {
782           tmp.add(sm);
783         }
784       }
785
786       mappings = tmp;
787     }
788   }
789
790   /**
791    * Propagate mouseover of a single position in a structure
792    * 
793    * @param pdbResNum
794    * @param chain
795    * @param pdbfile
796    */
797   public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
798   {
799     AtomSpec atomSpec = new AtomSpec(pdbfile, chain, pdbResNum, 0);
800     List<AtomSpec> atoms = Collections.singletonList(atomSpec);
801     mouseOverStructure(atoms);
802   }
803
804   /**
805    * Propagate mouseover or selection of multiple positions in a structure
806    * 
807    * @param atoms
808    */
809   public void mouseOverStructure(List<AtomSpec> atoms)
810   {
811     if (listeners == null)
812     {
813       // old or prematurely sent event
814       return;
815     }
816     boolean hasSequenceListener = false;
817     for (int i = 0; i < listeners.size(); i++)
818     {
819       if (listeners.elementAt(i) instanceof SequenceListener)
820       {
821         hasSequenceListener = true;
822       }
823     }
824     if (!hasSequenceListener)
825     {
826       return;
827     }
828
829     SearchResultsI results = new SearchResults();
830     for (AtomSpec atom : atoms)
831     {
832       SequenceI lastseq = null;
833       int lastipos = -1;
834       for (StructureMapping sm : mappings)
835       {
836         if (sm.pdbfile.equals(atom.getPdbFile())
837                 && sm.pdbchain.equals(atom.getChain()))
838         {
839           int indexpos = sm.getSeqPos(atom.getPdbResNum());
840           if (lastipos != indexpos && lastseq != sm.sequence)
841           {
842             results.addResult(sm.sequence, indexpos, indexpos);
843             lastipos = indexpos;
844             lastseq = sm.sequence;
845             // construct highlighted sequence list
846             for (AlignedCodonFrame acf : seqmappings)
847             {
848               acf.markMappedRegion(sm.sequence, indexpos, results);
849             }
850           }
851         }
852       }
853     }
854     for (Object li : listeners)
855     {
856       if (li instanceof SequenceListener)
857       {
858         ((SequenceListener) li).highlightSequence(results);
859       }
860     }
861   }
862
863   /**
864    * highlight regions associated with a position (indexpos) in seq
865    * 
866    * @param seq
867    *          the sequence that the mouse over occurred on
868    * @param indexpos
869    *          the absolute position being mouseovered in seq (0 to seq.length())
870    * @param seqPos
871    *          the sequence position (if -1, seq.findPosition is called to
872    *          resolve the residue number)
873    */
874   public void mouseOverSequence(SequenceI seq, int indexpos, int seqPos,
875           VamsasSource source)
876   {
877     boolean hasSequenceListeners = handlingVamsasMo
878             || !seqmappings.isEmpty();
879     SearchResultsI results = null;
880     if (seqPos == -1)
881     {
882       seqPos = seq.findPosition(indexpos);
883     }
884     for (int i = 0; i < listeners.size(); i++)
885     {
886       Object listener = listeners.elementAt(i);
887       if (listener == source)
888       {
889         // TODO listener (e.g. SeqPanel) is never == source (AlignViewport)
890         // Temporary fudge with SequenceListener.getVamsasSource()
891         continue;
892       }
893       if (listener instanceof StructureListener)
894       {
895         highlightStructure((StructureListener) listener, seq, seqPos);
896       }
897       else
898       {
899         if (listener instanceof SequenceListener)
900         {
901           final SequenceListener seqListener = (SequenceListener) listener;
902           if (hasSequenceListeners
903                   && seqListener.getVamsasSource() != source)
904           {
905             if (relaySeqMappings)
906             {
907               if (results == null)
908               {
909                 results = MappingUtils.buildSearchResults(seq, seqPos,
910                         seqmappings);
911               }
912               if (handlingVamsasMo)
913               {
914                 results.addResult(seq, seqPos, seqPos);
915
916               }
917               if (!results.isEmpty())
918               {
919                 seqListener.highlightSequence(results);
920               }
921             }
922           }
923         }
924         else if (listener instanceof VamsasListener && !handlingVamsasMo)
925         {
926           ((VamsasListener) listener).mouseOverSequence(seq, indexpos,
927                   source);
928         }
929         else if (listener instanceof SecondaryStructureListener)
930         {
931           ((SecondaryStructureListener) listener).mouseOverSequence(seq,
932                   indexpos, seqPos);
933         }
934       }
935     }
936   }
937
938   /**
939    * Send suitable messages to a StructureListener to highlight atoms
940    * corresponding to the given sequence position(s)
941    * 
942    * @param sl
943    * @param seq
944    * @param positions
945    */
946   public void highlightStructure(StructureListener sl, SequenceI seq,
947           int... positions)
948   {
949     if (!sl.isListeningFor(seq))
950     {
951       return;
952     }
953     int atomNo;
954     List<AtomSpec> atoms = new ArrayList<AtomSpec>();
955     for (StructureMapping sm : mappings)
956     {
957       if (sm.sequence == seq
958               || 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, sm
969                     .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, SelectionSource source)
1212   {
1213     for (SelectionListener slis : sel_listeners)
1214     {
1215       if (slis != source)
1216       {
1217         slis.selection(selection, colsel, source);
1218       }
1219     }
1220   }
1221
1222   Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
1223
1224   public synchronized void sendViewPosition(
1225           jalview.api.AlignmentViewPanel source, int startRes, int endRes,
1226           int startSeq, int endSeq)
1227   {
1228
1229     if (view_listeners != null && view_listeners.size() > 0)
1230     {
1231       Enumeration<AlignmentViewPanelListener> listeners = view_listeners
1232               .elements();
1233       while (listeners.hasMoreElements())
1234       {
1235         AlignmentViewPanelListener slis = listeners.nextElement();
1236         if (slis != source)
1237         {
1238           slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
1239         }
1240         ;
1241       }
1242     }
1243   }
1244
1245   /**
1246    * release all references associated with this manager provider
1247    * 
1248    * @param jalviewLite
1249    */
1250   public static void release(StructureSelectionManagerProvider jalviewLite)
1251   {
1252     // synchronized (instances)
1253     {
1254       if (instances == null)
1255       {
1256         return;
1257       }
1258       StructureSelectionManager mnger = (instances.get(jalviewLite));
1259       if (mnger != null)
1260       {
1261         instances.remove(jalviewLite);
1262         try
1263         {
1264           mnger.finalize();
1265         } catch (Throwable x)
1266         {
1267         }
1268       }
1269     }
1270   }
1271
1272   public void registerPDBEntry(PDBEntry pdbentry)
1273   {
1274     if (pdbentry.getFile() != null
1275             && pdbentry.getFile().trim().length() > 0)
1276     {
1277       registerPDBFile(pdbentry.getId(), pdbentry.getFile());
1278     }
1279   }
1280
1281   public void addCommandListener(CommandListener cl)
1282   {
1283     if (!commandListeners.contains(cl))
1284     {
1285       commandListeners.add(cl);
1286     }
1287   }
1288
1289   public boolean hasCommandListener(CommandListener cl)
1290   {
1291     return this.commandListeners.contains(cl);
1292   }
1293
1294   public boolean removeCommandListener(CommandListener l)
1295   {
1296     return commandListeners.remove(l);
1297   }
1298
1299   /**
1300    * Forward a command to any command listeners (except for the command's
1301    * source).
1302    * 
1303    * @param command
1304    *          the command to be broadcast (in its form after being performed)
1305    * @param undo
1306    *          if true, the command was being 'undone'
1307    * @param source
1308    */
1309   public void commandPerformed(CommandI command, boolean undo,
1310           VamsasSource source)
1311   {
1312     for (CommandListener listener : commandListeners)
1313     {
1314       listener.mirrorCommand(command, undo, this, source);
1315     }
1316   }
1317
1318   /**
1319    * Returns a new CommandI representing the given command as mapped to the
1320    * given sequences. If no mapping could be made, or the command is not of a
1321    * mappable kind, returns null.
1322    * 
1323    * @param command
1324    * @param undo
1325    * @param mapTo
1326    * @param gapChar
1327    * @return
1328    */
1329   public CommandI mapCommand(CommandI command, boolean undo,
1330           final AlignmentI mapTo, char gapChar)
1331   {
1332     if (command instanceof EditCommand)
1333     {
1334       return MappingUtils.mapEditCommand((EditCommand) command, undo,
1335               mapTo, gapChar, seqmappings);
1336     }
1337     else if (command instanceof OrderCommand)
1338     {
1339       return MappingUtils.mapOrderCommand((OrderCommand) command, undo,
1340               mapTo, seqmappings);
1341     }
1342     return null;
1343   }
1344
1345   public IProgressIndicator getProgressIndicator()
1346   {
1347     return progressIndicator;
1348   }
1349
1350   public void setProgressIndicator(IProgressIndicator progressIndicator)
1351   {
1352     this.progressIndicator = progressIndicator;
1353   }
1354
1355   public long getProgressSessionId()
1356   {
1357     return progressSessionId;
1358   }
1359
1360   public void setProgressSessionId(long progressSessionId)
1361   {
1362     this.progressSessionId = progressSessionId;
1363   }
1364
1365   public void setProgressBar(String message)
1366   {
1367     if (progressIndicator == null)
1368     {
1369       return;
1370     }
1371     progressIndicator.setProgressBar(message, progressSessionId);
1372   }
1373
1374   public List<AlignedCodonFrame> getSequenceMappings()
1375   {
1376     return seqmappings;
1377   }
1378
1379   public boolean isMappingForPhyre2Model()
1380   {
1381     return mappingForPhyre2Model;
1382   }
1383
1384   public void setMappingForPhyre2Model(boolean mappingForPhyre2Model)
1385   {
1386     this.mappingForPhyre2Model = mappingForPhyre2Model;
1387   }
1388
1389   public static StructureSelectionManager getStructureSelectionManager()
1390   {
1391     return instances.values().iterator().next();
1392   }
1393
1394 }