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