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