refactored VamsasListener to allow the source of the event to be passed to handlers
[jalview.git] / src / jalview / structure / StructureSelectionManager.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3  * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.structure;
19
20 import java.io.*;
21 import java.util.*;
22
23 import MCview.*;
24 import jalview.analysis.*;
25 import jalview.datamodel.*;
26
27 public class StructureSelectionManager
28 {
29   static StructureSelectionManager instance;
30
31   StructureMapping[] mappings;
32
33   Hashtable mappingData = new Hashtable();
34
35   public static StructureSelectionManager getStructureSelectionManager()
36   {
37     if (instance == null)
38     {
39       instance = new StructureSelectionManager();
40     }
41
42     return instance;
43   }
44
45   /**
46    * flag controlling whether SeqMappings are relayed from received sequence
47    * mouse over events to other sequences
48    */
49   boolean relaySeqMappings = true;
50
51   /**
52    * Enable or disable relay of seqMapping events to other sequences. You might
53    * want to do this if there are many sequence mappings and the host computer
54    * is slow
55    * 
56    * @param relay
57    */
58   public void setRelaySeqMappings(boolean relay)
59   {
60     relaySeqMappings = relay;
61   }
62
63   /**
64    * get the state of the relay seqMappings flag.
65    * 
66    * @return true if sequence mouse overs are being relayed to other mapped
67    *         sequences
68    */
69   public boolean isRelaySeqMappingsEnabled()
70   {
71     return relaySeqMappings;
72   }
73
74   Vector listeners = new Vector();
75
76   /**
77    * register a listener for alignment sequence mouseover events
78    * @param svl
79    */
80   public void addStructureViewerListener(Object svl)
81   {
82     if (!listeners.contains(svl))
83     {
84       listeners.addElement(svl);
85     }
86   }
87
88   public String alreadyMappedToFile(String pdbid)
89   {
90     if (mappings != null)
91     {
92       for (int i = 0; i < mappings.length; i++)
93       {
94         if (mappings[i].getPdbId().equals(pdbid))
95         {
96           return mappings[i].pdbfile;
97         }
98       }
99     }
100     return null;
101   }
102
103   /**
104    * create sequence structure mappings between each sequence and the given
105    * pdbFile (retrieved via the given protocol).
106    * 
107    * @param sequence
108    *          - one or more sequences to be mapped to pdbFile
109    * @param targetChains
110    *          - optional chain specification for mapping each sequence to pdb
111    *          (may be nill, individual elements may be nill)
112    * @param pdbFile
113    *          - structure data resource
114    * @param protocol
115    *          - how to resolve data from resource
116    * @return null or the structure data parsed as a pdb file
117    */
118   synchronized public MCview.PDBfile setMapping(SequenceI[] sequence,
119           String[] targetChains, String pdbFile, String protocol)
120   {
121     /*
122      * There will be better ways of doing this in the future, for now we'll use
123      * the tried and tested MCview pdb mapping
124      */
125     MCview.PDBfile pdb = null;
126     try
127     {
128       pdb = new MCview.PDBfile(pdbFile, protocol);
129     } catch (Exception ex)
130     {
131       ex.printStackTrace();
132       return null;
133     }
134
135     String targetChain;
136     for (int s = 0; s < sequence.length; s++)
137     {
138       if (targetChains != null && targetChains[s] != null)
139         targetChain = targetChains[s];
140       else if (sequence[s].getName().indexOf("|") > -1)
141       {
142         targetChain = sequence[s].getName().substring(
143                 sequence[s].getName().lastIndexOf("|") + 1);
144       }
145       else
146         targetChain = "";
147
148       int max = -10;
149       AlignSeq maxAlignseq = null;
150       String maxChainId = " ";
151       PDBChain maxChain = null;
152       boolean first = true;
153       for (int i = 0; i < pdb.chains.size(); i++)
154       {
155         // TODO: re http://issues.jalview.org/browse/JAL-583 : this patch may
156         // need to be revoked
157         PDBChain chain = ((PDBChain) pdb.chains.elementAt(i));
158         if (targetChain.length() > 0 && !targetChain.equals(chain.id))
159         {
160           continue; // don't try to map chains don't match.
161         }
162         // end of patch for limiting computed mappings
163         // TODO: correctly determine sequence type for mixed na/peptide
164         // structures
165         AlignSeq as = new AlignSeq(sequence[s],
166                 ((PDBChain) pdb.chains.elementAt(i)).sequence,
167                 ((PDBChain) pdb.chains.elementAt(i)).isNa ? AlignSeq.DNA
168                         : AlignSeq.PEP);
169         as.calcScoreMatrix();
170         as.traceAlignment();
171
172         if (first || as.maxscore > max
173                 || (as.maxscore == max && chain.id.equals(targetChain)))
174         {
175           first = false;
176           maxChain = chain;
177           max = as.maxscore;
178           maxAlignseq = as;
179           maxChainId = chain.id;
180         }
181       }
182       if (maxChain == null)
183       {
184         continue;
185       }
186       final StringBuffer mappingDetails = new StringBuffer();
187       mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
188               + maxChain.sequence.getSequenceAsString());
189       mappingDetails.append("\nNo of residues = "
190               + maxChain.residues.size() + "\n\n");
191       PrintStream ps = new PrintStream(System.out)
192       {
193         public void print(String x)
194         {
195           mappingDetails.append(x);
196         }
197
198         public void println()
199         {
200           mappingDetails.append("\n");
201         }
202       };
203
204       maxAlignseq.printAlignment(ps);
205
206       mappingDetails.append("\nPDB start/end " + maxAlignseq.seq2start
207               + " " + maxAlignseq.seq2end);
208       mappingDetails.append("\nSEQ start/end "
209               + (maxAlignseq.seq1start + sequence[s].getStart() - 1) + " "
210               + (maxAlignseq.seq1end + sequence[s].getEnd() - 1));
211
212       maxChain.makeExactMapping(maxAlignseq, sequence[s]);
213
214       maxChain.transferRESNUMFeatures(sequence[s], null);
215
216       int[][] mapping = new int[sequence[s].getEnd() + 2][2];
217       int resNum = -10000;
218       int index = 0;
219
220       do
221       {
222         Atom tmp = (Atom) maxChain.atoms.elementAt(index);
223         if (resNum != tmp.resNumber && tmp.alignmentMapping != -1)
224         {
225           resNum = tmp.resNumber;
226           mapping[tmp.alignmentMapping + 1][0] = tmp.resNumber;
227           mapping[tmp.alignmentMapping + 1][1] = tmp.atomIndex;
228         }
229
230         index++;
231       } while (index < maxChain.atoms.size());
232
233       if (mappings == null)
234       {
235         mappings = new StructureMapping[1];
236       }
237       else
238       {
239         StructureMapping[] tmp = new StructureMapping[mappings.length + 1];
240         System.arraycopy(mappings, 0, tmp, 0, mappings.length);
241         mappings = tmp;
242       }
243
244       if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
245         pdbFile = "INLINE" + pdb.id;
246
247       mappings[mappings.length - 1] = new StructureMapping(sequence[s],
248               pdbFile, pdb.id, maxChainId, mapping,
249               mappingDetails.toString());
250       maxChain.transferResidueAnnotation(mappings[mappings.length - 1]);
251     }
252     // ///////
253
254     return pdb;
255   }
256
257   public void removeStructureViewerListener(Object svl, String[] pdbfiles)
258   {
259     listeners.removeElement(svl);
260     if (pdbfiles == null)
261     {
262       return;
263     }
264     boolean removeMapping = true;
265     String[] handlepdbs;
266     Vector pdbs = new Vector();
267     for (int i = 0; i < pdbfiles.length; pdbs.addElement(pdbfiles[i++]))
268       ;
269     StructureListener sl;
270     for (int i = 0; i < listeners.size(); i++)
271     {
272       if (listeners.elementAt(i) instanceof StructureListener)
273       {
274         sl = (StructureListener) listeners.elementAt(i);
275         handlepdbs = sl.getPdbFile();
276         for (int j = 0; j < handlepdbs.length; j++)
277         {
278           if (pdbs.contains(handlepdbs[j]))
279           {
280             pdbs.removeElement(handlepdbs[j]);
281           }
282         }
283
284       }
285     }
286
287     if (pdbs.size() > 0 && mappings != null)
288     {
289       Vector tmp = new Vector();
290       for (int i = 0; i < mappings.length; i++)
291       {
292         if (!pdbs.contains(mappings[i].pdbfile))
293         {
294           tmp.addElement(mappings[i]);
295         }
296       }
297
298       mappings = new StructureMapping[tmp.size()];
299       tmp.copyInto(mappings);
300     }
301   }
302
303   public void mouseOverStructure(int pdbResNum, String chain, String pdbfile)
304   {
305     boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
306     SearchResults results = null;
307     for (int i = 0; i < listeners.size(); i++)
308     {
309       if (listeners.elementAt(i) instanceof SequenceListener)
310       {
311         if (results == null)
312         {
313           results = new SearchResults();
314         }
315         int indexpos;
316         if (mappings != null)
317         {
318           for (int j = 0; j < mappings.length; j++)
319           {
320             if (mappings[j].pdbfile.equals(pdbfile)
321                     && mappings[j].pdbchain.equals(chain))
322             {
323               indexpos = mappings[j].getSeqPos(pdbResNum);
324               results.addResult(mappings[j].sequence, indexpos, indexpos);
325               // construct highlighted sequence list
326               if (seqmappings != null)
327               {
328
329                 Enumeration e = seqmappings.elements();
330                 while (e.hasMoreElements())
331
332                 {
333                   ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
334                           mappings[j].sequence, indexpos, results);
335                 }
336               }
337             }
338           }
339         }
340       }
341     }
342     if (results.getSize() > 0)
343     {
344       for (int i = 0; i < listeners.size(); i++)
345       {
346         Object li = listeners.elementAt(i);
347         if (li instanceof SequenceListener)
348           ((SequenceListener) li).highlightSequence(results);
349       }
350     }
351   }
352
353   Vector seqmappings = null; // should be a simpler list of mapped seuqence
354
355   /**
356    * highlight regions associated with a position (indexpos) in seq
357    * 
358    * @param seq
359    *          the sequeence that the mouse over occured on
360    * @param indexpos
361    *          the absolute position being mouseovered in seq (0 to seq.length())
362    * @param index
363    *          the sequence position (if -1, seq.findPosition is called to
364    *          resolve the residue number)
365    */
366   public void mouseOverSequence(SequenceI seq, int indexpos, int index, VamsasSource source)
367   {
368     boolean hasSequenceListeners = handlingVamsasMo || seqmappings != null;
369     SearchResults results = null;
370     if (index == -1)
371       index = seq.findPosition(indexpos);
372     StructureListener sl;
373     int atomNo = 0;
374     for (int i = 0; i < listeners.size(); i++)
375     {
376       if (listeners.elementAt(i) instanceof StructureListener)
377       {
378         sl = (StructureListener) listeners.elementAt(i);
379         if (mappings == null)
380         {
381           continue;
382         }
383         for (int j = 0; j < mappings.length; j++)
384         {
385           if (mappings[j].sequence == seq
386                   || mappings[j].sequence == seq.getDatasetSequence())
387           {
388             atomNo = mappings[j].getAtomNum(index);
389
390             if (atomNo > 0)
391             {
392               sl.highlightAtom(atomNo, mappings[j].getPDBResNum(index),
393                       mappings[j].pdbchain, mappings[j].pdbfile);
394             }
395           }
396         }
397       }
398       else
399       {
400         if (relaySeqMappings && hasSequenceListeners
401                 && listeners.elementAt(i) instanceof SequenceListener)
402         {
403           // DEBUG
404           // System.err.println("relay Seq " + seq.getDisplayId(false) + " " +
405           // index);
406
407           if (results == null)
408           {
409             results = new SearchResults();
410             if (index >= seq.getStart() && index <= seq.getEnd())
411             {
412               // construct highlighted sequence list
413
414               if (seqmappings != null)
415               {
416                 Enumeration e = seqmappings.elements();
417                 while (e.hasMoreElements())
418
419                 {
420                   ((AlignedCodonFrame) e.nextElement()).markMappedRegion(
421                           seq, index, results);
422                 }
423               }
424               // hasSequenceListeners = results.getSize() > 0;
425               if (handlingVamsasMo)
426               {
427                 // maybe have to resolve seq to a dataset seqeunce...
428                 // add in additional direct sequence and/or dataset sequence
429                 // highlighting
430                 results.addResult(seq, index, index);
431               }
432             }
433           }
434           if (hasSequenceListeners)
435           {
436             ((SequenceListener) listeners.elementAt(i))
437                     .highlightSequence(results);
438           }
439         }
440         else if (listeners.elementAt(i) instanceof VamsasListener
441                 && !handlingVamsasMo)
442         {
443           // DEBUG
444           // System.err.println("Vamsas from Seq " + seq.getDisplayId(false) + "
445           // " +
446           // index);
447           // pass the mouse over and absolute position onto the
448           // VamsasListener(s)
449           ((VamsasListener) listeners.elementAt(i))
450                   .mouseOver(seq, indexpos, source);
451         }
452       }
453     }
454   }
455
456   /**
457    * true if a mouse over event from an external (ie Vamsas) source is being
458    * handled
459    */
460   boolean handlingVamsasMo = false;
461
462   long lastmsg = 0;
463
464   /**
465    * as mouseOverSequence but only route event to SequenceListeners
466    * 
467    * @param sequenceI
468    * @param position
469    *          in an alignment sequence
470    */
471   public void mouseOverVamsasSequence(SequenceI sequenceI, int position, VamsasSource source)
472   {
473     handlingVamsasMo = true;
474     long msg = sequenceI.hashCode() * (1 + position);
475     if (lastmsg != msg)
476     {
477       lastmsg = msg;
478       mouseOverSequence(sequenceI, position, -1, source);
479     }
480     handlingVamsasMo = false;
481   }
482
483   public Annotation[] colourSequenceFromStructure(SequenceI seq,
484           String pdbid)
485   {
486     return null;
487     // THIS WILL NOT BE AVAILABLE IN JALVIEW 2.3,
488     // UNTIL THE COLOUR BY ANNOTATION IS REWORKED
489     /*
490      * Annotation [] annotations = new Annotation[seq.getLength()];
491      * 
492      * StructureListener sl; int atomNo = 0; for (int i = 0; i <
493      * listeners.size(); i++) { if (listeners.elementAt(i) instanceof
494      * StructureListener) { sl = (StructureListener) listeners.elementAt(i);
495      * 
496      * for (int j = 0; j < mappings.length; j++) {
497      * 
498      * if (mappings[j].sequence == seq && mappings[j].getPdbId().equals(pdbid)
499      * && mappings[j].pdbfile.equals(sl.getPdbFile())) {
500      * System.out.println(pdbid+" "+mappings[j].getPdbId() +"
501      * "+mappings[j].pdbfile);
502      * 
503      * java.awt.Color col; for(int index=0; index<seq.getLength(); index++) {
504      * if(jalview.util.Comparison.isGap(seq.getCharAt(index))) continue;
505      * 
506      * atomNo = mappings[j].getAtomNum(seq.findPosition(index)); col =
507      * java.awt.Color.white; if (atomNo > 0) { col = sl.getColour(atomNo,
508      * mappings[j].getPDBResNum(index), mappings[j].pdbchain,
509      * mappings[j].pdbfile); }
510      * 
511      * annotations[index] = new Annotation("X",null,' ',0,col); } return
512      * annotations; } } } }
513      * 
514      * return annotations;
515      */
516   }
517
518   public void structureSelectionChanged()
519   {
520   }
521
522   public void sequenceSelectionChanged()
523   {
524   }
525
526   public void sequenceColoursChanged(Object source)
527   {
528     StructureListener sl;
529     for (int i = 0; i < listeners.size(); i++)
530     {
531       if (listeners.elementAt(i) instanceof StructureListener)
532       {
533         sl = (StructureListener) listeners.elementAt(i);
534         sl.updateColours(source);
535       }
536     }
537   }
538
539   public StructureMapping[] getMapping(String pdbfile)
540   {
541     Vector tmp = new Vector();
542     if (mappings != null)
543     {
544       for (int i = 0; i < mappings.length; i++)
545       {
546         if (mappings[i].pdbfile.equals(pdbfile))
547         {
548           tmp.addElement(mappings[i]);
549         }
550       }
551     }
552     StructureMapping[] ret = new StructureMapping[tmp.size()];
553     for (int i = 0; i < tmp.size(); i++)
554     {
555       ret[i] = (StructureMapping) tmp.elementAt(i);
556     }
557
558     return ret;
559   }
560
561   public String printMapping(String pdbfile)
562   {
563     StringBuffer sb = new StringBuffer();
564     for (int i = 0; i < mappings.length; i++)
565     {
566       if (mappings[i].pdbfile.equals(pdbfile))
567       {
568         sb.append(mappings[i].mappingDetails);
569       }
570     }
571
572     return sb.toString();
573   }
574
575   private int[] seqmappingrefs = null; // refcount for seqmappings elements
576
577   private synchronized void modifySeqMappingList(boolean add,
578           AlignedCodonFrame[] codonFrames)
579   {
580     if (!add && (seqmappings == null || seqmappings.size() == 0))
581       return;
582     if (seqmappings == null)
583       seqmappings = new Vector();
584     if (codonFrames != null && codonFrames.length > 0)
585     {
586       for (int cf = 0; cf < codonFrames.length; cf++)
587       {
588         if (seqmappings.contains(codonFrames[cf]))
589         {
590           if (add)
591           {
592             seqmappingrefs[seqmappings.indexOf(codonFrames[cf])]++;
593           }
594           else
595           {
596             if (--seqmappingrefs[seqmappings.indexOf(codonFrames[cf])] <= 0)
597             {
598               int pos = seqmappings.indexOf(codonFrames[cf]);
599               int[] nr = new int[seqmappingrefs.length - 1];
600               if (pos > 0)
601               {
602                 System.arraycopy(seqmappingrefs, 0, nr, 0, pos);
603               }
604               if (pos < seqmappingrefs.length - 1)
605               {
606                 System.arraycopy(seqmappingrefs, pos + 1, nr, 0,
607                         seqmappingrefs.length - pos - 2);
608               }
609             }
610           }
611         }
612         else
613         {
614           if (add)
615           {
616             seqmappings.addElement(codonFrames[cf]);
617
618             int[] nsr = new int[(seqmappingrefs == null) ? 1
619                     : seqmappingrefs.length + 1];
620             if (seqmappingrefs != null && seqmappingrefs.length > 0)
621               System.arraycopy(seqmappingrefs, 0, nsr, 0,
622                       seqmappingrefs.length);
623             nsr[(seqmappingrefs == null) ? 0 : seqmappingrefs.length] = 1;
624             seqmappingrefs = nsr;
625           }
626         }
627       }
628     }
629   }
630
631   public void removeMappings(AlignedCodonFrame[] codonFrames)
632   {
633     modifySeqMappingList(false, codonFrames);
634   }
635
636   public void addMappings(AlignedCodonFrame[] codonFrames)
637   {
638     modifySeqMappingList(true, codonFrames);
639   }
640
641   Vector sel_listeners = new Vector();
642
643   public void addSelectionListener(SelectionListener selecter)
644   {
645     if (!sel_listeners.contains(selecter))
646     {
647       sel_listeners.addElement(selecter);
648     }
649   }
650
651   public void removeSelectionListener(SelectionListener toremove)
652   {
653     if (sel_listeners.contains(toremove))
654     {
655       sel_listeners.removeElement(toremove);
656     }
657   }
658
659   public synchronized void sendSelection(
660           jalview.datamodel.SequenceGroup selection,
661           jalview.datamodel.ColumnSelection colsel, SelectionSource source)
662   {
663     if (sel_listeners != null && sel_listeners.size() > 0)
664     {
665       Enumeration listeners = sel_listeners.elements();
666       while (listeners.hasMoreElements())
667       {
668         SelectionListener slis = ((SelectionListener) listeners
669                 .nextElement());
670         if (slis != source)
671         {
672           slis.selection(selection, colsel, source);
673         }
674         ;
675       }
676     }
677   }
678 }