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