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