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