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