JAL-1528 bug fixes and adjustments to Chimera interface
[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.AppletFormatAdapter;
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               && AppletFormatAdapter.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         @Override
364         public void print(String x)
365         {
366           mappingDetails.append(x);
367         }
368
369         @Override
370         public void println()
371         {
372           mappingDetails.append("\n");
373         }
374       };
375
376       maxAlignseq.printAlignment(ps);
377
378       mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
379               + " " + maxAlignseq.seq2end);
380       mappingDetails.append("\nSEQ start/end "
381               + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
382               + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
383
384       maxChain.makeExactMapping(maxAlignseq, sequence[s]);
385       jalview.datamodel.Mapping sqmpping = maxAlignseq
386               .getMappingFromS1(false);
387       jalview.datamodel.Mapping omap = new jalview.datamodel.Mapping(
388               sqmpping.getMap().getInverse());
389       maxChain.transferRESNUMFeatures(sequence[s], null);
390
391       // allocate enough slots to store the mapping from positions in
392       // sequence[s] to the associated chain
393       int[][] mapping = new int[sequence[s].findPosition(sequence[s]
394               .getLength()) + 2][2];
395       int resNum = -10000;
396       int index = 0;
397
398       do
399       {
400         Atom tmp = (Atom) maxChain.atoms.elementAt(index);
401         if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
402         {
403           resNum = tmp.resNumber;
404           mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
405           mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
406         }
407
408         index++;
409       } while (index < maxChain.atoms.size());
410
411       if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
412       {
413         pdbFile = "INLINE" + pdb.id;
414       }
415       StructureMapping newMapping = new StructureMapping(sequence[s],
416               pdbFile, pdb.id, maxChainId, mapping,
417               mappingDetails.toString());
418       if (forStructureView)
419       {
420
421         if (mappings == null)
422         {
423           mappings = new StructureMapping[1];
424         }
425         else
426         {
427           StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
428           System.arraycopy(mappings, 0, tmp, 0, mappings.length);
429           mappings = tmp;
430         }
431
432         mappings[mappings.length - 1] = newMapping;
433       }
434       maxChain.transferResidueAnnotation(newMapping, sqmpping);
435     }
436     // ///////
437
438     return pdb;
439   }
440
441   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
442   {
443     listeners.removeElement(svl);
444     if (svl instanceof SequenceListener)
445     {
446       for (int i = 0; i < listeners.size(); i++)
447       {
448         if (listeners.elementAt(i) instanceof StructureListener)
449         {
450           ((StructureListener) listeners.elementAt(i))
451                   .releaseReferences(svl);
452         }
453       }
454     }
455
456     if (pdbfiles == null)
457     {
458       return;
459     }
460     boolean removeMapping = true;
461     String[] handlepdbs;
462     Vector pdbs = new Vector();
463     for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
464     {
465       ;
466     }
467     StructureListener sl;
468     for (int i = 0; i < listeners.size(); i++)
469     {
470       if (listeners.elementAt(i) instanceof StructureListener)
471       {
472         sl = (StructureListener) listeners.elementAt(i);
473         handlepdbs = sl.getPdbFile();
474         for (int j = 0; j < handlepdbs.length; j++)
475         {
476           if (pdbs.contains(handlepdbs[j]))
477           {
478             pdbs.removeElement(handlepdbs[j]);
479           }
480         }
481
482       }
483     }
484
485     if (pdbs.size() > 0 && mappings != null)
486     {
487       Vector tmp = new Vector();
488       for (int i = 0; i < mappings.length; i++)
489       {
490         if (!pdbs.contains(mappings[i].pdbfile))
491         {
492           tmp.addElement(mappings[i]);
493         }
494       }
495
496       mappings = new StructureMapping[tmp.size()];
497       tmp.copyInto(mappings);
498     }
499   }
500
501   public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
502   {
503     if (listeners == null)
504     {
505       // old or prematurely sent event
506       return;
507     }
508     boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
509     SearchResults results = null;
510     SequenceI lastseq = null;
511     int lastipos = -1, indexpos;
512     for (int i = 0; i < listeners.size(); i++)
513     {
514       if (listeners.elementAt(i) instanceof SequenceListener)
515       {
516         if (results == null)
517         {
518           results = new SearchResults();
519         }
520         if (mappings != null)
521         {
522           for (int j = 0; j < mappings.length; j++)
523           {
524             if (mappings[j].pdbfile.equals(pdbfile)
525                     && mappings[j].pdbchain.equals(chain))
526             {
527               indexpos = mappings[j].getSeqPos(pdbResNum);
528               if (lastipos != indexpos && lastseq != mappings[j].sequence)
529               {
530                 results.addResult(mappings[j].sequence, indexpos, indexpos);
531                 lastipos = indexpos;
532                 lastseq = mappings[j].sequence;
533                 // construct highlighted sequence list
534                 if (seqmappings != null)
535                 {
536
537                   Enumeration e = seqmappings.elements();
538                   while (e.hasMoreElements())
539
540                   {
541                     ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
542                             mappings[j].sequence, indexpos, results);
543                   }
544                 }
545               }
546
547             }
548           }
549         }
550       }
551     }
552     if (results != null)
553     {
554       for (int i = 0; i < listeners.size(); i++)
555       {
556         Object li = listeners.elementAt(i);
557         if (li instanceof SequenceListener)
558         {
559           ((SequenceListener) li).highlightSequence(results);
560         }
561       }
562     }
563   }
564
565   Vector seqmappings = null; // should be a simpler list of mapped seuqence
566
567   /**
568    * highlight regions associated with a position (indexpos) in seq
569    * 
570    * @param seq
571    *          the sequeence that the mouse over occured on
572    * @param indexpos
573    *          the absolute position being mouseovered in seq (0 to seq.length())
574    * @param index
575    *          the sequence position (if -1, seq.findPosition is called to
576    *          resolve the residue number)
577    */
578   public void mouseOverSequence(SequenceI seq, int indexpos, int index,
579           VamsasSource source)
580   {
581     boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
582     SearchResults results = null;
583     if (index == -1)
584     {
585       index = seq.findPosition(indexpos);
586     }
587     StructureListener sl;
588     int atomNo = 0;
589     for (int i = 0; i < listeners.size(); i++)
590     {
591       Object listener = listeners.elementAt(i);
592       if (listener == source)
593       {
594         continue;
595       }
596       if (listener instanceof StructureListener)
597       {
598         sl = (StructureListener) listener;
599         if (mappings == null)
600         {
601           continue;
602         }
603         for (int j = 0; j < mappings.length; j++)
604         {
605           if (mappings[j].sequence == seq
606                   || mappings[j].sequence == seq.getDatasetSequence())
607           {
608             atomNo = mappings[j].getAtomNum(index);
609
610             if (atomNo > 0)
611             {
612               sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
613                       mappings[j].pdbchain, mappings[j].pdbfile);
614             }
615           }
616         }
617       }
618       else
619       {
620         if (relaySeqMappings && hasSequenceListeners
621                 && listener instanceof SequenceListener)
622         {
623           // DEBUG
624           // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
625           // index);
626
627           if (results == null)
628           {
629             results = new SearchResults();
630             if (index >= seq.getStart() && index <= seq.getEnd())
631             {
632               // construct highlighted sequence list
633
634               if (seqmappings != null)
635               {
636                 Enumeration e = seqmappings.elements();
637                 while (e.hasMoreElements())
638
639                 {
640                   ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
641                           seq, index, results);
642                 }
643               }
644               // hasSequenceListeners = results.getSize() > 0;
645               if (handlingVamsasMo)
646               {
647                 // maybe have to resolve seq to a dataset seqeunce...
648                 // add in additional direct sequence and/or dataset sequence
649                 // highlighting
650                 results.addResult(seq, index, index);
651               }
652             }
653           }
654           if (hasSequenceListeners)
655           {
656             ((SequenceListener) listener).highlightSequence(results);
657           }
658         }
659         else if (listener instanceof VamsasListener && !handlingVamsasMo)
660         {
661           // DEBUG
662           // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
663           // " +
664           // index);
665           // pass the mouse over and absolute position onto the
666           // VamsasListener(s)
667           ((VamsasListener) listener).mouseOver(seq, indexpos, source);
668         }
669         else if (listener instanceof SecondaryStructureListener)
670         {
671           ((SecondaryStructureListener) listener).mouseOverSequence(seq,
672                   indexpos);
673         }
674       }
675     }
676   }
677
678   /**
679    * true if a mouse over event from an external (ie Vamsas) source is being
680    * handled
681    */
682   boolean handlingVamsasMo = false;
683
684   long lastmsg = 0;
685
686   /**
687    * as mouseOverSequence but only route event to SequenceListeners
688    * 
689    * @param sequenceI
690    * @param position
691    *          in an alignment sequence
692    */
693   public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
694           VamsasSource source)
695   {
696     handlingVamsasMo = true;
697     long msg = sequenceI.hashCode() * (1 + position);
698     if (lastmsg != msg)
699     {
700       lastmsg = msg;
701       mouseOverSequence(sequenceI, position, -1, source);
702     }
703     handlingVamsasMo = false;
704   }
705
706   public Annotation[] colourSequenceFromStructure(SequenceI seq,
707           String pdbid)
708   {
709     return null;
710     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
711     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
712     /*
713      * Annotation [] annotations = new Annotation[seq.getLength()];
714      * 
715      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
716      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
717      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
718      * 
719      * for (int j = 0; j < mappings.length; j++) {
720      * 
721      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
722      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
723      * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
724      * "+mappings[j].pdbfile);
725      * 
726      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
727      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
728      * 
729      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
730      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
731      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
732      * mappings[j].pdbfile); }
733      * 
734      * annotations[index] = new Annotation("X",null,' ',0,col); } return
735      * annotations; } } } }
736      * 
737      * return annotations;
738      */
739   }
740
741   public void structureSelectionChanged()
742   {
743   }
744
745   public void sequenceSelectionChanged()
746   {
747   }
748
749   public void sequenceColoursChanged(Object source)
750   {
751     StructureListener sl;
752     for (int i = 0; i < listeners.size(); i++)
753     {
754       if (listeners.elementAt(i) instanceof StructureListener)
755       {
756         sl = (StructureListener) listeners.elementAt(i);
757         sl.updateColours(source);
758       }
759     }
760   }
761
762   public StructureMapping[] getMapping(String pdbfile)
763   {
764     Vector tmp = new Vector();
765     if (mappings != null)
766     {
767       for (int i = 0; i < mappings.length; i++)
768       {
769         if (mappings[i].pdbfile.equals(pdbfile))
770         {
771           tmp.addElement(mappings[i]);
772         }
773       }
774     }
775     StructureMapping[] ret = new StructureMapping[tmp.size()];
776     for (int i = 0; i < tmp.size(); i++)
777     {
778       ret[i] = (StructureMapping) tmp.elementAt(i);
779     }
780
781     return ret;
782   }
783
784   public String printMapping(String pdbfile)
785   {
786     StringBuffer sb = new StringBuffer();
787     for (int i = 0; i < mappings.length; i++)
788     {
789       if (mappings[i].pdbfile.equals(pdbfile))
790       {
791         sb.append(mappings[i].mappingDetails);
792       }
793     }
794
795     return sb.toString();
796   }
797
798   private int[] seqmappingrefs = null; // refcount for seqmappings elements
799
800   private synchronized void modifySeqMappingList(boolean add,
801           AlignedCodonFrame[] codonFrames)
802   {
803     if (!add && (seqmappings == null || seqmappings.size() == 0))
804     {
805       return;
806     }
807     if (seqmappings == null)
808     {
809       seqmappings = new Vector();
810     }
811     if (codonFrames != null && codonFrames.length > 0)
812     {
813       for (int cf = 0; cf < codonFrames.length; cf++)
814       {
815         if (seqmappings.contains(codonFrames[cf]))
816         {
817           if (add)
818           {
819             seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
820           }
821           else
822           {
823             if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
824             {
825               int pos = seqmappings.indexOf(codonFrames[cf]);
826               int[] nr = new int[seqmappingrefs.length - 1];
827               if (pos > 0)
828               {
829                 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
830               }
831               if (pos < seqmappingrefs.length - 1)
832               {
833                 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
834                         seqmappingrefs.length - pos - 2);
835               }
836             }
837           }
838         }
839         else
840         {
841           if (add)
842           {
843             seqmappings.addElement(codonFrames[cf]);
844
845             int[] nsr = new int[(seqmappingrefs == null) ? 1
846                     : seqmappingrefs.length + 1];
847             if (seqmappingrefs != null && seqmappingrefs.length > 0)
848             {
849               System.arraycopy(seqmappingrefs, 0, nsr, 0,
850                       seqmappingrefs.length);
851             }
852             nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
853             seqmappingrefs = nsr;
854           }
855         }
856       }
857     }
858   }
859
860   public void removeMappings(AlignedCodonFrame[] codonFrames)
861   {
862     modifySeqMappingList(false, codonFrames);
863   }
864
865   public void addMappings(AlignedCodonFrame[] codonFrames)
866   {
867     modifySeqMappingList(true, codonFrames);
868   }
869
870   Vector<SelectionListener> sel_listeners = new Vector<SelectionListener>();
871
872   public void addSelectionListener(SelectionListener selecter)
873   {
874     if (!sel_listeners.contains(selecter))
875     {
876       sel_listeners.addElement(selecter);
877     }
878   }
879
880   public void removeSelectionListener(SelectionListener toremove)
881   {
882     if (sel_listeners.contains(toremove))
883     {
884       sel_listeners.removeElement(toremove);
885     }
886   }
887
888   public synchronized void sendSelection(
889           jalview.datamodel.SequenceGroup selection,
890           jalview.datamodel.ColumnSelection colsel, SelectionSource source)
891   {
892     if (sel_listeners != null && sel_listeners.size() > 0)
893     {
894       Enumeration listeners = sel_listeners.elements();
895       while (listeners.hasMoreElements())
896       {
897         SelectionListener slis = ((SelectionListener) listeners
898                 .nextElement());
899         if (slis != source)
900         {
901           slis.selection(selection, colsel, source);
902         }
903         ;
904       }
905     }
906   }
907
908   Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
909
910   public synchronized void sendViewPosition(
911           jalview.api.AlignmentViewPanel source, int startRes, int endRes,
912           int startSeq, int endSeq)
913   {
914
915     if (view_listeners != null && view_listeners.size() > 0)
916     {
917       Enumeration<AlignmentViewPanelListener> listeners = view_listeners
918               .elements();
919       while (listeners.hasMoreElements())
920       {
921         AlignmentViewPanelListener slis = listeners.nextElement();
922         if (slis != source)
923         {
924           slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
925         }
926         ;
927       }
928     }
929   }
930
931   public void finalize() throws Throwable
932   {
933     if (listeners != null)
934     {
935       listeners.clear();
936       listeners = null;
937     }
938     if (pdbIdFileName != null)
939     {
940       pdbIdFileName.clear();
941       pdbIdFileName = null;
942     }
943     if (sel_listeners != null)
944     {
945       sel_listeners.clear();
946       sel_listeners = null;
947     }
948     if (view_listeners != null)
949     {
950       view_listeners.clear();
951       view_listeners = null;
952     }
953     mappings = null;
954     seqmappingrefs = null;
955   }
956
957   /**
958    * release all references associated with this manager provider
959    * 
960    * @param jalviewLite
961    */
962   public static void release(StructureSelectionManagerProvider jalviewLite)
963   {
964     // synchronized (instances)
965     {
966       if (instances == null)
967       {
968         return;
969       }
970       StructureSelectionManager mnger = (instances.get(jalviewLite));
971       if (mnger != null)
972       {
973         instances.remove(jalviewLite);
974         try
975         {
976           mnger.finalize();
977         } catch (Throwable x)
978         {
979         }
980         ;
981       }
982     }
983   }
984
985   public void registerPDBEntry(PDBEntry pdbentry)
986   {
987     if (pdbentry.getFile() != null
988             && pdbentry.getFile().trim().length() > 0)
989     {
990       registerPDBFile(pdbentry.getId(), pdbentry.getFile());
991     }
992   }
993
994 }