JAL-1622 code tidy only, no functional change
[jalview.git] / src / jalview / structure / StructureSelectionManager.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.structure;
22
23 import java.io.PrintStream;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.Enumeration;
28 import java.util.HashMap;
29 import java.util.IdentityHashMap;
30 import java.util.LinkedHashSet;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.Vector;
35
36 import MCview.Atom;
37 import MCview.PDBChain;
38 import MCview.PDBfile;
39
40 import jalview.analysis.AlignSeq;
41 import jalview.api.StructureSelectionManagerProvider;
42 import jalview.commands.CommandI;
43 import jalview.commands.EditCommand;
44 import jalview.commands.OrderCommand;
45 import jalview.datamodel.AlignedCodonFrame;
46 import jalview.datamodel.AlignmentAnnotation;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.Annotation;
49 import jalview.datamodel.PDBEntry;
50 import jalview.datamodel.SearchResults;
51 import jalview.datamodel.SequenceI;
52 import jalview.io.AppletFormatAdapter;
53 import jalview.util.MappingUtils;
54 import jalview.util.MessageManager;
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   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               seqListener.highlightSequence(results);
731             }
732           }
733         }
734         else if (listener instanceof VamsasListener && !handlingVamsasMo)
735         {
736           ((VamsasListener) listener).mouseOverSequence(seq, indexpos,
737                   source);
738         }
739         else if (listener instanceof SecondaryStructureListener)
740         {
741           ((SecondaryStructureListener) listener).mouseOverSequence(seq,
742                   indexpos);
743         }
744       }
745     }
746   }
747
748   /**
749    * Send suitable messages to a StructureListener to highlight atoms
750    * corresponding to the given sequence position.
751    * 
752    * @param sl
753    * @param seq
754    * @param index
755    */
756   protected void highlightStructure(StructureListener sl, SequenceI seq,
757           int index)
758   {
759     int atomNo;
760     List<AtomSpec> atoms = new ArrayList<AtomSpec>();
761     for (StructureMapping sm : mappings)
762     {
763       if (sm.sequence == seq || sm.sequence == seq.getDatasetSequence())
764       {
765         atomNo = sm.getAtomNum(index);
766
767         if (atomNo > 0)
768         {
769           atoms.add(new AtomSpec(sm.pdbfile, sm.pdbchain, sm
770                   .getPDBResNum(index), atomNo));
771         }
772       }
773     }
774     sl.highlightAtoms(atoms);
775   }
776
777   /**
778    * true if a mouse over event from an external (ie Vamsas) source is being
779    * handled
780    */
781   boolean handlingVamsasMo = false;
782
783   long lastmsg = 0;
784
785   /**
786    * as mouseOverSequence but only route event to SequenceListeners
787    * 
788    * @param sequenceI
789    * @param position
790    *          in an alignment sequence
791    */
792   public void mouseOverVamsasSequence(SequenceI sequenceI, int position,
793           VamsasSource source)
794   {
795     handlingVamsasMo = true;
796     long msg = sequenceI.hashCode() * (1 + position);
797     if (lastmsg != msg)
798     {
799       lastmsg = msg;
800       mouseOverSequence(sequenceI, position, -1, source);
801     }
802     handlingVamsasMo = false;
803   }
804
805   public Annotation[] colourSequenceFromStructure(SequenceI seq,
806           String pdbid)
807   {
808     return null;
809     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
810     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
811     /*
812      * Annotation [] annotations = new Annotation[seq.getLength()];
813      * 
814      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
815      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
816      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
817      * 
818      * for (int j = 0; j < mappings.length; j++) {
819      * 
820      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
821      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
822      * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
823      * "+mappings[j].pdbfile);
824      * 
825      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
826      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
827      * 
828      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
829      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
830      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
831      * mappings[j].pdbfile); }
832      * 
833      * annotations[index] = new Annotation("X",null,' ',0,col); } return
834      * annotations; } } } }
835      * 
836      * return annotations;
837      */
838   }
839
840   public void structureSelectionChanged()
841   {
842   }
843
844   public void sequenceSelectionChanged()
845   {
846   }
847
848   public void sequenceColoursChanged(Object source)
849   {
850     StructureListener sl;
851     for (int i = 0; i < listeners.size(); i++)
852     {
853       if (listeners.elementAt(i) instanceof StructureListener)
854       {
855         sl = (StructureListener) listeners.elementAt(i);
856         sl.updateColours(source);
857       }
858     }
859   }
860
861   public StructureMapping[] getMapping(String pdbfile)
862   {
863     List<StructureMapping> tmp = new ArrayList<StructureMapping>();
864     for (StructureMapping sm : mappings)
865     {
866       if (sm.pdbfile.equals(pdbfile))
867       {
868         tmp.add(sm);
869       }
870     }
871     return tmp.toArray(new StructureMapping[tmp.size()]);
872   }
873
874   /**
875    * Returns a readable description of all mappings for the given pdbfile to any
876    * of the given sequences
877    * 
878    * @param pdbfile
879    * @param seqs
880    * @return
881    */
882   public String printMappings(String pdbfile, List<SequenceI> seqs)
883   {
884     if (pdbfile == null || seqs == null || seqs.isEmpty())
885     {
886       return "";
887     }
888
889     StringBuilder sb = new StringBuilder(64);
890     for (StructureMapping sm : mappings)
891     {
892       if (sm.pdbfile.equals(pdbfile) && seqs.contains(sm.sequence))
893       {
894         sb.append(sm.mappingDetails);
895         sb.append(NEWLINE);
896         // separator makes it easier to read multiple mappings
897         sb.append("=====================");
898         sb.append(NEWLINE);
899       }
900     }
901     sb.append(NEWLINE);
902
903     return sb.toString();
904   }
905
906   /**
907    * Decrement the reference counter for each of the given mappings, and remove
908    * it entirely if its reference counter reduces to zero.
909    * 
910    * @param set
911    */
912   public void removeMappings(Set<AlignedCodonFrame> set)
913   {
914     if (set != null)
915     {
916       for (AlignedCodonFrame acf : set)
917       {
918         removeMapping(acf);
919       }
920     }
921   }
922
923   /**
924    * Decrement the reference counter for the given mapping, and remove it
925    * entirely if its reference counter reduces to zero.
926    * 
927    * @param acf
928    */
929   public void removeMapping(AlignedCodonFrame acf)
930   {
931     if (acf != null && seqmappings.contains(acf))
932     {
933       int count = seqMappingRefCounts.get(acf);
934       count--;
935       if (count > 0)
936       {
937         seqMappingRefCounts.put(acf, count);
938       }
939       else
940       {
941         seqmappings.remove(acf);
942         seqMappingRefCounts.remove(acf);
943       }
944     }
945   }
946
947   /**
948    * Add each of the given codonFrames to the stored set. If not aready present,
949    * increments its reference count instead.
950    * 
951    * @param set
952    */
953   public void addMappings(Set<AlignedCodonFrame> set)
954   {
955     if (set != null)
956     {
957       for (AlignedCodonFrame acf : set)
958       {
959         addMapping(acf);
960       }
961     }
962   }
963
964   /**
965    * Add the given mapping to the stored set, or if already stored, increment
966    * its reference counter.
967    */
968   public void addMapping(AlignedCodonFrame acf)
969   {
970     if (acf != null)
971     {
972       if (seqmappings.contains(acf))
973       {
974         seqMappingRefCounts.put(acf, seqMappingRefCounts.get(acf) + 1);
975       }
976       else
977       {
978         seqmappings.add(acf);
979         seqMappingRefCounts.put(acf, 1);
980       }
981     }
982   }
983
984   public void addSelectionListener(SelectionListener selecter)
985   {
986     if (!sel_listeners.contains(selecter))
987     {
988       sel_listeners.add(selecter);
989     }
990   }
991
992   public void removeSelectionListener(SelectionListener toremove)
993   {
994     if (sel_listeners.contains(toremove))
995     {
996       sel_listeners.remove(toremove);
997     }
998   }
999
1000   public synchronized void sendSelection(
1001           jalview.datamodel.SequenceGroup selection,
1002           jalview.datamodel.ColumnSelection colsel, SelectionSource source)
1003   {
1004     for (SelectionListener slis : sel_listeners)
1005     {
1006       if (slis != source)
1007       {
1008         slis.selection(selection, colsel, source);
1009       }
1010     }
1011   }
1012
1013   Vector<AlignmentViewPanelListener> view_listeners = new Vector<AlignmentViewPanelListener>();
1014
1015   public synchronized void sendViewPosition(
1016           jalview.api.AlignmentViewPanel source, int startRes, int endRes,
1017           int startSeq, int endSeq)
1018   {
1019
1020     if (view_listeners != null && view_listeners.size() > 0)
1021     {
1022       Enumeration<AlignmentViewPanelListener> listeners = view_listeners
1023               .elements();
1024       while (listeners.hasMoreElements())
1025       {
1026         AlignmentViewPanelListener slis = listeners.nextElement();
1027         if (slis != source)
1028         {
1029           slis.viewPosition(startRes, endRes, startSeq, endSeq, source);
1030         }
1031         ;
1032       }
1033     }
1034   }
1035
1036   /**
1037    * release all references associated with this manager provider
1038    * 
1039    * @param jalviewLite
1040    */
1041   public static void release(StructureSelectionManagerProvider jalviewLite)
1042   {
1043     // synchronized (instances)
1044     {
1045       if (instances == null)
1046       {
1047         return;
1048       }
1049       StructureSelectionManager mnger = (instances.get(jalviewLite));
1050       if (mnger != null)
1051       {
1052         instances.remove(jalviewLite);
1053         try
1054         {
1055           mnger.finalize();
1056         } catch (Throwable x)
1057         {
1058         }
1059       }
1060     }
1061   }
1062
1063   public void registerPDBEntry(PDBEntry pdbentry)
1064   {
1065     if (pdbentry.getFile() != null
1066             && pdbentry.getFile().trim().length() > 0)
1067     {
1068       registerPDBFile(pdbentry.getId(), pdbentry.getFile());
1069     }
1070   }
1071
1072   public void addCommandListener(CommandListener cl)
1073   {
1074     if (!commandListeners.contains(cl))
1075     {
1076       commandListeners.add(cl);
1077     }
1078   }
1079
1080   public boolean hasCommandListener(CommandListener cl)
1081   {
1082     return this.commandListeners.contains(cl);
1083   }
1084
1085   public boolean removeCommandListener(CommandListener l)
1086   {
1087     return commandListeners.remove(l);
1088   }
1089
1090   /**
1091    * Forward a command to any command listeners (except for the command's
1092    * source).
1093    * 
1094    * @param command
1095    *          the command to be broadcast (in its form after being performed)
1096    * @param undo
1097    *          if true, the command was being 'undone'
1098    * @param source
1099    */
1100   public void commandPerformed(CommandI command, boolean undo,
1101           VamsasSource source)
1102   {
1103     for (CommandListener listener : commandListeners)
1104     {
1105       listener.mirrorCommand(command, undo, this, source);
1106     }
1107   }
1108
1109   /**
1110    * Returns a new CommandI representing the given command as mapped to the
1111    * given sequences. If no mapping could be made, or the command is not of a
1112    * mappable kind, returns null.
1113    * 
1114    * @param command
1115    * @param undo
1116    * @param mapTo
1117    * @param gapChar
1118    * @return
1119    */
1120   public CommandI mapCommand(CommandI command, boolean undo,
1121           final AlignmentI mapTo, char gapChar)
1122   {
1123     if (command instanceof EditCommand)
1124     {
1125       return MappingUtils.mapEditCommand((EditCommand) command, undo,
1126               mapTo, gapChar, seqmappings);
1127     }
1128     else if (command instanceof OrderCommand)
1129     {
1130       return MappingUtils.mapOrderCommand((OrderCommand) command, undo,
1131               mapTo, seqmappings);
1132     }
1133     return null;
1134   }
1135 }