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