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