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