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