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