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