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