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