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