JAL-674 JAL-961 pass row reference to handler to check calcId and any specific proper...
[jalview.git] / src / jalview / structure / StructureSelectionManager.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.datamodel.AlignedCodonFrame;
26 import jalview.datamodel.AlignmentAnnotation;
27 import jalview.datamodel.Annotation;
28 import jalview.datamodel.PDBEntry;
29 import jalview.datamodel.SearchResults;
30 import jalview.datamodel.SequenceI;
31 import jalview.io.FormatAdapter;
32 import jalview.util.MessageManager;
33
34 import java.io.PrintStream;
35 import java.util.Enumeration;
36 import java.util.HashMap;
37 import java.util.IdentityHashMap;
38 import java.util.Vector;
39
40 import MCview.Atom;
41 import MCview.PDBChain;
42
43 public class StructureSelectionManager
44 {
45   static IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager> instances;
46
47   StructureMapping[] mappings;
48
49   /**
50    * debug function - write all mappings to stdout
51    */
52   public void reportMapping()
53   {
54     if (mappings == null)
55     {
56       System.err.println("reportMapping: No PDB/Sequence mappings.");
57     }
58     else
59     {
60       System.err.println("reportMapping: There are " + mappings.length
61               + " mappings.");
62       for (int m = 0; m < mappings.length; m++)
63       {
64         System.err.println("mapping " + m + " : " + mappings[m].pdbfile);
65       }
66     }
67   }
68
69   /**
70    * map between the PDB IDs (or structure identifiers) used by Jalview and the
71    * absolute filenames for PDB data that corresponds to it
72    */
73   HashMap<String, String> pdbIdFileName = new HashMap<String, String>(),
74           pdbFileNameId = new HashMap<String, String>();
75
76   public void registerPDBFile(String idForFile, String absoluteFile)
77   {
78     pdbIdFileName.put(idForFile, absoluteFile);
79     pdbFileNameId.put(absoluteFile, idForFile);
80   }
81
82   public String findIdForPDBFile(String idOrFile)
83   {
84     String id = pdbFileNameId.get(idOrFile);
85     return id;
86   }
87
88   public String findFileForPDBId(String idOrFile)
89   {
90     String id = pdbIdFileName.get(idOrFile);
91     return id;
92   }
93
94   public boolean isPDBFileRegistered(String idOrFile)
95   {
96     return pdbFileNameId.containsKey(idOrFile)
97             || pdbIdFileName.containsKey(idOrFile);
98   }
99
100   private static StructureSelectionManager nullProvider = null;
101
102   public static StructureSelectionManager getStructureSelectionManager(
103           StructureSelectionManagerProvider context)
104   {
105     if (context == null)
106     {
107       if (nullProvider == null)
108       {
109         if (instances != null)
110         {
111           throw new Error(MessageManager.getString("error.implementation_error_structure_selection_manager_null"),
112                   new NullPointerException(MessageManager.getString("exception.ssm_context_is_null")));
113         }
114         else
115         {
116           nullProvider = new StructureSelectionManager();
117         }
118         return nullProvider;
119       }
120     }
121     if (instances == null)
122     {
123       instances = new java.util.IdentityHashMap<StructureSelectionManagerProvider, StructureSelectionManager>();
124     }
125     StructureSelectionManager instance = instances.get(context);
126     if (instance == null)
127     {
128       if (nullProvider != null)
129       {
130         instance = nullProvider;
131       }
132       else
133       {
134         instance = new StructureSelectionManager();
135       }
136       instances.put(context, instance);
137     }
138     return instance;
139   }
140
141   /**
142    * flag controlling whether SeqMappings are relayed from received sequence
143    * mouse over events to other sequences
144    */
145   boolean relaySeqMappings = true;
146
147   /**
148    * Enable or disable relay of seqMapping events to other sequences. You might
149    * want to do this if there are many sequence mappings and the host computer
150    * is slow
151    * 
152    * @param relay
153    */
154   public void setRelaySeqMappings(boolean relay)
155   {
156     relaySeqMappings = relay;
157   }
158
159   /**
160    * get the state of the relay seqMappings flag.
161    * 
162    * @return true if sequence mouse overs are being relayed to other mapped
163    *         sequences
164    */
165   public boolean isRelaySeqMappingsEnabled()
166   {
167     return relaySeqMappings;
168   }
169
170   Vector listeners = new Vector();
171
172   /**
173    * register a listener for alignment sequence mouseover events
174    * 
175    * @param svl
176    */
177   public void addStructureViewerListener(Object svl)
178   {
179     if (!listeners.contains(svl))
180     {
181       listeners.addElement(svl);
182     }
183   }
184
185   public String alreadyMappedToFile(String pdbid)
186   {
187     if (mappings != null)
188     {
189       for (int i = 0; i < mappings.length; i++)
190       {
191         if (mappings[i].getPdbId().equals(pdbid))
192         {
193           return mappings[i].pdbfile;
194         }
195       }
196     }
197     return null;
198   }
199
200   /**
201    * Import structure data and register a structure mapping for broadcasting
202    * colouring, mouseovers and selection events (convenience wrapper).
203    * 
204    * @param sequence
205    *          - one or more sequences to be mapped to pdbFile
206    * @param targetChains
207    *          - optional chain specification for mapping each sequence to pdb
208    *          (may be nill, individual elements may be nill)
209    * @param pdbFile
210    *          - structure data resource
211    * @param protocol
212    *          - how to resolve data from resource
213    * @return null or the structure data parsed as a pdb file
214    */
215   synchronized public MCview.PDBfile setMapping(SequenceI[] sequence,
216           String[] targetChains, String pdbFile, String protocol)
217   {
218     return setMapping(true, sequence, targetChains, pdbFile, protocol);
219   }
220
221   /**
222    * create sequence structure mappings between each sequence and the given
223    * pdbFile (retrieved via the given protocol).
224    * 
225    * @param forStructureView
226    *          when true, record the mapping for use in mouseOvers
227    * 
228    * @param sequence
229    *          - one or more sequences to be mapped to pdbFile
230    * @param targetChains
231    *          - optional chain specification for mapping each sequence to pdb
232    *          (may be nill, individual elements may be nill)
233    * @param pdbFile
234    *          - structure data resource
235    * @param protocol
236    *          - how to resolve data from resource
237    * @return null or the structure data parsed as a pdb file
238    */
239   synchronized public MCview.PDBfile setMapping(boolean forStructureView,
240           SequenceI[] sequence,
241           String[] targetChains, String pdbFile, String protocol)
242   {
243     /*
244      * There will be better ways of doing this in the future, for now we'll use
245      * the tried and tested MCview pdb mapping
246      */
247     MCview.PDBfile pdb = null;
248     boolean parseSecStr=true;
249     if (isPDBFileRegistered(pdbFile))
250     {
251       for (SequenceI sq : sequence)
252       {
253         SequenceI ds = sq;
254         while (ds.getDatasetSequence() != null)
255         {
256           ds = ds.getDatasetSequence();
257         }
258         ;
259         if (ds.getAnnotation() != null)
260         {
261           for (AlignmentAnnotation ala : ds.getAnnotation())
262           {
263             // false if any annotation present from this structure
264             // JBPNote this fails for jmol/chimera view because the *file* is
265             // passed, not the structure data ID -
266             if (MCview.PDBfile.isCalcIdForFile(ala,
267                     findIdForPDBFile(pdbFile)))
268             {
269               parseSecStr = false;
270             }
271           }
272         }
273       }
274     }
275     try
276     {
277       pdb = new MCview.PDBfile(true, parseSecStr, pdbFile, protocol);
278       if (pdb.id != null && pdb.id.trim().length() > 0
279               && FormatAdapter.FILE.equals(protocol))
280       {
281         registerPDBFile(pdb.id.trim(), pdbFile);
282       }
283     } catch (Exception ex)
284     {
285       ex.printStackTrace();
286       return null;
287     }
288
289     String targetChain;
290     for (int s = 0; s < sequence.length; s++)
291     {
292       boolean infChain = true;
293       if (targetChains != null && targetChains[s] != null)
294       {
295         infChain = false;
296         targetChain = targetChains[s];
297       }
298       else if (sequence[s].getName().indexOf("|") > -1)
299       {
300         targetChain = sequence[s].getName().substring(
301                 sequence[s].getName().lastIndexOf("|") + 1);
302         if (targetChain.length() > 1)
303         {
304           if (targetChain.trim().length() == 0)
305           {
306             targetChain = " ";
307           }
308           else
309           {
310             // not a valid chain identifier
311             targetChain = "";
312           }
313         }
314       }
315       else
316       {
317         targetChain = "";
318       }
319
320       int max = -10;
321       AlignSeq maxAlignseq = null;
322       String maxChainId = " ";
323       PDBChain maxChain = null;
324       boolean first = true;
325       for (int i = 0; i < pdb.chains.size(); i++)
326       {
327         PDBChain chain = (pdb.chains.elementAt(i));
328         if (targetChain.length() > 0 && !targetChain.equals(chain.id)
329                 && !infChain)
330         {
331           continue; // don't try to map chains don't match.
332         }
333         // TODO: correctly determine sequence type for mixed na/peptide
334         // structures
335         AlignSeq as = new AlignSeq(sequence[s],
336                 pdb.chains.elementAt(i).sequence,
337                 pdb.chains.elementAt(i).isNa ? AlignSeq.DNA
338                         : AlignSeq.PEP);
339         as.calcScoreMatrix();
340         as.traceAlignment();
341
342         if (first || as.maxscore > max
343                 || (as.maxscore == max && chain.id.equals(targetChain)))
344         {
345           first = false;
346           maxChain = chain;
347           max = as.maxscore;
348           maxAlignseq = as;
349           maxChainId = chain.id;
350         }
351       }
352       if (maxChain == null)
353       {
354         continue;
355       }
356       final StringBuffer mappingDetails = new StringBuffer();
357       mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
358               + maxChain.sequence.getSequenceAsString());
359       mappingDetails.append("\nNo of residues = "
360               + maxChain.residues.size() + "\n\n");
361       PrintStream ps = new PrintStream(System.out)
362       {
363         public void print(String x)
364         {
365           mappingDetails.append(x);
366         }
367
368         public void println()
369         {
370           mappingDetails.append("\n");
371         }
372       };
373
374       maxAlignseq.printAlignment(ps);
375
376       mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
377               + " " + maxAlignseq.seq2end);
378       mappingDetails.append("\nSEQ start/end "
379               + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
380               + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
381
382       maxChain.makeExactMapping(maxAlignseq, sequence[s]);
383
384       maxChain.transferRESNUMFeatures(sequence[s], null);
385
386       // allocate enough slots to store the mapping from positions in
387       // sequence[s] to the associated chain
388       int[][] mapping = new int[sequence[s].findPosition(sequence[s]
389               .getLength()) + 2][2];
390       int resNum = -10000;
391       int index = 0;
392
393       do
394       {
395         Atom tmp = (Atom) maxChain.atoms.elementAt(index);
396         if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
397         {
398           resNum = tmp.resNumber;
399           mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
400           mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
401         }
402
403         index++;
404       } while (index < maxChain.atoms.size());
405
406       if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
407       {
408         pdbFile = "INLINE" + pdb.id;
409       }
410       StructureMapping newMapping = new StructureMapping(sequence[s],
411               pdbFile, pdb.id, maxChainId, mapping,
412               mappingDetails.toString());
413       if (forStructureView)
414       {
415
416         if (mappings == null)
417         {
418           mappings = new StructureMapping[1];
419         }
420         else
421         {
422           StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
423           System.arraycopy(mappings, 0, tmp, 0, mappings.length);
424           mappings = tmp;
425         }
426
427         mappings[mappings.length - 1] = newMapping;
428       }
429       maxChain.transferResidueAnnotation(newMapping);
430     }
431     // ///////
432
433     return pdb;
434   }
435
436   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
437   {
438     listeners.removeElement(svl);
439     if (svl instanceof SequenceListener)
440     {
441       for (int i = 0; i < listeners.size(); i++)
442       {
443         if (listeners.elementAt(i) instanceof StructureListener)
444         {
445           ((StructureListener) listeners.elementAt(i))
446                   .releaseReferences(svl);
447         }
448       }
449     }
450
451     if (pdbfiles == null)
452     {
453       return;
454     }
455     boolean removeMapping = true;
456     String[] handlepdbs;
457     Vector pdbs = new Vector();
458     for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
459     {
460       ;
461     }
462     StructureListener sl;
463     for (int i = 0; i < listeners.size(); i++)
464     {
465       if (listeners.elementAt(i) instanceof StructureListener)
466       {
467         sl = (StructureListener) listeners.elementAt(i);
468         handlepdbs = sl.getPdbFile();
469         for (int j = 0; j < handlepdbs.length; j++)
470         {
471           if (pdbs.contains(handlepdbs[j]))
472           {
473             pdbs.removeElement(handlepdbs[j]);
474           }
475         }
476
477       }
478     }
479
480     if (pdbs.size() > 0 && mappings != null)
481     {
482       Vector tmp = new Vector();
483       for (int i = 0; i < mappings.length; i++)
484       {
485         if (!pdbs.contains(mappings[i].pdbfile))
486         {
487           tmp.addElement(mappings[i]);
488         }
489       }
490
491       mappings = new StructureMapping[tmp.size()];
492       tmp.copyInto(mappings);
493     }
494   }
495
496   public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
497   {
498     if (listeners == null)
499     {
500       // old or prematurely sent event
501       return;
502     }
503     boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
504     SearchResults results = null;
505     SequenceI lastseq = null;
506     int lastipos = -1, indexpos;
507     for (int i = 0; i < listeners.size(); i++)
508     {
509       if (listeners.elementAt(i) instanceof SequenceListener)
510       {
511         if (results == null)
512         {
513           results = new SearchResults();
514         }
515         if (mappings != null)
516         {
517           for (int j = 0; j < mappings.length; j++)
518           {
519             if (mappings[j].pdbfile.equals(pdbfile)
520                     && mappings[j].pdbchain.equals(chain))
521             {
522               indexpos = mappings[j].getSeqPos(pdbResNum);
523               if (lastipos != indexpos && lastseq != mappings[j].sequence)
524               {
525                 results.addResult(mappings[j].sequence, indexpos, indexpos);
526                 lastipos = indexpos;
527                 lastseq = mappings[j].sequence;
528                 // construct highlighted sequence list
529                 if (seqmappings != null)
530                 {
531
532                   Enumeration e = seqmappings.elements();
533                   while (e.hasMoreElements())
534
535                   {
536                     ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
537                             mappings[j].sequence, indexpos, results);
538                   }
539                 }
540               }
541
542             }
543           }
544         }
545       }
546     }
547     if (results != null)
548     {
549       for (int i = 0; i < listeners.size(); i++)
550       {
551         Object li = listeners.elementAt(i);
552         if (li instanceof SequenceListener)
553         {
554           ((SequenceListener) li).highlightSequence(results);
555         }
556       }
557     }
558   }
559
560   Vector seqmappings = null; // should be a simpler list of mapped seuqence
561
562   /**
563    * highlight regions associated with a position (indexpos) in seq
564    * 
565    * @param seq
566    *          the sequeence that the mouse over occured on
567    * @param indexpos
568    *          the absolute position being mouseovered in seq (0 to seq.length())
569    * @param index
570    *          the sequence position (if -1, seq.findPosition is called to
571    *          resolve the residue number)
572    */
573   public void mouseOverSequence(SequenceI seq, int indexpos, int index,
574           VamsasSource source)
575   {
576     boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
577     SearchResults results = null;
578     if (index == -1)
579     {
580       index = seq.findPosition(indexpos);
581     }
582     StructureListener sl;
583     int atomNo = 0;
584     for (int i = 0; i < listeners.size(); i++)
585     {
586       Object listener = listeners.elementAt(i);
587       if (listener == source)
588       {
589         continue;
590       }
591       if (listener instanceof StructureListener)
592       {
593         sl = (StructureListener) listener;
594         if (mappings == null)
595         {
596           continue;
597         }
598         for (int j = 0; j < mappings.length; j++)
599         {
600           if (mappings[j].sequence == seq
601                   || mappings[j].sequence == seq.getDatasetSequence())
602           {
603             atomNo = mappings[j].getAtomNum(index);
604
605             if (atomNo > 0)
606             {
607               sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
608                       mappings[j].pdbchain, mappings[j].pdbfile);
609             }
610           }
611         }
612       }
613       else
614       {
615         if (relaySeqMappings && hasSequenceListeners
616                 && listener instanceof SequenceListener)
617         {
618           // DEBUG
619           // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
620           // index);
621
622           if (results == null)
623           {
624             results = new SearchResults();
625             if (index >= seq.getStart() && index <= seq.getEnd())
626             {
627               // construct highlighted sequence list
628
629               if (seqmappings != null)
630               {
631                 Enumeration e = seqmappings.elements();
632                 while (e.hasMoreElements())
633
634                 {
635                   ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
636                           seq, index, results);
637                 }
638               }
639               // hasSequenceListeners = results.getSize() > 0;
640               if (handlingVamsasMo)
641               {
642                 // maybe have to resolve seq to a dataset seqeunce...
643                 // add in additional direct sequence and/or dataset sequence
644                 // highlighting
645                 results.addResult(seq, index, index);
646               }
647             }
648           }
649           if (hasSequenceListeners)
650           {
651             ((SequenceListener) listener).highlightSequence(results);
652           }
653         }
654         else if (listener instanceof VamsasListener && !handlingVamsasMo)
655         {
656           // DEBUG
657           // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
658           // " +
659           // index);
660           // pass the mouse over and absolute position onto the
661           // VamsasListener(s)
662           ((VamsasListener) listener).mouseOver(seq, indexpos, source);
663         }
664         else if (listener instanceof SecondaryStructureListener)
665         {
666           ((SecondaryStructureListener) listener).mouseOverSequence(seq,
667                   indexpos);
668         }
669       }
670     }
671   }
672
673   /**
674    * true if a mouse over event from an external (ie Vamsas) source is being
675    * handled
676    */
677   boolean handlingVamsasMo = false;
678
679   long lastmsg = 0;
680
681   /**
682    * as mouseOverSequence but only route event to SequenceListeners
683    * 
684    * @param sequenceI
685    * @param position
686    *          in an alignment sequence
687    */
688   public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
689           VamsasSource source)
690   {
691     handlingVamsasMo = true;
692     long msg = sequenceI.hashCode() * (1 + position);
693     if (lastmsg != msg)
694     {
695       lastmsg = msg;
696       mouseOverSequence(sequenceI, position, -1, source);
697     }
698     handlingVamsasMo = false;
699   }
700
701   public Annotation[] colourSequenceFromStructure(SequenceI seq,
702           String pdbid)
703   {
704     return null;
705     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
706     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
707     /*
708      * Annotation [] annotations = new Annotation[seq.getLength()];
709      * 
710      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
711      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
712      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
713      * 
714      * for (int j = 0; j < mappings.length; j++) {
715      * 
716      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
717      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
718      * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
719      * "+mappings[j].pdbfile);
720      * 
721      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
722      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
723      * 
724      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
725      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
726      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
727      * mappings[j].pdbfile); }
728      * 
729      * annotations[index] = new Annotation("X",null,' ',0,col); } return
730      * annotations; } } } }
731      * 
732      * return annotations;
733      */
734   }
735
736   public void structureSelectionChanged()
737   {
738   }
739
740   public void sequenceSelectionChanged()
741   {
742   }
743
744   public void sequenceColoursChanged(Object source)
745   {
746     StructureListener sl;
747     for (int i = 0; i < listeners.size(); i++)
748     {
749       if (listeners.elementAt(i) instanceof StructureListener)
750       {
751         sl = (StructureListener) listeners.elementAt(i);
752         sl.updateColours(source);
753       }
754     }
755   }
756
757   public StructureMapping[] getMapping(String pdbfile)
758   {
759     Vector tmp = new Vector();
760     if (mappings != null)
761     {
762       for (int i = 0; i < mappings.length; i++)
763       {
764         if (mappings[i].pdbfile.equals(pdbfile))
765         {
766           tmp.addElement(mappings[i]);
767         }
768       }
769     }
770     StructureMapping[] ret = new StructureMapping[tmp.size()];
771     for (int i = 0; i < tmp.size(); i++)
772     {
773       ret[i] = (StructureMapping) tmp.elementAt(i);
774     }
775
776     return ret;
777   }
778
779   public String printMapping(String pdbfile)
780   {
781     StringBuffer sb = new StringBuffer();
782     for (int i = 0; i < mappings.length; i++)
783     {
784       if (mappings[i].pdbfile.equals(pdbfile))
785       {
786         sb.append(mappings[i].mappingDetails);
787       }
788     }
789
790     return sb.toString();
791   }
792
793   private int[] seqmappingrefs = null; // refcount for seqmappings elements
794
795   private synchronized void modifySeqMappingList(boolean add,
796           AlignedCodonFrame[] codonFrames)
797   {
798     if (!add && (seqmappings == null || seqmappings.size() == 0))
799     {
800       return;
801     }
802     if (seqmappings == null)
803     {
804       seqmappings = new Vector();
805     }
806     if (codonFrames != null && codonFrames.length > 0)
807     {
808       for (int cf = 0; cf < codonFrames.length; cf++)
809       {
810         if (seqmappings.contains(codonFrames[cf]))
811         {
812           if (add)
813           {
814             seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
815           }
816           else
817           {
818             if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
819             {
820               int pos = seqmappings.indexOf(codonFrames[cf]);
821               int[] nr = new int[seqmappingrefs.length - 1];
822               if (pos > 0)
823               {
824                 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
825               }
826               if (pos < seqmappingrefs.length - 1)
827               {
828                 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
829                         seqmappingrefs.length - pos - 2);
830               }
831             }
832           }
833         }
834         else
835         {
836           if (add)
837           {
838             seqmappings.addElement(codonFrames[cf]);
839
840             int[] nsr = new int[(seqmappingrefs == null) ? 1
841                     : seqmappingrefs.length + 1];
842             if (seqmappingrefs != null && seqmappingrefs.length > 0)
843             {
844               System.arraycopy(seqmappingrefs, 0, nsr, 0,
845                       seqmappingrefs.length);
846             }
847             nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
848             seqmappingrefs = nsr;
849           }
850         }
851       }
852     }
853   }
854
855   public void removeMappings(AlignedCodonFrame[] codonFrames)
856   {
857     modifySeqMappingList(false, codonFrames);
858   }
859
860   public void addMappings(AlignedCodonFrame[] codonFrames)
861   {
862     modifySeqMappingList(true, codonFrames);
863   }
864
865   Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
866
867   public void addSelectionListener(SelectionListener selecter)
868   {
869     if (!sel_listeners.contains(selecter))
870     {
871       sel_listeners.addElement(selecter);
872     }
873   }
874
875   public void removeSelectionListener(SelectionListener toremove)
876   {
877     if (sel_listeners.contains(toremove))
878     {
879       sel_listeners.removeElement(toremove);
880     }
881   }
882
883   public synchronized void sendSelection(
884           jalview.datamodel.SequenceGroup selection,
885           jalview.datamodel.ColumnSelection colsel, SelectionSource source)
886   {
887     if (sel_listeners != null && sel_listeners.size() > 0)
888     {
889       Enumeration listeners = sel_listeners.elements();
890       while (listeners.hasMoreElements())
891       {
892         SelectionListener slis = ((SelectionListener) listeners
893                 .nextElement());
894         if (slis != source)
895         {
896           slis.selection(selection, colsel, source);
897         }
898         ;
899       }
900     }
901   }
902
903   Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
904
905   public synchronized void sendViewPosition(
906           jalview.api.AlignmentViewPanel source, int startRes, int endRes,
907           int startSeq, int endSeq)
908   {
909
910     if (view_listeners != null && view_listeners.size() > 0)
911     {
912       Enumeration<AlignmentViewPanelListener> listeners = view_listeners
913               .elements();
914       while (listeners.hasMoreElements())
915       {
916         AlignmentViewPanelListener slis = listeners.nextElement();
917         if (slis != source)
918         {
919           slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
920         }
921         ;
922       }
923     }
924   }
925
926   public void finalize() throws Throwable
927   {
928     if (listeners != null)
929     {
930       listeners.clear();
931       listeners = null;
932     }
933     if (pdbIdFileName != null)
934     {
935       pdbIdFileName.clear();
936       pdbIdFileName = null;
937     }
938     if (sel_listeners != null)
939     {
940       sel_listeners.clear();
941       sel_listeners = null;
942     }
943     if (view_listeners != null)
944     {
945       view_listeners.clear();
946       view_listeners = null;
947     }
948     mappings = null;
949     seqmappingrefs = null;
950   }
951
952   /**
953    * release all references associated with this manager provider
954    * 
955    * @param jalviewLite
956    */
957   public static void release(StructureSelectionManagerProvider jalviewLite)
958   {
959     // synchronized (instances)
960     {
961       if (instances == null)
962       {
963         return;
964       }
965       StructureSelectionManager mnger = (instances.get(jalviewLite));
966       if (mnger != null)
967       {
968         instances.remove(jalviewLite);
969         try
970         {
971           mnger.finalize();
972         } catch (Throwable x)
973         {
974         }
975         ;
976       }
977     }
978   }
979
980   public void registerPDBEntry(PDBEntry pdbentry)
981   {
982     if (pdbentry.getFile() != null
983             && pdbentry.getFile().trim().length() > 0)
984     {
985       registerPDBFile(pdbentry.getId(), pdbentry.getFile());
986     }
987   }
988
989 }