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