JAL-3949 Complete new abstracted logging framework in jalview.log. Updated log calls...
[jalview.git] / src / jalview / structures / models / AAStructureBindingModel.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.structures.models;
22
23 import java.util.Locale;
24
25 import java.awt.Color;
26 import java.io.File;
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.BitSet;
31 import java.util.HashMap;
32 import java.util.LinkedHashMap;
33 import java.util.List;
34 import java.util.Map;
35
36 import javax.swing.SwingUtilities;
37
38 import jalview.api.AlignViewportI;
39 import jalview.api.AlignmentViewPanel;
40 import jalview.api.FeatureRenderer;
41 import jalview.api.SequenceRenderer;
42 import jalview.api.StructureSelectionManagerProvider;
43 import jalview.api.structures.JalviewStructureDisplayI;
44 import jalview.bin.Cache;
45 import jalview.datamodel.AlignmentI;
46 import jalview.datamodel.HiddenColumns;
47 import jalview.datamodel.MappedFeatures;
48 import jalview.datamodel.PDBEntry;
49 import jalview.datamodel.SequenceFeature;
50 import jalview.datamodel.SequenceI;
51 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
52 import jalview.gui.AlignmentPanel;
53 import jalview.gui.Desktop;
54 import jalview.gui.StructureViewer.ViewerType;
55 import jalview.io.DataSourceType;
56 import jalview.io.StructureFile;
57 import jalview.renderer.seqfeatures.FeatureColourFinder;
58 import jalview.schemes.ColourSchemeI;
59 import jalview.schemes.ResidueProperties;
60 import jalview.structure.AtomSpec;
61 import jalview.structure.AtomSpecModel;
62 import jalview.structure.StructureCommandI;
63 import jalview.structure.StructureCommandsI;
64 import jalview.structure.StructureListener;
65 import jalview.structure.StructureMapping;
66 import jalview.structure.StructureSelectionManager;
67 import jalview.util.Comparison;
68 import jalview.util.MessageManager;
69
70 /**
71  * 
72  * A base class to hold common function for 3D structure model binding.
73  * Initial version created by refactoring JMol and Chimera binding models, but
74  * other structure viewers could in principle be accommodated in future.
75  * 
76  * @author gmcarstairs
77  *
78  */
79 public abstract class AAStructureBindingModel
80         extends SequenceStructureBindingModel
81         implements StructureListener, StructureSelectionManagerProvider
82 {
83   /**
84    * Data bean class to simplify parameterisation in superposeStructures
85    */
86   public static class SuperposeData
87   {
88     public String filename;
89
90     public String pdbId;
91
92     public String chain = "";
93
94     public boolean isRna;
95
96     /*
97      * The pdb residue number (if any) mapped to columns of the alignment
98      */
99     public int[] pdbResNo; // or use SparseIntArray?
100
101     public String modelId;
102
103     /**
104      * Constructor
105      * 
106      * @param width
107      *          width of alignment (number of columns that may potentially
108      *          participate in superposition)
109      * @param model
110      *          structure viewer model number
111      */
112     public SuperposeData(int width, String model)
113     {
114       pdbResNo = new int[width];
115       modelId = model;
116     }
117   }
118
119   private static final int MIN_POS_TO_SUPERPOSE = 4;
120
121   private static final String COLOURING_STRUCTURES = MessageManager
122           .getString("status.colouring_structures");
123
124   /*
125    * the Jalview panel through which the user interacts
126    * with the structure viewer
127    */
128   private JalviewStructureDisplayI viewer;
129
130   /*
131    * helper that generates command syntax
132    */
133   private StructureCommandsI commandGenerator;
134
135   private StructureSelectionManager ssm;
136
137   /*
138    * modelled chains, formatted as "pdbid:chainCode"
139    */
140   private List<String> chainNames;
141
142   /*
143    * lookup of pdb file name by key "pdbid:chainCode"
144    */
145   private Map<String, String> chainFile;
146
147   /*
148    * distinct PDB entries (pdb files) associated
149    * with sequences
150    */
151   private PDBEntry[] pdbEntry;
152
153   /*
154    * sequences mapped to each pdbentry
155    */
156   private SequenceI[][] sequence;
157
158   /*
159    * array of target chains for sequences - tied to pdbentry and sequence[]
160    */
161   private String[][] chains;
162
163   /*
164    * datasource protocol for access to PDBEntrylatest
165    */
166   DataSourceType protocol = null;
167
168   protected boolean colourBySequence = true;
169
170   private boolean nucleotide;
171
172   private boolean finishedInit = false;
173
174   /**
175    * current set of model filenames loaded in the viewer
176    */
177   protected String[] modelFileNames = null;
178
179   public String fileLoadingError;
180
181   protected Thread externalViewerMonitor;
182
183   /**
184    * Constructor
185    * 
186    * @param ssm
187    * @param seqs
188    */
189   public AAStructureBindingModel(StructureSelectionManager ssm,
190           SequenceI[][] seqs)
191   {
192     this.ssm = ssm;
193     this.sequence = seqs;
194     chainNames = new ArrayList<>();
195     chainFile = new HashMap<>();
196   }
197
198   /**
199    * Constructor
200    * 
201    * @param ssm
202    * @param pdbentry
203    * @param sequenceIs
204    * @param protocol
205    */
206   public AAStructureBindingModel(StructureSelectionManager ssm,
207           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
208           DataSourceType protocol)
209   {
210     this(ssm, sequenceIs);
211     this.nucleotide = Comparison.isNucleotide(sequenceIs);
212     this.pdbEntry = pdbentry;
213     this.protocol = protocol;
214     resolveChains();
215   }
216
217   private boolean resolveChains()
218   {
219     /**
220      * final count of chain mappings discovered
221      */
222     int chainmaps = 0;
223     // JBPNote: JAL-2693 - this should be a list of chain mappings per
224     // [pdbentry][sequence]
225     String[][] newchains = new String[pdbEntry.length][];
226     int pe = 0;
227     for (PDBEntry pdb : pdbEntry)
228     {
229       SequenceI[] seqsForPdb = sequence[pe];
230       if (seqsForPdb != null)
231       {
232         newchains[pe] = new String[seqsForPdb.length];
233         int se = 0;
234         for (SequenceI asq : seqsForPdb)
235         {
236           String chain = (chains != null && chains[pe] != null)
237                   ? chains[pe][se]
238                   : null;
239           SequenceI sq = (asq.getDatasetSequence() == null) ? asq
240                   : asq.getDatasetSequence();
241           if (sq.getAllPDBEntries() != null)
242           {
243             for (PDBEntry pdbentry : sq.getAllPDBEntries())
244             {
245               if (pdb.getFile() != null && pdbentry.getFile() != null
246                       && pdb.getFile().equals(pdbentry.getFile()))
247               {
248                 String chaincode = pdbentry.getChainCode();
249                 if (chaincode != null && chaincode.length() > 0)
250                 {
251                   chain = chaincode;
252                   chainmaps++;
253                   break;
254                 }
255               }
256             }
257           }
258           newchains[pe][se] = chain;
259           se++;
260         }
261         pe++;
262       }
263     }
264
265     chains = newchains;
266     return chainmaps > 0;
267   }
268
269   public StructureSelectionManager getSsm()
270   {
271     return ssm;
272   }
273
274   /**
275    * Returns the i'th PDBEntry (or null)
276    * 
277    * @param i
278    * @return
279    */
280   public PDBEntry getPdbEntry(int i)
281   {
282     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
283   }
284
285   /**
286    * Answers true if this binding includes the given PDB id, else false
287    * 
288    * @param pdbId
289    * @return
290    */
291   public boolean hasPdbId(String pdbId)
292   {
293     if (pdbEntry != null)
294     {
295       for (PDBEntry pdb : pdbEntry)
296       {
297         if (pdb.getId().equals(pdbId))
298         {
299           return true;
300         }
301       }
302     }
303     return false;
304   }
305
306   /**
307    * Returns the number of modelled PDB file entries.
308    * 
309    * @return
310    */
311   public int getPdbCount()
312   {
313     return pdbEntry == null ? 0 : pdbEntry.length;
314   }
315
316   public SequenceI[][] getSequence()
317   {
318     return sequence;
319   }
320
321   public String[][] getChains()
322   {
323     return chains;
324   }
325
326   public DataSourceType getProtocol()
327   {
328     return protocol;
329   }
330
331   // TODO may remove this if calling methods can be pulled up here
332   protected void setPdbentry(PDBEntry[] pdbentry)
333   {
334     this.pdbEntry = pdbentry;
335   }
336
337   protected void setSequence(SequenceI[][] sequence)
338   {
339     this.sequence = sequence;
340   }
341
342   protected void setChains(String[][] chains)
343   {
344     this.chains = chains;
345   }
346
347   /**
348    * Construct a title string for the viewer window based on the data Jalview
349    * knows about
350    * 
351    * @param viewerName
352    *          TODO
353    * @param verbose
354    * 
355    * @return
356    */
357   public String getViewerTitle(String viewerName, boolean verbose)
358   {
359     if (getSequence() == null || getSequence().length < 1
360             || getPdbCount() < 1 || getSequence()[0].length < 1)
361     {
362       return ("Jalview " + viewerName + " Window");
363     }
364     // TODO: give a more informative title when multiple structures are
365     // displayed.
366     StringBuilder title = new StringBuilder(64);
367     final PDBEntry pdbe = getPdbEntry(0);
368     title.append(viewerName + " view for " + getSequence()[0][0].getName()
369             + ":" + pdbe.getId());
370
371     if (verbose)
372     {
373       String method = (String) pdbe.getProperty("method");
374       if (method != null)
375       {
376         title.append(" Method: ").append(method);
377       }
378       String chain = (String) pdbe.getProperty("chains");
379       if (chain != null)
380       {
381         title.append(" Chain:").append(chain);
382       }
383     }
384     return title.toString();
385   }
386
387   /**
388    * Called by after closeViewer is called, to release any resources and
389    * references so they can be garbage collected. Override if needed.
390    */
391   protected void releaseUIResources()
392   {
393   }
394
395   @Override
396   public void releaseReferences(Object svl)
397   {
398   }
399
400   public boolean isColourBySequence()
401   {
402     return colourBySequence;
403   }
404
405   /**
406    * Called when the binding thinks the UI needs to be refreshed after a
407    * structure viewer state change. This could be because structures were
408    * loaded, or because an error has occurred. Default does nothing, override as
409    * required.
410    */
411   public void refreshGUI()
412   {
413   }
414
415   /**
416    * Instruct the Jalview binding to update the pdbentries vector if necessary
417    * prior to matching the jmol view's contents to the list of structure files
418    * Jalview knows about. By default does nothing, override as required.
419    */
420   public void refreshPdbEntries()
421   {
422   }
423
424   public void setColourBySequence(boolean colourBySequence)
425   {
426     this.colourBySequence = colourBySequence;
427   }
428
429   protected void addSequenceAndChain(int pe, SequenceI[] seq,
430           String[] tchain)
431   {
432     if (pe < 0 || pe >= getPdbCount())
433     {
434       throw new Error(MessageManager.formatMessage(
435               "error.implementation_error_no_pdbentry_from_index",
436               new Object[]
437               { Integer.valueOf(pe).toString() }));
438     }
439     final String nullChain = "TheNullChain";
440     List<SequenceI> s = new ArrayList<>();
441     List<String> c = new ArrayList<>();
442     if (getChains() == null)
443     {
444       setChains(new String[getPdbCount()][]);
445     }
446     if (getSequence()[pe] != null)
447     {
448       for (int i = 0; i < getSequence()[pe].length; i++)
449       {
450         s.add(getSequence()[pe][i]);
451         if (getChains()[pe] != null)
452         {
453           if (i < getChains()[pe].length)
454           {
455             c.add(getChains()[pe][i]);
456           }
457           else
458           {
459             c.add(nullChain);
460           }
461         }
462         else
463         {
464           if (tchain != null && tchain.length > 0)
465           {
466             c.add(nullChain);
467           }
468         }
469       }
470     }
471     for (int i = 0; i < seq.length; i++)
472     {
473       if (!s.contains(seq[i]))
474       {
475         s.add(seq[i]);
476         if (tchain != null && i < tchain.length)
477         {
478           c.add(tchain[i] == null ? nullChain : tchain[i]);
479         }
480       }
481     }
482     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
483     getSequence()[pe] = tmp;
484     if (c.size() > 0)
485     {
486       String[] tch = c.toArray(new String[c.size()]);
487       for (int i = 0; i < tch.length; i++)
488       {
489         if (tch[i] == nullChain)
490         {
491           tch[i] = null;
492         }
493       }
494       getChains()[pe] = tch;
495     }
496     else
497     {
498       getChains()[pe] = null;
499     }
500   }
501
502   /**
503    * add structures and any known sequence associations
504    * 
505    * @returns the pdb entries added to the current set.
506    */
507   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
508           SequenceI[][] seq, String[][] chns)
509   {
510     List<PDBEntry> v = new ArrayList<>();
511     List<int[]> rtn = new ArrayList<>();
512     for (int i = 0; i < getPdbCount(); i++)
513     {
514       v.add(getPdbEntry(i));
515     }
516     for (int i = 0; i < pdbe.length; i++)
517     {
518       int r = v.indexOf(pdbe[i]);
519       if (r == -1 || r >= getPdbCount())
520       {
521         rtn.add(new int[] { v.size(), i });
522         v.add(pdbe[i]);
523       }
524       else
525       {
526         // just make sure the sequence/chain entries are all up to date
527         addSequenceAndChain(r, seq[i], chns[i]);
528       }
529     }
530     pdbe = v.toArray(new PDBEntry[v.size()]);
531     setPdbentry(pdbe);
532     if (rtn.size() > 0)
533     {
534       // expand the tied sequence[] and string[] arrays
535       SequenceI[][] sqs = new SequenceI[getPdbCount()][];
536       String[][] sch = new String[getPdbCount()][];
537       System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
538       System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
539       setSequence(sqs);
540       setChains(sch);
541       pdbe = new PDBEntry[rtn.size()];
542       for (int r = 0; r < pdbe.length; r++)
543       {
544         int[] stri = (rtn.get(r));
545         // record the pdb file as a new addition
546         pdbe[r] = getPdbEntry(stri[0]);
547         // and add the new sequence/chain entries
548         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
549       }
550     }
551     else
552     {
553       pdbe = null;
554     }
555     return pdbe;
556   }
557
558   /**
559    * Add sequences to the pe'th pdbentry's sequence set.
560    * 
561    * @param pe
562    * @param seq
563    */
564   public void addSequence(int pe, SequenceI[] seq)
565   {
566     addSequenceAndChain(pe, seq, null);
567   }
568
569   /**
570    * add the given sequences to the mapping scope for the given pdb file handle
571    * 
572    * @param pdbFile
573    *          - pdbFile identifier
574    * @param seq
575    *          - set of sequences it can be mapped to
576    */
577   public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
578   {
579     for (int pe = 0; pe < getPdbCount(); pe++)
580     {
581       if (getPdbEntry(pe).getFile().equals(pdbFile))
582       {
583         addSequence(pe, seq);
584       }
585     }
586   }
587   
588
589   @Override
590   public abstract void highlightAtoms(List<AtomSpec> atoms);
591
592   protected boolean isNucleotide()
593   {
594     return this.nucleotide;
595   }
596
597   /**
598    * Returns a readable description of all mappings for the wrapped pdbfile to
599    * any mapped sequences
600    * 
601    * @param pdbfile
602    * @param seqs
603    * @return
604    */
605   public String printMappings()
606   {
607     if (pdbEntry == null)
608     {
609       return "";
610     }
611     StringBuilder sb = new StringBuilder(128);
612     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
613     {
614       String pdbfile = getPdbEntry(pdbe).getFile();
615       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
616       sb.append(getSsm().printMappings(pdbfile, seqs));
617     }
618     return sb.toString();
619   }
620
621   /**
622    * Returns the mapped structure position for a given aligned column of a given
623    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
624    * not mapped to structure.
625    * 
626    * @param seq
627    * @param alignedPos
628    * @param mapping
629    * @return
630    */
631   protected int getMappedPosition(SequenceI seq, int alignedPos,
632           StructureMapping mapping)
633   {
634     if (alignedPos >= seq.getLength())
635     {
636       return -1;
637     }
638
639     if (Comparison.isGap(seq.getCharAt(alignedPos)))
640     {
641       return -1;
642     }
643     int seqPos = seq.findPosition(alignedPos);
644     int pos = mapping.getPDBResNum(seqPos);
645     return pos;
646   }
647
648   /**
649    * Helper method to identify residues that can participate in a structure
650    * superposition command. For each structure, identify a sequence in the
651    * alignment which is mapped to the structure. Identify non-gapped columns in
652    * the sequence which have a mapping to a residue in the structure. Returns
653    * the index of the first structure that has a mapping to the alignment.
654    * 
655    * @param alignment
656    *          the sequence alignment which is the basis of structure
657    *          superposition
658    * @param matched
659    *          a BitSet, where bit j is set to indicate that every structure has
660    *          a mapped residue present in column j (so the column can
661    *          participate in structure alignment)
662    * @param structures
663    *          an array of data beans corresponding to pdb file index
664    * @return
665    */
666   protected int findSuperposableResidues(AlignmentI alignment,
667           BitSet matched,
668           AAStructureBindingModel.SuperposeData[] structures)
669   {
670     int refStructure = -1;
671     String[] files = getStructureFiles();
672     if (files == null)
673     {
674       return -1;
675     }
676     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
677     {
678       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
679       int lastPos = -1;
680
681       /*
682        * Find the first mapped sequence (if any) for this PDB entry which is in
683        * the alignment
684        */
685       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
686       for (int s = 0; s < seqCountForPdbFile; s++)
687       {
688         for (StructureMapping mapping : mappings)
689         {
690           final SequenceI theSequence = getSequence()[pdbfnum][s];
691           if (mapping.getSequence() == theSequence
692                   && alignment.findIndex(theSequence) > -1)
693           {
694             if (refStructure < 0)
695             {
696               refStructure = pdbfnum;
697             }
698             for (int r = 0; r < alignment.getWidth(); r++)
699             {
700               if (!matched.get(r))
701               {
702                 continue;
703               }
704               int pos = getMappedPosition(theSequence, r, mapping);
705               if (pos < 1 || pos == lastPos)
706               {
707                 matched.clear(r);
708                 continue;
709               }
710               lastPos = pos;
711               structures[pdbfnum].pdbResNo[r] = pos;
712             }
713             String chain = mapping.getChain();
714             if (chain != null && chain.trim().length() > 0)
715             {
716               structures[pdbfnum].chain = chain;
717             }
718             structures[pdbfnum].pdbId = mapping.getPdbId();
719             structures[pdbfnum].isRna = theSequence.getRNA() != null;
720
721             /*
722              * move on to next pdb file (ignore sequences for other chains
723              * for the same structure)
724              */
725             s = seqCountForPdbFile;
726             break; // fixme break out of two loops here!
727           }
728         }
729       }
730     }
731     return refStructure;
732   }
733
734   /**
735    * Returns true if the structure viewer has loaded all of the files of
736    * interest (identified by the file mapping having been set up), or false if
737    * any are still not loaded after a timeout interval.
738    * 
739    * @param files
740    */
741   protected boolean waitForFileLoad(String[] files)
742   {
743     /*
744      * give up after 10 secs plus 1 sec per file
745      */
746     long starttime = System.currentTimeMillis();
747     long endTime = 10000 + 1000 * files.length + starttime;
748     String notLoaded = null;
749
750     boolean waiting = true;
751     while (waiting && System.currentTimeMillis() < endTime)
752     {
753       waiting = false;
754       for (String file : files)
755       {
756         notLoaded = file;
757         if (file == null)
758         {
759           continue;
760         }
761         try
762         {
763           StructureMapping[] sm = getSsm().getMapping(file);
764           if (sm == null || sm.length == 0)
765           {
766             waiting = true;
767           }
768         } catch (Throwable x)
769         {
770           waiting = true;
771         }
772       }
773     }
774
775     if (waiting)
776     {
777       System.err.println(
778               "Timed out waiting for structure viewer to load file "
779                       + notLoaded);
780       return false;
781     }
782     return true;
783   }
784
785   @Override
786   public boolean isListeningFor(SequenceI seq)
787   {
788     if (sequence != null)
789     {
790       for (SequenceI[] seqs : sequence)
791       {
792         if (seqs != null)
793         {
794           for (SequenceI s : seqs)
795           {
796             if (s == seq || (s.getDatasetSequence() != null
797                     && s.getDatasetSequence() == seq.getDatasetSequence()))
798             {
799               return true;
800             }
801           }
802         }
803       }
804     }
805     return false;
806   }
807
808   public boolean isFinishedInit()
809   {
810     return finishedInit;
811   }
812
813   public void setFinishedInit(boolean fi)
814   {
815     this.finishedInit = fi;
816   }
817
818   /**
819    * Returns a list of chains mapped in this viewer, formatted as
820    * "pdbid:chainCode"
821    * 
822    * @return
823    */
824   public List<String> getChainNames()
825   {
826     return chainNames;
827   }
828
829   /**
830    * Returns the Jalview panel hosting the structure viewer (if any)
831    * 
832    * @return
833    */
834   public JalviewStructureDisplayI getViewer()
835   {
836     return viewer;
837   }
838
839   public void setViewer(JalviewStructureDisplayI v)
840   {
841     viewer = v;
842   }
843
844   /**
845    * Constructs and sends a command to align structures against a reference
846    * structure, based on one or more sequence alignments. May optionally return
847    * an error or warning message for the alignment command(s).
848    * 
849    * @param alignWith
850    *          an array of one or more alignment views to process
851    * @return
852    */
853   public String superposeStructures(List<AlignmentViewPanel> alignWith)
854   {
855     String error = "";
856     String[] files = getStructureFiles();
857
858     if (!waitForFileLoad(files))
859     {
860       return null;
861     }
862     refreshPdbEntries();
863
864     for (AlignmentViewPanel view : alignWith)
865     {
866       AlignmentI alignment = view.getAlignment();
867       HiddenColumns hiddenCols = alignment.getHiddenColumns();
868
869       /*
870        * 'matched' bit i will be set for visible alignment columns i where
871        * all sequences have a residue with a mapping to their PDB structure
872        */
873       BitSet matched = new BitSet();
874       final int width = alignment.getWidth();
875       for (int m = 0; m < width; m++)
876       {
877         if (hiddenCols == null || hiddenCols.isVisible(m))
878         {
879           matched.set(m);
880         }
881       }
882
883       AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
884       for (int f = 0; f < files.length; f++)
885       {
886         structures[f] = new AAStructureBindingModel.SuperposeData(width,
887                 getModelIdForFile(files[f]));
888       }
889
890       /*
891        * Calculate the superposable alignment columns ('matched'), and the
892        * corresponding structure residue positions (structures.pdbResNo)
893        */
894       int refStructure = findSuperposableResidues(alignment, matched,
895               structures);
896
897       /*
898        * require at least 4 positions to be able to execute superposition
899        */
900       int nmatched = matched.cardinality();
901       if (nmatched < MIN_POS_TO_SUPERPOSE)
902       {
903         String msg = MessageManager
904                 .formatMessage("label.insufficient_residues", nmatched);
905         error += view.getViewName() + ": " + msg + "; ";
906         continue;
907       }
908
909       /*
910        * get a model of the superposable residues in the reference structure 
911        */
912       AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
913               matched);
914
915       /*
916        * Show all as backbone before doing superposition(s)
917        * (residues used for matching will be shown as ribbon)
918        */
919       // todo better way to ensure synchronous than setting getReply true!!
920       executeCommands(commandGenerator.showBackbone(), true, null);
921
922       /*
923        * superpose each (other) structure to the reference in turn
924        */
925       for (int i = 0; i < structures.length; i++)
926       {
927         if (i != refStructure)
928         {
929           AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
930           List<StructureCommandI> commands = commandGenerator
931                   .superposeStructures(refAtoms, atomSpec);
932           List<String> replies = executeCommands(commands, true, null);
933           for (String reply : replies)
934           {
935             // return this error (Chimera only) to the user
936             if (reply.toLowerCase(Locale.ROOT).contains("unequal numbers of atoms"))
937             {
938               error += "; " + reply;
939             }
940           }
941         }
942       }
943     }
944
945     return error;
946   }
947
948   private AtomSpecModel getAtomSpec(
949           AAStructureBindingModel.SuperposeData superposeData,
950           BitSet matched)
951   {
952     AtomSpecModel model = new AtomSpecModel();
953     int nextColumnMatch = matched.nextSetBit(0);
954     while (nextColumnMatch != -1)
955     {
956       int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
957       model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
958               superposeData.chain);
959       nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
960     }
961
962     return model;
963   }
964
965   /**
966    * returns the current sequenceRenderer that should be used to colour the
967    * structures
968    * 
969    * @param alignment
970    * 
971    * @return
972    */
973   public abstract SequenceRenderer getSequenceRenderer(
974           AlignmentViewPanel alignment);
975
976   /**
977    * Sends a command to the structure viewer to colour each chain with a
978    * distinct colour (to the extent supported by the viewer)
979    */
980   public void colourByChain()
981   {
982     colourBySequence = false;
983
984     // TODO: JAL-628 colour chains distinctly across all visible models
985
986     executeCommand(false, COLOURING_STRUCTURES,
987             commandGenerator.colourByChain());
988   }
989
990   /**
991    * Sends a command to the structure viewer to colour each chain with a
992    * distinct colour (to the extent supported by the viewer)
993    */
994   public void colourByCharge()
995   {
996     colourBySequence = false;
997
998     executeCommands(commandGenerator.colourByCharge(), false,
999             COLOURING_STRUCTURES);
1000   }
1001
1002   /**
1003    * Sends a command to the structure to apply a colour scheme (defined in
1004    * Jalview but not necessarily applied to the alignment), which defines a
1005    * colour per residue letter. More complex schemes (e.g. that depend on
1006    * consensus) cannot be used here and are ignored.
1007    * 
1008    * @param cs
1009    */
1010   public void colourByJalviewColourScheme(ColourSchemeI cs)
1011   {
1012     colourBySequence = false;
1013
1014     if (cs == null || !cs.isSimple())
1015     {
1016       return;
1017     }
1018
1019     /*
1020      * build a map of {Residue3LetterCode, Color}
1021      */
1022     Map<String, Color> colours = new HashMap<>();
1023     List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1024             false);
1025     for (String resName : residues)
1026     {
1027       char res = resName.length() == 3
1028               ? ResidueProperties.getSingleCharacterCode(resName)
1029               : resName.charAt(0);
1030       Color colour = cs.findColour(res, 0, null, null, 0f);
1031       colours.put(resName, colour);
1032     }
1033
1034     /*
1035      * pass to the command constructor, and send the command
1036      */
1037     List<StructureCommandI> cmd = commandGenerator
1038             .colourByResidues(colours);
1039     executeCommands(cmd, false, COLOURING_STRUCTURES);
1040   }
1041
1042   public void setBackgroundColour(Color col)
1043   {
1044     StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1045     executeCommand(false, null, cmd);
1046   }
1047
1048   /**
1049    * Execute one structure viewer command. If {@code getReply} is true, may
1050    * optionally return one or more reply messages, else returns null.
1051    * 
1052    * @param cmd
1053    * @param getReply
1054    */
1055   protected abstract List<String> executeCommand(StructureCommandI cmd,
1056           boolean getReply);
1057
1058   /**
1059    * Executes one or more structure viewer commands
1060    * 
1061    * @param commands
1062    * @param getReply
1063    * @param msg
1064    */
1065   protected List<String> executeCommands(List<StructureCommandI> commands,
1066           boolean getReply, String msg)
1067   {
1068     return executeCommand(getReply, msg,
1069             commands.toArray(new StructureCommandI[commands.size()]));
1070   }
1071
1072   /**
1073    * Executes one or more structure viewer commands, optionally returning the
1074    * reply, and optionally showing a status message while the command is being
1075    * executed.
1076    * <p>
1077    * If a reply is wanted, the execution is done synchronously (waits),
1078    * otherwise it is done in a separate thread (doesn't wait). WARNING: if you
1079    * are sending commands that need to execute before later calls to
1080    * executeCommand (e.g. mouseovers, which clean up after previous ones) then
1081    * set getReply true to ensure that commands are not executed out of order.
1082    * 
1083    * @param getReply
1084    * @param msg
1085    * @param cmds
1086    * @return
1087    */
1088   protected List<String> executeCommand(boolean getReply, String msg,
1089           StructureCommandI... cmds)
1090   {
1091     JalviewStructureDisplayI theViewer = getViewer();
1092     final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1093
1094     if (getReply)
1095     {
1096       /*
1097        * execute and wait for reply
1098        */
1099       List<String> response = new ArrayList<>();
1100       try
1101       {
1102         for (StructureCommandI cmd : cmds)
1103         {
1104           List<String> replies = executeCommand(cmd, true);
1105           if (replies != null)
1106           {
1107             response.addAll(replies);
1108           }
1109         }
1110         return response;
1111       } finally
1112       {
1113         if (msg != null)
1114         {
1115           theViewer.stopProgressBar(null, handle);
1116         }
1117       }
1118     }
1119
1120     /*
1121      * fire and forget
1122      */
1123     String threadName = msg == null ? "StructureCommand" : msg;
1124     new Thread(new Runnable()
1125     {
1126       @Override
1127       public void run()
1128       {
1129         try
1130         {
1131           for (StructureCommandI cmd : cmds)
1132           {
1133             executeCommand(cmd, false);
1134           }
1135         } finally
1136         {
1137           if (msg != null)
1138           {
1139             SwingUtilities.invokeLater(new Runnable()
1140             {
1141               @Override
1142               public void run()
1143               {
1144                 theViewer.stopProgressBar(null, handle);
1145               }
1146             });
1147           }
1148         }
1149       }
1150     }, threadName).start();
1151     return null;
1152   }
1153
1154   /**
1155    * Colours any structures associated with sequences in the given alignment as
1156    * coloured in the alignment view, provided colourBySequence is enabled
1157    */
1158   public void colourBySequence(AlignmentViewPanel alignmentv)
1159   {
1160     if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1161     {
1162       return;
1163     }
1164     Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1165             alignmentv);
1166
1167     List<StructureCommandI> colourBySequenceCommands = commandGenerator
1168             .colourBySequence(colourMap);
1169     executeCommands(colourBySequenceCommands, false, COLOURING_STRUCTURES);
1170   }
1171
1172   /**
1173    * Centre the display in the structure viewer
1174    */
1175   public void focusView()
1176   {
1177     executeCommand(false, null, commandGenerator.focusView());
1178   }
1179
1180   /**
1181    * Generates and executes a command to show only specified chains in the
1182    * structure viewer. The list of chains to show should contain entries
1183    * formatted as "pdbid:chaincode".
1184    * 
1185    * @param toShow
1186    */
1187   public void showChains(List<String> toShow)
1188   {
1189     // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1190
1191     /*
1192      * Reformat the pdbid:chainCode values as modelNo:chainCode
1193      * since this is what is needed to construct the viewer command
1194      * todo: find a less messy way to do this
1195      */
1196     List<String> showThese = new ArrayList<>();
1197     for (String chainId : toShow)
1198     {
1199       String[] tokens = chainId.split("\\:");
1200       if (tokens.length == 2)
1201       {
1202         String pdbFile = getFileForChain(chainId);
1203         String model = getModelIdForFile(pdbFile);
1204         showThese.add(model + ":" + tokens[1]);
1205       }
1206     }
1207     executeCommands(commandGenerator.showChains(showThese), false, null);
1208   }
1209
1210   /**
1211    * Answers the structure viewer's model id given a PDB file name. Returns an
1212    * empty string if model id is not found.
1213    * 
1214    * @param chainId
1215    * @return
1216    */
1217   protected abstract String getModelIdForFile(String chainId);
1218
1219   public boolean hasFileLoadingError()
1220   {
1221     return fileLoadingError != null && fileLoadingError.length() > 0;
1222   }
1223
1224   /**
1225    * Returns the FeatureRenderer for the given alignment view
1226    * 
1227    * @param avp
1228    * @return
1229    */
1230   public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1231   {
1232     AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1233             : avp;
1234     if (ap == null)
1235     {
1236       return null;
1237     }
1238     return ap.getFeatureRenderer();
1239   }
1240
1241   protected void setStructureCommands(StructureCommandsI cmd)
1242   {
1243     commandGenerator = cmd;
1244   }
1245
1246   /**
1247    * Records association of one chain id (formatted as "pdbid:chainCode") with
1248    * the corresponding PDB file name
1249    * 
1250    * @param chainId
1251    * @param fileName
1252    */
1253   public void addChainFile(String chainId, String fileName)
1254   {
1255     chainFile.put(chainId, fileName);
1256   }
1257
1258   /**
1259    * Returns the PDB filename for the given chain id (formatted as
1260    * "pdbid:chainCode"), or null if not found
1261    * 
1262    * @param chainId
1263    * @return
1264    */
1265   protected String getFileForChain(String chainId)
1266   {
1267     return chainFile.get(chainId);
1268   }
1269
1270   @Override
1271   public void updateColours(Object source)
1272   {
1273     AlignmentViewPanel ap = (AlignmentViewPanel) source;
1274     // ignore events from panels not used to colour this view
1275     if (!getViewer().isUsedForColourBy(ap))
1276     {
1277       return;
1278     }
1279     if (!isLoadingFromArchive())
1280     {
1281       colourBySequence(ap);
1282     }
1283   }
1284
1285   public StructureCommandsI getCommandGenerator()
1286   {
1287     return commandGenerator;
1288   }
1289
1290   protected abstract ViewerType getViewerType();
1291
1292   /**
1293    * Builds a data structure which records mapped structure residues for each
1294    * colour. From this we can easily generate the viewer commands for colour by
1295    * sequence. Constructs and returns a map of {@code Color} to
1296    * {@code AtomSpecModel}, where the atomspec model holds
1297    * 
1298    * <pre>
1299    *   Model ids
1300    *     Chains
1301    *       Residue positions
1302    * </pre>
1303    * 
1304    * Ordering is by order of addition (for colours), natural ordering (for
1305    * models and chains)
1306    * 
1307    * @param ssm
1308    * @param sequence
1309    * @param viewPanel
1310    * @return
1311    */
1312   protected Map<Object, AtomSpecModel> buildColoursMap(
1313           StructureSelectionManager ssm, SequenceI[][] sequence,
1314           AlignmentViewPanel viewPanel)
1315   {
1316     String[] files = getStructureFiles();
1317     SequenceRenderer sr = getSequenceRenderer(viewPanel);
1318     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1319     FeatureColourFinder finder = new FeatureColourFinder(fr);
1320     AlignViewportI viewport = viewPanel.getAlignViewport();
1321     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1322     AlignmentI al = viewport.getAlignment();
1323     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1324     Color lastColour = null;
1325
1326     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1327     {
1328       final String modelId = getModelIdForFile(files[pdbfnum]);
1329       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1330
1331       if (mapping == null || mapping.length < 1)
1332       {
1333         continue;
1334       }
1335
1336       int startPos = -1, lastPos = -1;
1337       String lastChain = "";
1338       for (int s = 0; s < sequence[pdbfnum].length; s++)
1339       {
1340         for (int sp, m = 0; m < mapping.length; m++)
1341         {
1342           final SequenceI seq = sequence[pdbfnum][s];
1343           if (mapping[m].getSequence() == seq
1344                   && (sp = al.findIndex(seq)) > -1)
1345           {
1346             SequenceI asp = al.getSequenceAt(sp);
1347             for (int r = 0; r < asp.getLength(); r++)
1348             {
1349               // no mapping to gaps in sequence
1350               if (Comparison.isGap(asp.getCharAt(r)))
1351               {
1352                 continue;
1353               }
1354               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1355
1356               if (pos < 1 || pos == lastPos)
1357               {
1358                 continue;
1359               }
1360
1361               Color colour = sr.getResidueColour(seq, r, finder);
1362
1363               /*
1364                * darker colour for hidden regions
1365                */
1366               if (!cs.isVisible(r))
1367               {
1368                 colour = Color.GRAY;
1369               }
1370
1371               final String chain = mapping[m].getChain();
1372
1373               /*
1374                * Just keep incrementing the end position for this colour range
1375                * _unless_ colour, PDB model or chain has changed, or there is a
1376                * gap in the mapped residue sequence
1377                */
1378               final boolean newColour = !colour.equals(lastColour);
1379               final boolean nonContig = lastPos + 1 != pos;
1380               final boolean newChain = !chain.equals(lastChain);
1381               if (newColour || nonContig || newChain)
1382               {
1383                 if (startPos != -1)
1384                 {
1385                   addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1386                           lastPos, lastChain);
1387                 }
1388                 startPos = pos;
1389               }
1390               lastColour = colour;
1391               lastPos = pos;
1392               lastChain = chain;
1393             }
1394             // final colour range
1395             if (lastColour != null)
1396             {
1397               addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1398                       lastPos, lastChain);
1399             }
1400             // break;
1401           }
1402         }
1403       }
1404     }
1405     return colourMap;
1406   }
1407
1408   /**
1409    * todo better refactoring (map lookup or similar to get viewer structure id)
1410    * 
1411    * @param pdbfnum
1412    * @param file
1413    * @return
1414    */
1415   protected String getModelId(int pdbfnum, String file)
1416   {
1417     return String.valueOf(pdbfnum);
1418   }
1419
1420   /**
1421    * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1422    * full PDB file path
1423    * 
1424    * @param pdb
1425    * @param file
1426    */
1427   public void stashFoundChains(StructureFile pdb, String file)
1428   {
1429     for (int i = 0; i < pdb.getChains().size(); i++)
1430     {
1431       String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1432       addChainFile(chid, file);
1433       getChainNames().add(chid);
1434     }
1435   }
1436
1437   /**
1438    * Helper method to add one contiguous range to the AtomSpec model for the
1439    * given value (creating the model if necessary). As used by Jalview,
1440    * {@code value} is
1441    * <ul>
1442    * <li>a colour, when building a 'colour structure by sequence' command</li>
1443    * <li>a feature value, when building a 'set Chimera attributes from features'
1444    * command</li>
1445    * </ul>
1446    * 
1447    * @param map
1448    * @param value
1449    * @param model
1450    * @param startPos
1451    * @param endPos
1452    * @param chain
1453    */
1454   public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1455           Object value, String model, int startPos, int endPos,
1456           String chain)
1457   {
1458     /*
1459      * Get/initialize map of data for the colour
1460      */
1461     AtomSpecModel atomSpec = map.get(value);
1462     if (atomSpec == null)
1463     {
1464       atomSpec = new AtomSpecModel();
1465       map.put(value, atomSpec);
1466     }
1467
1468     atomSpec.addRange(model, startPos, endPos, chain);
1469   }
1470
1471   /**
1472    * Returns the file extension (including '.' separator) to use for a saved
1473    * viewer session file. Default is to return null (not supported), override as
1474    * required.
1475    * 
1476    * @return
1477    */
1478   public String getSessionFileExtension()
1479   {
1480     return null;
1481   }
1482
1483   /**
1484    * If supported, saves the state of the structure viewer to a temporary file
1485    * and returns the file. Returns null and logs an error on any failure.
1486    * 
1487    * @return
1488    */
1489   public File saveSession()
1490   {
1491     String prefix = getViewerType().toString();
1492     String suffix = getSessionFileExtension();
1493     File f = null;
1494     try
1495     {
1496       f = File.createTempFile(prefix, suffix);
1497       saveSession(f);
1498     } catch (IOException e)
1499     {
1500       Cache.error(String.format("Error saving %s session: %s", prefix,
1501               e.toString()));
1502     }
1503
1504     return f;
1505   }
1506
1507   /**
1508    * Saves the structure viewer session to the given file
1509    * 
1510    * @param f
1511    */
1512   protected void saveSession(File f)
1513   {
1514     StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1515     if (cmd != null)
1516     {
1517       executeCommand(cmd, false);
1518     }
1519   }
1520
1521   /**
1522    * Returns true if the viewer is an external structure viewer for which the
1523    * process is still alive, else false (for Jmol, or an external viewer which
1524    * the user has independently closed)
1525    * 
1526    * @return
1527    */
1528   public boolean isViewerRunning()
1529   {
1530     return false;
1531   }
1532
1533   /**
1534    * Closes Jalview's structure viewer panel and releases associated resources.
1535    * If it is managing an external viewer program, and {@code forceClose} is
1536    * true, also asks that program to close.
1537    * 
1538    * @param forceClose
1539    */
1540   public void closeViewer(boolean forceClose)
1541   {
1542     getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1543     releaseUIResources();
1544
1545     /*
1546      * end the thread that closes this panel if the external viewer closes
1547      */
1548     if (externalViewerMonitor != null)
1549     {
1550       externalViewerMonitor.interrupt();
1551       externalViewerMonitor = null;
1552     }
1553
1554     stopListening();
1555
1556     if (forceClose)
1557     {
1558       StructureCommandI cmd = getCommandGenerator().closeViewer();
1559       if (cmd != null)
1560       {
1561         executeCommand(cmd, false);
1562       }
1563     }
1564   }
1565
1566   /**
1567    * Returns the URL of a help page for the structure viewer, or null if none is
1568    * known
1569    * 
1570    * @return
1571    */
1572   public String getHelpURL()
1573   {
1574     return null;
1575   }
1576
1577   /**
1578    * <pre>
1579    * Helper method to build a map of 
1580    *   { featureType, { feature value, AtomSpecModel } }
1581    * </pre>
1582    * 
1583    * @param viewPanel
1584    * @return
1585    */
1586   protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1587           AlignmentViewPanel viewPanel)
1588   {
1589     Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1590     String[] files = getStructureFiles();
1591     if (files == null)
1592     {
1593       return theMap;
1594     }
1595
1596     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1597     if (fr == null)
1598     {
1599       return theMap;
1600     }
1601
1602     AlignViewportI viewport = viewPanel.getAlignViewport();
1603     List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1604
1605     /*
1606      * if alignment is showing features from complement, we also transfer
1607      * these features to the corresponding mapped structure residues
1608      */
1609     boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1610     List<String> complementFeatures = new ArrayList<>();
1611     FeatureRenderer complementRenderer = null;
1612     if (showLinkedFeatures)
1613     {
1614       AlignViewportI comp = fr.getViewport().getCodingComplement();
1615       if (comp != null)
1616       {
1617         complementRenderer = Desktop.getAlignFrameFor(comp)
1618                 .getFeatureRenderer();
1619         complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1620       }
1621     }
1622     if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1623     {
1624       return theMap;
1625     }
1626
1627     AlignmentI alignment = viewPanel.getAlignment();
1628     SequenceI[][] seqs = getSequence();
1629
1630     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1631     {
1632       String modelId = getModelIdForFile(files[pdbfnum]);
1633       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1634
1635       if (mapping == null || mapping.length < 1)
1636       {
1637         continue;
1638       }
1639
1640       for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1641       {
1642         for (int m = 0; m < mapping.length; m++)
1643         {
1644           final SequenceI seq = seqs[pdbfnum][seqNo];
1645           int sp = alignment.findIndex(seq);
1646           StructureMapping structureMapping = mapping[m];
1647           if (structureMapping.getSequence() == seq && sp > -1)
1648           {
1649             /*
1650              * found a sequence with a mapping to a structure;
1651              * now scan its features
1652              */
1653             if (!visibleFeatures.isEmpty())
1654             {
1655               scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1656                       theMap, modelId);
1657             }
1658             if (showLinkedFeatures)
1659             {
1660               scanComplementFeatures(complementRenderer, structureMapping,
1661                       seq, theMap, modelId);
1662             }
1663           }
1664         }
1665       }
1666     }
1667     return theMap;
1668   }
1669
1670   /**
1671    * Ask the structure viewer to open a session file. Returns true if
1672    * successful, else false (or not supported).
1673    * 
1674    * @param filepath
1675    * @return
1676    */
1677   public boolean openSession(String filepath)
1678   {
1679     StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1680     if (cmd == null)
1681     {
1682       return false;
1683     }
1684     executeCommand(cmd, true);
1685     // todo: test for failure - how?
1686     return true;
1687   }
1688
1689   /**
1690    * Scans visible features in mapped positions of the CDS/peptide complement,
1691    * and adds any found to the map of attribute values/structure positions
1692    * 
1693    * @param complementRenderer
1694    * @param structureMapping
1695    * @param seq
1696    * @param theMap
1697    * @param modelNumber
1698    */
1699   protected static void scanComplementFeatures(
1700           FeatureRenderer complementRenderer,
1701           StructureMapping structureMapping, SequenceI seq,
1702           Map<String, Map<Object, AtomSpecModel>> theMap,
1703           String modelNumber)
1704   {
1705     /*
1706      * for each sequence residue mapped to a structure position...
1707      */
1708     for (int seqPos : structureMapping.getMapping().keySet())
1709     {
1710       /*
1711        * find visible complementary features at mapped position(s)
1712        */
1713       MappedFeatures mf = complementRenderer
1714               .findComplementFeaturesAtResidue(seq, seqPos);
1715       if (mf != null)
1716       {
1717         for (SequenceFeature sf : mf.features)
1718         {
1719           String type = sf.getType();
1720
1721           /*
1722            * Don't copy features which originated from Chimera
1723            */
1724           if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1725                   .equals(sf.getFeatureGroup()))
1726           {
1727             continue;
1728           }
1729
1730           /*
1731            * record feature 'value' (score/description/type) as at the
1732            * corresponding structure position
1733            */
1734           List<int[]> mappedRanges = structureMapping
1735                   .getPDBResNumRanges(seqPos, seqPos);
1736
1737           if (!mappedRanges.isEmpty())
1738           {
1739             String value = sf.getDescription();
1740             if (value == null || value.length() == 0)
1741             {
1742               value = type;
1743             }
1744             float score = sf.getScore();
1745             if (score != 0f && !Float.isNaN(score))
1746             {
1747               value = Float.toString(score);
1748             }
1749             Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1750             if (featureValues == null)
1751             {
1752               featureValues = new HashMap<>();
1753               theMap.put(type, featureValues);
1754             }
1755             for (int[] range : mappedRanges)
1756             {
1757               addAtomSpecRange(featureValues, value, modelNumber, range[0],
1758                       range[1], structureMapping.getChain());
1759             }
1760           }
1761         }
1762       }
1763     }
1764   }
1765
1766   /**
1767    * Inspect features on the sequence; for each feature that is visible,
1768    * determine its mapped ranges in the structure (if any) according to the
1769    * given mapping, and add them to the map.
1770    * 
1771    * @param visibleFeatures
1772    * @param mapping
1773    * @param seq
1774    * @param theMap
1775    * @param modelId
1776    */
1777   protected static void scanSequenceFeatures(List<String> visibleFeatures,
1778           StructureMapping mapping, SequenceI seq,
1779           Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1780   {
1781     List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1782             visibleFeatures.toArray(new String[visibleFeatures.size()]));
1783     for (SequenceFeature sf : sfs)
1784     {
1785       String type = sf.getType();
1786
1787       /*
1788        * Don't copy features which originated from Chimera
1789        */
1790       if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1791               .equals(sf.getFeatureGroup()))
1792       {
1793         continue;
1794       }
1795
1796       List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1797               sf.getEnd());
1798
1799       if (!mappedRanges.isEmpty())
1800       {
1801         String value = sf.getDescription();
1802         if (value == null || value.length() == 0)
1803         {
1804           value = type;
1805         }
1806         float score = sf.getScore();
1807         if (score != 0f && !Float.isNaN(score))
1808         {
1809           value = Float.toString(score);
1810         }
1811         Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1812         if (featureValues == null)
1813         {
1814           featureValues = new HashMap<>();
1815           theMap.put(type, featureValues);
1816         }
1817         for (int[] range : mappedRanges)
1818         {
1819           addAtomSpecRange(featureValues, value, modelId, range[0],
1820                   range[1], mapping.getChain());
1821         }
1822       }
1823     }
1824   }
1825
1826   /**
1827    * Returns the number of structure files in the structure viewer and mapped to
1828    * Jalview. This may be zero if the files are still in the process of loading
1829    * in the viewer.
1830    * 
1831    * @return
1832    */
1833   public int getMappedStructureCount()
1834   {
1835     String[] files = getStructureFiles();
1836     return files == null ? 0 : files.length;
1837   }
1838
1839   /**
1840    * Starts a thread that waits for the external viewer program process to
1841    * finish, so that we can then close the associated resources. This avoids
1842    * leaving orphaned viewer panels in Jalview if the user closes the external
1843    * viewer.
1844    * 
1845    * @param p
1846    */
1847   protected void startExternalViewerMonitor(Process p)
1848   {
1849     externalViewerMonitor = new Thread(new Runnable()
1850     {
1851
1852       @Override
1853       public void run()
1854       {
1855         try
1856         {
1857           p.waitFor();
1858           JalviewStructureDisplayI display = getViewer();
1859           if (display != null)
1860           {
1861             display.closeViewer(false);
1862           }
1863         } catch (InterruptedException e)
1864         {
1865           // exit thread if Chimera Viewer is closed in Jalview
1866         }
1867       }
1868     });
1869     externalViewerMonitor.start();
1870   }
1871
1872   /**
1873    * If supported by the external structure viewer, sends it commands to notify
1874    * model or selection changes to the specified URL (where Jalview has started
1875    * a listener)
1876    * 
1877    * @param uri
1878    */
1879   protected void startListening(String uri)
1880   {
1881     List<StructureCommandI> commands = getCommandGenerator()
1882             .startNotifications(uri);
1883     if (commands != null)
1884     {
1885       executeCommands(commands, false, null);
1886     }
1887   }
1888
1889   /**
1890    * If supported by the external structure viewer, sends it commands to stop
1891    * notifying model or selection changes
1892    */
1893   protected void stopListening()
1894   {
1895     List<StructureCommandI> commands = getCommandGenerator()
1896             .stopNotifications();
1897     if (commands != null)
1898     {
1899       executeCommands(commands, false, null);
1900     }
1901   }
1902
1903   /**
1904    * If supported by the structure viewer, queries it for all residue attributes
1905    * with the given attribute name, and creates features on corresponding
1906    * residues of the alignment. Returns the number of features added.
1907    * 
1908    * @param attName
1909    * @param alignmentPanel
1910    * @return
1911    */
1912   public int copyStructureAttributesToFeatures(String attName,
1913           AlignmentPanel alignmentPanel)
1914   {
1915     StructureCommandI cmd = getCommandGenerator()
1916             .getResidueAttributes(attName);
1917     if (cmd == null)
1918     {
1919       return 0;
1920     }
1921     List<String> residueAttributes = executeCommand(cmd, true);
1922
1923     int featuresAdded = createFeaturesForAttributes(attName,
1924             residueAttributes);
1925     if (featuresAdded > 0)
1926     {
1927       alignmentPanel.getFeatureRenderer().featuresAdded();
1928     }
1929     return featuresAdded;
1930   }
1931
1932   /**
1933    * Parses {@code residueAttributes} and creates sequence features on any
1934    * mapped alignment residues. Returns the number of features created.
1935    * <p>
1936    * {@code residueAttributes} is the reply from the structure viewer to a
1937    * command to list any residue attributes for the given attribute name. Syntax
1938    * and parsing of this is viewer-specific.
1939    * 
1940    * @param attName
1941    * @param residueAttributes
1942    * @return
1943    */
1944   protected int createFeaturesForAttributes(String attName,
1945           List<String> residueAttributes)
1946   {
1947     return 0;
1948   }
1949 }