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