JAL-4026 ignore StructureSelectionManager events if no viewer is available to act...
[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.awt.Color;
24 import java.io.File;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.BitSet;
29 import java.util.HashMap;
30 import java.util.LinkedHashMap;
31 import java.util.List;
32 import java.util.Locale;
33 import java.util.Map;
34
35 import javax.swing.SwingUtilities;
36
37 import jalview.api.AlignViewportI;
38 import jalview.api.AlignmentViewPanel;
39 import jalview.api.FeatureRenderer;
40 import jalview.api.SequenceRenderer;
41 import jalview.api.StructureSelectionManagerProvider;
42 import jalview.api.structures.JalviewStructureDisplayI;
43 import jalview.bin.Console;
44 import jalview.datamodel.AlignmentI;
45 import jalview.datamodel.HiddenColumns;
46 import jalview.datamodel.MappedFeatures;
47 import jalview.datamodel.PDBEntry;
48 import jalview.datamodel.SequenceFeature;
49 import jalview.datamodel.SequenceI;
50 import jalview.ext.rbvi.chimera.JalviewChimeraBinding;
51 import jalview.gui.AlignmentPanel;
52 import jalview.gui.Desktop;
53 import jalview.gui.StructureViewer.ViewerType;
54 import jalview.io.DataSourceType;
55 import jalview.io.StructureFile;
56 import jalview.renderer.seqfeatures.FeatureColourFinder;
57 import jalview.schemes.ColourSchemeI;
58 import jalview.schemes.ResidueProperties;
59 import jalview.structure.AtomSpec;
60 import jalview.structure.AtomSpecModel;
61 import jalview.structure.StructureCommandI;
62 import jalview.structure.StructureCommandsI;
63 import jalview.structure.StructureCommandsI.AtomSpecType;
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. Initial
73  * version created by refactoring JMol and Chimera binding models, but other
74  * 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   @Override
595   public abstract void highlightAtoms(List<AtomSpec> atoms);
596
597   protected boolean isNucleotide()
598   {
599     return this.nucleotide;
600   }
601
602   /**
603    * Returns a readable description of all mappings for the wrapped pdbfile to
604    * any mapped sequences
605    * 
606    * @param pdbfile
607    * @param seqs
608    * @return
609    */
610   public String printMappings()
611   {
612     if (pdbEntry == null)
613     {
614       return "";
615     }
616     StringBuilder sb = new StringBuilder(128);
617     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
618     {
619       String pdbfile = getPdbEntry(pdbe).getFile();
620       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
621       sb.append(getSsm().printMappings(pdbfile, seqs));
622     }
623     return sb.toString();
624   }
625
626   /**
627    * Returns the mapped structure position for a given aligned column of a given
628    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
629    * not mapped to structure.
630    * 
631    * @param seq
632    * @param alignedPos
633    * @param mapping
634    * @return
635    */
636   protected int getMappedPosition(SequenceI seq, int alignedPos,
637           StructureMapping mapping)
638   {
639     if (alignedPos >= seq.getLength())
640     {
641       return -1;
642     }
643
644     if (Comparison.isGap(seq.getCharAt(alignedPos)))
645     {
646       return -1;
647     }
648     int seqPos = seq.findPosition(alignedPos);
649     int pos = mapping.getPDBResNum(seqPos);
650     return pos;
651   }
652
653   /**
654    * Helper method to identify residues that can participate in a structure
655    * superposition command. For each structure, identify a sequence in the
656    * alignment which is mapped to the structure. Identify non-gapped columns in
657    * the sequence which have a mapping to a residue in the structure. Returns
658    * the index of the first structure that has a mapping to the alignment.
659    * 
660    * @param alignment
661    *          the sequence alignment which is the basis of structure
662    *          superposition
663    * @param matched
664    *          a BitSet, where bit j is set to indicate that every structure has
665    *          a mapped residue present in column j (so the column can
666    *          participate in structure alignment)
667    * @param structures
668    *          an array of data beans corresponding to pdb file index
669    * @return
670    */
671   protected int findSuperposableResidues(AlignmentI alignment,
672           BitSet matched,
673           AAStructureBindingModel.SuperposeData[] structures)
674   {
675     int refStructure = -1;
676     String[] files = getStructureFiles();
677     if (files == null)
678     {
679       return -1;
680     }
681     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
682     {
683       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
684       int lastPos = -1;
685
686       /*
687        * Find the first mapped sequence (if any) for this PDB entry which is in
688        * the alignment
689        */
690       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
691       for (int s = 0; s < seqCountForPdbFile; s++)
692       {
693         for (StructureMapping mapping : mappings)
694         {
695           final SequenceI theSequence = getSequence()[pdbfnum][s];
696           if (mapping.getSequence() == theSequence
697                   && alignment.findIndex(theSequence) > -1)
698           {
699             if (refStructure < 0)
700             {
701               refStructure = pdbfnum;
702             }
703             for (int r = 0; r < alignment.getWidth(); r++)
704             {
705               if (!matched.get(r))
706               {
707                 continue;
708               }
709               int pos = getMappedPosition(theSequence, r, mapping);
710               if (pos < 1 || pos == lastPos)
711               {
712                 matched.clear(r);
713                 continue;
714               }
715               lastPos = pos;
716               structures[pdbfnum].pdbResNo[r] = pos;
717             }
718             String chain = mapping.getChain();
719             if (chain != null && chain.trim().length() > 0)
720             {
721               structures[pdbfnum].chain = chain;
722             }
723             structures[pdbfnum].pdbId = mapping.getPdbId();
724             structures[pdbfnum].isRna = !theSequence.isProtein();
725
726             /*
727              * move on to next pdb file (ignore sequences for other chains
728              * for the same structure)
729              */
730             s = seqCountForPdbFile;
731             break; // fixme break out of two loops here!
732           }
733         }
734       }
735     }
736     return refStructure;
737   }
738
739   /**
740    * Returns true if the structure viewer has loaded all of the files of
741    * interest (identified by the file mapping having been set up), or false if
742    * any are still not loaded after a timeout interval.
743    * 
744    * @param files
745    */
746   protected boolean waitForFileLoad(String[] files)
747   {
748     /*
749      * give up after 10 secs plus 1 sec per file
750      */
751     long starttime = System.currentTimeMillis();
752     long endTime = 10000 + 1000 * files.length + starttime;
753     String notLoaded = null;
754
755     boolean waiting = true;
756     while (waiting && System.currentTimeMillis() < endTime)
757     {
758       waiting = false;
759       for (String file : files)
760       {
761         notLoaded = file;
762         if (file == null)
763         {
764           continue;
765         }
766         try
767         {
768           StructureMapping[] sm = getSsm().getMapping(file);
769           if (sm == null || sm.length == 0)
770           {
771             waiting = true;
772           }
773         } catch (Throwable x)
774         {
775           waiting = true;
776         }
777       }
778     }
779
780     if (waiting)
781     {
782       System.err.println(
783               "Timed out waiting for structure viewer to load file "
784                       + notLoaded);
785       return false;
786     }
787     return true;
788   }
789
790   @Override
791   public boolean isListeningFor(SequenceI seq)
792   {
793     if (sequence != null)
794     {
795       for (SequenceI[] seqs : sequence)
796       {
797         if (seqs != null)
798         {
799           for (SequenceI s : seqs)
800           {
801             if (s == seq || (s.getDatasetSequence() != null
802                     && s.getDatasetSequence() == seq.getDatasetSequence()))
803             {
804               return true;
805             }
806           }
807         }
808       }
809     }
810     return false;
811   }
812
813   public boolean isFinishedInit()
814   {
815     return finishedInit;
816   }
817
818   public void setFinishedInit(boolean fi)
819   {
820     this.finishedInit = fi;
821   }
822
823   /**
824    * Returns a list of chains mapped in this viewer, formatted as
825    * "pdbid:chainCode"
826    * 
827    * @return
828    */
829   public List<String> getChainNames()
830   {
831     return chainNames;
832   }
833
834   /**
835    * Returns the Jalview panel hosting the structure viewer (if any)
836    * 
837    * @return
838    */
839   public JalviewStructureDisplayI getViewer()
840   {
841     return viewer;
842   }
843
844   public void setViewer(JalviewStructureDisplayI v)
845   {
846     viewer = v;
847   }
848
849   /**
850    * Constructs and sends a command to align structures against a reference
851    * structure, based on one or more sequence alignments. May optionally return
852    * an error or warning message for the alignment command(s).
853    * 
854    * @param alignWith
855    *          an array of one or more alignment views to process
856    * @return
857    */
858   public String superposeStructures(List<AlignmentViewPanel> alignWith)
859   {
860     String error = "";
861     String[] files = getStructureFiles();
862
863     if (!waitForFileLoad(files))
864     {
865       return null;
866     }
867     refreshPdbEntries();
868
869     for (AlignmentViewPanel view : alignWith)
870     {
871       AlignmentI alignment = view.getAlignment();
872       HiddenColumns hiddenCols = alignment.getHiddenColumns();
873
874       /*
875        * 'matched' bit i will be set for visible alignment columns i where
876        * all sequences have a residue with a mapping to their PDB structure
877        */
878       BitSet matched = new BitSet();
879       final int width = alignment.getWidth();
880       for (int m = 0; m < width; m++)
881       {
882         if (hiddenCols == null || hiddenCols.isVisible(m))
883         {
884           matched.set(m);
885         }
886       }
887
888       AAStructureBindingModel.SuperposeData[] structures = new AAStructureBindingModel.SuperposeData[files.length];
889       for (int f = 0; f < files.length; f++)
890       {
891         structures[f] = new AAStructureBindingModel.SuperposeData(width,
892                 getModelIdForFile(files[f]));
893       }
894
895       /*
896        * Calculate the superposable alignment columns ('matched'), and the
897        * corresponding structure residue positions (structures.pdbResNo)
898        */
899       int refStructure = findSuperposableResidues(alignment, matched,
900               structures);
901
902       /*
903        * require at least 4 positions to be able to execute superposition
904        */
905       int nmatched = matched.cardinality();
906       if (nmatched < MIN_POS_TO_SUPERPOSE)
907       {
908         String msg = MessageManager
909                 .formatMessage("label.insufficient_residues", nmatched);
910         error += view.getViewName() + ": " + msg + "; ";
911         continue;
912       }
913
914       /*
915        * get a model of the superposable residues in the reference structure 
916        */
917       AtomSpecModel refAtoms = getAtomSpec(structures[refStructure],
918               matched);
919
920       /*
921        * Show all as backbone before doing superposition(s)
922        * (residues used for matching will be shown as ribbon)
923        */
924       // todo better way to ensure synchronous than setting getReply true!!
925       executeCommands(commandGenerator.showBackbone(), true, null);
926
927       AtomSpecType backbone = structures[refStructure].isRna
928               ? AtomSpecType.PHOSPHATE
929               : AtomSpecType.ALPHA;
930       /*
931        * superpose each (other) structure to the reference in turn
932        */
933       for (int i = 0; i < structures.length; i++)
934       {
935         if (i != refStructure)
936         {
937           AtomSpecModel atomSpec = getAtomSpec(structures[i], matched);
938           List<StructureCommandI> commands = commandGenerator
939                   .superposeStructures(refAtoms, atomSpec, backbone);
940           List<String> replies = executeCommands(commands, true, null);
941           for (String reply : replies)
942           {
943             // return this error (Chimera only) to the user
944             if (reply.toLowerCase(Locale.ROOT)
945                     .contains("unequal numbers of atoms"))
946             {
947               error += "; " + reply;
948             }
949           }
950         }
951       }
952     }
953
954     return error;
955   }
956
957   private AtomSpecModel getAtomSpec(
958           AAStructureBindingModel.SuperposeData superposeData,
959           BitSet matched)
960   {
961     AtomSpecModel model = new AtomSpecModel();
962     int nextColumnMatch = matched.nextSetBit(0);
963     while (nextColumnMatch != -1)
964     {
965       int pdbResNum = superposeData.pdbResNo[nextColumnMatch];
966       model.addRange(superposeData.modelId, pdbResNum, pdbResNum,
967               superposeData.chain);
968       nextColumnMatch = matched.nextSetBit(nextColumnMatch + 1);
969     }
970
971     return model;
972   }
973
974   /**
975    * returns the current sequenceRenderer that should be used to colour the
976    * structures
977    * 
978    * @param alignment
979    * 
980    * @return
981    */
982   public abstract SequenceRenderer getSequenceRenderer(
983           AlignmentViewPanel alignment);
984
985   /**
986    * Sends a command to the structure viewer to colour each chain with a
987    * distinct colour (to the extent supported by the viewer)
988    */
989   public void colourByChain()
990   {
991     colourBySequence = false;
992
993     // TODO: JAL-628 colour chains distinctly across all visible models
994
995     executeCommand(false, COLOURING_STRUCTURES,
996             commandGenerator.colourByChain());
997   }
998
999   /**
1000    * Sends a command to the structure viewer to colour each chain with a
1001    * distinct colour (to the extent supported by the viewer)
1002    */
1003   public void colourByCharge()
1004   {
1005     colourBySequence = false;
1006
1007     executeCommands(commandGenerator.colourByCharge(), false,
1008             COLOURING_STRUCTURES);
1009   }
1010
1011   /**
1012    * Sends a command to the structure to apply a colour scheme (defined in
1013    * Jalview but not necessarily applied to the alignment), which defines a
1014    * colour per residue letter. More complex schemes (e.g. that depend on
1015    * consensus) cannot be used here and are ignored.
1016    * 
1017    * @param cs
1018    */
1019   public void colourByJalviewColourScheme(ColourSchemeI cs)
1020   {
1021     colourBySequence = false;
1022
1023     if (cs == null || !cs.isSimple())
1024     {
1025       return;
1026     }
1027
1028     /*
1029      * build a map of {Residue3LetterCode, Color}
1030      */
1031     Map<String, Color> colours = new HashMap<>();
1032     List<String> residues = ResidueProperties.getResidues(isNucleotide(),
1033             false);
1034     for (String resName : residues)
1035     {
1036       char res = resName.length() == 3
1037               ? ResidueProperties.getSingleCharacterCode(resName)
1038               : resName.charAt(0);
1039       Color colour = cs.findColour(res, 0, null, null, 0f);
1040       colours.put(resName, colour);
1041     }
1042
1043     /*
1044      * pass to the command constructor, and send the command
1045      */
1046     List<StructureCommandI> cmd = commandGenerator
1047             .colourByResidues(colours);
1048     executeCommands(cmd, false, COLOURING_STRUCTURES);
1049   }
1050
1051   public void setBackgroundColour(Color col)
1052   {
1053     StructureCommandI cmd = commandGenerator.setBackgroundColour(col);
1054     executeCommand(false, null, cmd);
1055   }
1056
1057   /**
1058    * Execute one structure viewer command. If {@code getReply} is true, may
1059    * optionally return one or more reply messages, else returns null.
1060    * 
1061    * @param cmd
1062    * @param getReply
1063    */
1064   protected abstract List<String> executeCommand(StructureCommandI cmd,
1065           boolean getReply);
1066
1067   /**
1068    * Executes one or more structure viewer commands
1069    * 
1070    * @param commands
1071    * @param getReply
1072    * @param msg
1073    */
1074   protected List<String> executeCommands(List<StructureCommandI> commands,
1075           boolean getReply, String msg)
1076   {
1077     return executeCommand(getReply, msg,
1078             commands.toArray(new StructureCommandI[commands.size()]));
1079   }
1080
1081   /**
1082    * Executes one or more structure viewer commands, optionally returning the
1083    * reply, and optionally showing a status message while the command is being
1084    * executed.
1085    * <p>
1086    * If a reply is wanted, the execution is done synchronously (waits),
1087    * otherwise it is done in a separate thread (doesn't wait). WARNING: if you
1088    * are sending commands that need to execute before later calls to
1089    * executeCommand (e.g. mouseovers, which clean up after previous ones) then
1090    * set getReply true to ensure that commands are not executed out of order.
1091    * 
1092    * @param getReply
1093    * @param msg
1094    * @param cmds
1095    * @return
1096    */
1097   protected List<String> executeCommand(boolean getReply, String msg,
1098           StructureCommandI... cmds)
1099   {
1100     JalviewStructureDisplayI theViewer = getViewer();
1101     final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
1102
1103     if (getReply)
1104     {
1105       /*
1106        * execute and wait for reply
1107        */
1108       List<String> response = new ArrayList<>();
1109       try
1110       {
1111         for (StructureCommandI cmd : cmds)
1112         {
1113           List<String> replies = executeCommand(cmd, true);
1114           if (replies != null)
1115           {
1116             response.addAll(replies);
1117           }
1118         }
1119         return response;
1120       } finally
1121       {
1122         if (msg != null)
1123         {
1124           theViewer.stopProgressBar(null, handle);
1125         }
1126       }
1127     }
1128
1129     /*
1130      * fire and forget
1131      */
1132     String threadName = msg == null ? "StructureCommand" : msg;
1133     new Thread(new Runnable()
1134     {
1135       @Override
1136       public void run()
1137       {
1138         try
1139         {
1140           for (StructureCommandI cmd : cmds)
1141           {
1142             executeCommand(cmd, false);
1143           }
1144         } finally
1145         {
1146           if (msg != null)
1147           {
1148             SwingUtilities.invokeLater(new Runnable()
1149             {
1150               @Override
1151               public void run()
1152               {
1153                 theViewer.stopProgressBar(null, handle);
1154               }
1155             });
1156           }
1157         }
1158       }
1159     }, threadName).start();
1160     return null;
1161   }
1162
1163   /**
1164    * Colours any structures associated with sequences in the given alignment as
1165    * coloured in the alignment view, provided colourBySequence is enabled
1166    */
1167   public void colourBySequence(AlignmentViewPanel alignmentv)
1168   {
1169     if (!colourBySequence || !isLoadingFinished() || getSsm() == null)
1170     {
1171       return;
1172     }
1173     Map<Object, AtomSpecModel> colourMap = buildColoursMap(ssm, sequence,
1174             alignmentv);
1175
1176     List<StructureCommandI> colourBySequenceCommands = commandGenerator
1177             .colourBySequence(colourMap);
1178     executeCommands(colourBySequenceCommands, false, COLOURING_STRUCTURES);
1179   }
1180
1181   /**
1182    * Centre the display in the structure viewer
1183    */
1184   public void focusView()
1185   {
1186     executeCommand(false, null, commandGenerator.focusView());
1187   }
1188
1189   /**
1190    * Generates and executes a command to show only specified chains in the
1191    * structure viewer. The list of chains to show should contain entries
1192    * formatted as "pdbid:chaincode".
1193    * 
1194    * @param toShow
1195    */
1196   public void showChains(List<String> toShow)
1197   {
1198     // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1199
1200     /*
1201      * Reformat the pdbid:chainCode values as modelNo:chainCode
1202      * since this is what is needed to construct the viewer command
1203      * todo: find a less messy way to do this
1204      */
1205     List<String> showThese = new ArrayList<>();
1206     for (String chainId : toShow)
1207     {
1208       String[] tokens = chainId.split("\\:");
1209       if (tokens.length == 2)
1210       {
1211         String pdbFile = getFileForChain(chainId);
1212         String model = getModelIdForFile(pdbFile);
1213         showThese.add(model + ":" + tokens[1]);
1214       }
1215     }
1216     executeCommands(commandGenerator.showChains(showThese), false, null);
1217   }
1218
1219   /**
1220    * Answers the structure viewer's model id given a PDB file name. Returns an
1221    * empty string if model id is not found.
1222    * 
1223    * @param chainId
1224    * @return
1225    */
1226   protected abstract String getModelIdForFile(String chainId);
1227
1228   public boolean hasFileLoadingError()
1229   {
1230     return fileLoadingError != null && fileLoadingError.length() > 0;
1231   }
1232
1233   /**
1234    * Returns the FeatureRenderer for the given alignment view
1235    * 
1236    * @param avp
1237    * @return
1238    */
1239   public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1240   {
1241     AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1242             : avp;
1243     if (ap == null)
1244     {
1245       return null;
1246     }
1247     return ap.getFeatureRenderer();
1248   }
1249
1250   protected void setStructureCommands(StructureCommandsI cmd)
1251   {
1252     commandGenerator = cmd;
1253   }
1254
1255   /**
1256    * Records association of one chain id (formatted as "pdbid:chainCode") with
1257    * the corresponding PDB file name
1258    * 
1259    * @param chainId
1260    * @param fileName
1261    */
1262   public void addChainFile(String chainId, String fileName)
1263   {
1264     chainFile.put(chainId, fileName);
1265   }
1266
1267   /**
1268    * Returns the PDB filename for the given chain id (formatted as
1269    * "pdbid:chainCode"), or null if not found
1270    * 
1271    * @param chainId
1272    * @return
1273    */
1274   protected String getFileForChain(String chainId)
1275   {
1276     return chainFile.get(chainId);
1277   }
1278
1279   @Override
1280   public void updateColours(Object source)
1281   {
1282     if (getViewer() == null)
1283     {
1284       // can happen if a viewer was not instantiated or cleaned up and is still
1285       // registered - mostly during tests
1286       return;
1287     }
1288     AlignmentViewPanel ap = (AlignmentViewPanel) source;
1289     // ignore events from panels not used to colour this view
1290     if (!getViewer().isUsedForColourBy(ap))
1291     {
1292       return;
1293     }
1294     if (!isLoadingFromArchive())
1295     {
1296       colourBySequence(ap);
1297     }
1298   }
1299
1300   public StructureCommandsI getCommandGenerator()
1301   {
1302     return commandGenerator;
1303   }
1304
1305   protected abstract ViewerType getViewerType();
1306
1307   /**
1308    * Builds a data structure which records mapped structure residues for each
1309    * colour. From this we can easily generate the viewer commands for colour by
1310    * sequence. Constructs and returns a map of {@code Color} to
1311    * {@code AtomSpecModel}, where the atomspec model holds
1312    * 
1313    * <pre>
1314    *   Model ids
1315    *     Chains
1316    *       Residue positions
1317    * </pre>
1318    * 
1319    * Ordering is by order of addition (for colours), natural ordering (for
1320    * models and chains)
1321    * 
1322    * @param ssm
1323    * @param sequence
1324    * @param viewPanel
1325    * @return
1326    */
1327   protected Map<Object, AtomSpecModel> buildColoursMap(
1328           StructureSelectionManager ssm, SequenceI[][] sequence,
1329           AlignmentViewPanel viewPanel)
1330   {
1331     String[] files = getStructureFiles();
1332     SequenceRenderer sr = getSequenceRenderer(viewPanel);
1333     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1334     FeatureColourFinder finder = new FeatureColourFinder(fr);
1335     AlignViewportI viewport = viewPanel.getAlignViewport();
1336     HiddenColumns cs = viewport.getAlignment().getHiddenColumns();
1337     AlignmentI al = viewport.getAlignment();
1338     Map<Object, AtomSpecModel> colourMap = new LinkedHashMap<>();
1339     Color lastColour = null;
1340
1341     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1342     {
1343       final String modelId = getModelIdForFile(files[pdbfnum]);
1344       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1345
1346       if (mapping == null || mapping.length < 1)
1347       {
1348         continue;
1349       }
1350
1351       int startPos = -1, lastPos = -1;
1352       String lastChain = "";
1353       for (int s = 0; s < sequence[pdbfnum].length; s++)
1354       {
1355         for (int sp, m = 0; m < mapping.length; m++)
1356         {
1357           final SequenceI seq = sequence[pdbfnum][s];
1358           if (mapping[m].getSequence() == seq
1359                   && (sp = al.findIndex(seq)) > -1)
1360           {
1361             SequenceI asp = al.getSequenceAt(sp);
1362             for (int r = 0; r < asp.getLength(); r++)
1363             {
1364               // no mapping to gaps in sequence
1365               if (Comparison.isGap(asp.getCharAt(r)))
1366               {
1367                 continue;
1368               }
1369               int pos = mapping[m].getPDBResNum(asp.findPosition(r));
1370
1371               if (pos < 1 || pos == lastPos)
1372               {
1373                 continue;
1374               }
1375
1376               Color colour = sr.getResidueColour(seq, r, finder);
1377
1378               /*
1379                * darker colour for hidden regions
1380                */
1381               if (!cs.isVisible(r))
1382               {
1383                 colour = Color.GRAY;
1384               }
1385
1386               final String chain = mapping[m].getChain();
1387
1388               /*
1389                * Just keep incrementing the end position for this colour range
1390                * _unless_ colour, PDB model or chain has changed, or there is a
1391                * gap in the mapped residue sequence
1392                */
1393               final boolean newColour = !colour.equals(lastColour);
1394               final boolean nonContig = lastPos + 1 != pos;
1395               final boolean newChain = !chain.equals(lastChain);
1396               if (newColour || nonContig || newChain)
1397               {
1398                 if (startPos != -1)
1399                 {
1400                   addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1401                           lastPos, lastChain);
1402                 }
1403                 startPos = pos;
1404               }
1405               lastColour = colour;
1406               lastPos = pos;
1407               lastChain = chain;
1408             }
1409             // final colour range
1410             if (lastColour != null)
1411             {
1412               addAtomSpecRange(colourMap, lastColour, modelId, startPos,
1413                       lastPos, lastChain);
1414             }
1415             // break;
1416           }
1417         }
1418       }
1419     }
1420     return colourMap;
1421   }
1422
1423   /**
1424    * todo better refactoring (map lookup or similar to get viewer structure id)
1425    * 
1426    * @param pdbfnum
1427    * @param file
1428    * @return
1429    */
1430   protected String getModelId(int pdbfnum, String file)
1431   {
1432     return String.valueOf(pdbfnum);
1433   }
1434
1435   /**
1436    * Saves chains, formatted as "pdbId:chainCode", and lookups from this to the
1437    * full PDB file path
1438    * 
1439    * @param pdb
1440    * @param file
1441    */
1442   public void stashFoundChains(StructureFile pdb, String file)
1443   {
1444     for (int i = 0; i < pdb.getChains().size(); i++)
1445     {
1446       String chid = pdb.getId() + ":" + pdb.getChains().elementAt(i).id;
1447       addChainFile(chid, file);
1448       getChainNames().add(chid);
1449     }
1450   }
1451
1452   /**
1453    * Helper method to add one contiguous range to the AtomSpec model for the
1454    * given value (creating the model if necessary). As used by Jalview,
1455    * {@code value} is
1456    * <ul>
1457    * <li>a colour, when building a 'colour structure by sequence' command</li>
1458    * <li>a feature value, when building a 'set Chimera attributes from features'
1459    * command</li>
1460    * </ul>
1461    * 
1462    * @param map
1463    * @param value
1464    * @param model
1465    * @param startPos
1466    * @param endPos
1467    * @param chain
1468    */
1469   public static final void addAtomSpecRange(Map<Object, AtomSpecModel> map,
1470           Object value, String model, int startPos, int endPos,
1471           String chain)
1472   {
1473     /*
1474      * Get/initialize map of data for the colour
1475      */
1476     AtomSpecModel atomSpec = map.get(value);
1477     if (atomSpec == null)
1478     {
1479       atomSpec = new AtomSpecModel();
1480       map.put(value, atomSpec);
1481     }
1482
1483     atomSpec.addRange(model, startPos, endPos, chain);
1484   }
1485
1486   /**
1487    * Returns the file extension (including '.' separator) to use for a saved
1488    * viewer session file. Default is to return null (not supported), override as
1489    * required.
1490    * 
1491    * @return
1492    */
1493   public String getSessionFileExtension()
1494   {
1495     return null;
1496   }
1497
1498   /**
1499    * If supported, saves the state of the structure viewer to a temporary file
1500    * and returns the file. Returns null and logs an error on any failure.
1501    * 
1502    * @return
1503    */
1504   public File saveSession()
1505   {
1506     String prefix = getViewerType().toString();
1507     String suffix = getSessionFileExtension();
1508     File f = null;
1509     try
1510     {
1511       f = File.createTempFile(prefix, suffix);
1512       saveSession(f);
1513     } catch (IOException e)
1514     {
1515       Console.error(String.format("Error saving %s session: %s", prefix,
1516               e.toString()));
1517     }
1518
1519     return f;
1520   }
1521
1522   /**
1523    * Saves the structure viewer session to the given file
1524    * 
1525    * @param f
1526    */
1527   protected void saveSession(File f)
1528   {
1529     StructureCommandI cmd = commandGenerator.saveSession(f.getPath());
1530     if (cmd != null)
1531     {
1532       executeCommand(cmd, false);
1533     }
1534   }
1535
1536   /**
1537    * Returns true if the viewer is an external structure viewer for which the
1538    * process is still alive, else false (for Jmol, or an external viewer which
1539    * the user has independently closed)
1540    * 
1541    * @return
1542    */
1543   public boolean isViewerRunning()
1544   {
1545     return false;
1546   }
1547
1548   /**
1549    * Closes Jalview's structure viewer panel and releases associated resources.
1550    * If it is managing an external viewer program, and {@code forceClose} is
1551    * true, also asks that program to close.
1552    * 
1553    * @param forceClose
1554    */
1555   public void closeViewer(boolean forceClose)
1556   {
1557     getSsm().removeStructureViewerListener(this, this.getStructureFiles());
1558     releaseUIResources();
1559
1560     /*
1561      * end the thread that closes this panel if the external viewer closes
1562      */
1563     if (externalViewerMonitor != null)
1564     {
1565       externalViewerMonitor.interrupt();
1566       externalViewerMonitor = null;
1567     }
1568
1569     stopListening();
1570
1571     if (forceClose)
1572     {
1573       StructureCommandI cmd = getCommandGenerator().closeViewer();
1574       if (cmd != null)
1575       {
1576         executeCommand(cmd, false);
1577       }
1578     }
1579   }
1580
1581   /**
1582    * Returns the URL of a help page for the structure viewer, or null if none is
1583    * known
1584    * 
1585    * @return
1586    */
1587   public String getHelpURL()
1588   {
1589     return null;
1590   }
1591
1592   /**
1593    * <pre>
1594    * Helper method to build a map of 
1595    *   { featureType, { feature value, AtomSpecModel } }
1596    * </pre>
1597    * 
1598    * @param viewPanel
1599    * @return
1600    */
1601   protected Map<String, Map<Object, AtomSpecModel>> buildFeaturesMap(
1602           AlignmentViewPanel viewPanel)
1603   {
1604     Map<String, Map<Object, AtomSpecModel>> theMap = new LinkedHashMap<>();
1605     String[] files = getStructureFiles();
1606     if (files == null)
1607     {
1608       return theMap;
1609     }
1610
1611     FeatureRenderer fr = viewPanel.getFeatureRenderer();
1612     if (fr == null)
1613     {
1614       return theMap;
1615     }
1616
1617     AlignViewportI viewport = viewPanel.getAlignViewport();
1618     List<String> visibleFeatures = fr.getDisplayedFeatureTypes();
1619
1620     /*
1621      * if alignment is showing features from complement, we also transfer
1622      * these features to the corresponding mapped structure residues
1623      */
1624     boolean showLinkedFeatures = viewport.isShowComplementFeatures();
1625     List<String> complementFeatures = new ArrayList<>();
1626     FeatureRenderer complementRenderer = null;
1627     if (showLinkedFeatures)
1628     {
1629       AlignViewportI comp = fr.getViewport().getCodingComplement();
1630       if (comp != null)
1631       {
1632         complementRenderer = Desktop.getAlignFrameFor(comp)
1633                 .getFeatureRenderer();
1634         complementFeatures = complementRenderer.getDisplayedFeatureTypes();
1635       }
1636     }
1637     if (visibleFeatures.isEmpty() && complementFeatures.isEmpty())
1638     {
1639       return theMap;
1640     }
1641
1642     AlignmentI alignment = viewPanel.getAlignment();
1643     SequenceI[][] seqs = getSequence();
1644
1645     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
1646     {
1647       String modelId = getModelIdForFile(files[pdbfnum]);
1648       StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
1649
1650       if (mapping == null || mapping.length < 1)
1651       {
1652         continue;
1653       }
1654
1655       for (int seqNo = 0; seqNo < seqs[pdbfnum].length; seqNo++)
1656       {
1657         for (int m = 0; m < mapping.length; m++)
1658         {
1659           final SequenceI seq = seqs[pdbfnum][seqNo];
1660           int sp = alignment.findIndex(seq);
1661           StructureMapping structureMapping = mapping[m];
1662           if (structureMapping.getSequence() == seq && sp > -1)
1663           {
1664             /*
1665              * found a sequence with a mapping to a structure;
1666              * now scan its features
1667              */
1668             if (!visibleFeatures.isEmpty())
1669             {
1670               scanSequenceFeatures(visibleFeatures, structureMapping, seq,
1671                       theMap, modelId);
1672             }
1673             if (showLinkedFeatures)
1674             {
1675               scanComplementFeatures(complementRenderer, structureMapping,
1676                       seq, theMap, modelId);
1677             }
1678           }
1679         }
1680       }
1681     }
1682     return theMap;
1683   }
1684
1685   /**
1686    * Ask the structure viewer to open a session file. Returns true if
1687    * successful, else false (or not supported).
1688    * 
1689    * @param filepath
1690    * @return
1691    */
1692   public boolean openSession(String filepath)
1693   {
1694     StructureCommandI cmd = getCommandGenerator().openSession(filepath);
1695     if (cmd == null)
1696     {
1697       return false;
1698     }
1699     executeCommand(cmd, true);
1700     // todo: test for failure - how?
1701     return true;
1702   }
1703
1704   /**
1705    * Scans visible features in mapped positions of the CDS/peptide complement,
1706    * and adds any found to the map of attribute values/structure positions
1707    * 
1708    * @param complementRenderer
1709    * @param structureMapping
1710    * @param seq
1711    * @param theMap
1712    * @param modelNumber
1713    */
1714   protected static void scanComplementFeatures(
1715           FeatureRenderer complementRenderer,
1716           StructureMapping structureMapping, SequenceI seq,
1717           Map<String, Map<Object, AtomSpecModel>> theMap,
1718           String modelNumber)
1719   {
1720     /*
1721      * for each sequence residue mapped to a structure position...
1722      */
1723     for (int seqPos : structureMapping.getMapping().keySet())
1724     {
1725       /*
1726        * find visible complementary features at mapped position(s)
1727        */
1728       MappedFeatures mf = complementRenderer
1729               .findComplementFeaturesAtResidue(seq, seqPos);
1730       if (mf != null)
1731       {
1732         for (SequenceFeature sf : mf.features)
1733         {
1734           String type = sf.getType();
1735
1736           /*
1737            * Don't copy features which originated from Chimera
1738            */
1739           if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1740                   .equals(sf.getFeatureGroup()))
1741           {
1742             continue;
1743           }
1744
1745           /*
1746            * record feature 'value' (score/description/type) as at the
1747            * corresponding structure position
1748            */
1749           List<int[]> mappedRanges = structureMapping
1750                   .getPDBResNumRanges(seqPos, seqPos);
1751
1752           if (!mappedRanges.isEmpty())
1753           {
1754             String value = sf.getDescription();
1755             if (value == null || value.length() == 0)
1756             {
1757               value = type;
1758             }
1759             float score = sf.getScore();
1760             if (score != 0f && !Float.isNaN(score))
1761             {
1762               value = Float.toString(score);
1763             }
1764             Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1765             if (featureValues == null)
1766             {
1767               featureValues = new HashMap<>();
1768               theMap.put(type, featureValues);
1769             }
1770             for (int[] range : mappedRanges)
1771             {
1772               addAtomSpecRange(featureValues, value, modelNumber, range[0],
1773                       range[1], structureMapping.getChain());
1774             }
1775           }
1776         }
1777       }
1778     }
1779   }
1780
1781   /**
1782    * Inspect features on the sequence; for each feature that is visible,
1783    * determine its mapped ranges in the structure (if any) according to the
1784    * given mapping, and add them to the map.
1785    * 
1786    * @param visibleFeatures
1787    * @param mapping
1788    * @param seq
1789    * @param theMap
1790    * @param modelId
1791    */
1792   protected static void scanSequenceFeatures(List<String> visibleFeatures,
1793           StructureMapping mapping, SequenceI seq,
1794           Map<String, Map<Object, AtomSpecModel>> theMap, String modelId)
1795   {
1796     List<SequenceFeature> sfs = seq.getFeatures().getPositionalFeatures(
1797             visibleFeatures.toArray(new String[visibleFeatures.size()]));
1798     for (SequenceFeature sf : sfs)
1799     {
1800       String type = sf.getType();
1801
1802       /*
1803        * Don't copy features which originated from Chimera
1804        */
1805       if (JalviewChimeraBinding.CHIMERA_FEATURE_GROUP
1806               .equals(sf.getFeatureGroup()))
1807       {
1808         continue;
1809       }
1810
1811       List<int[]> mappedRanges = mapping.getPDBResNumRanges(sf.getBegin(),
1812               sf.getEnd());
1813
1814       if (!mappedRanges.isEmpty())
1815       {
1816         String value = sf.getDescription();
1817         if (value == null || value.length() == 0)
1818         {
1819           value = type;
1820         }
1821         float score = sf.getScore();
1822         if (score != 0f && !Float.isNaN(score))
1823         {
1824           value = Float.toString(score);
1825         }
1826         Map<Object, AtomSpecModel> featureValues = theMap.get(type);
1827         if (featureValues == null)
1828         {
1829           featureValues = new HashMap<>();
1830           theMap.put(type, featureValues);
1831         }
1832         for (int[] range : mappedRanges)
1833         {
1834           addAtomSpecRange(featureValues, value, modelId, range[0],
1835                   range[1], mapping.getChain());
1836         }
1837       }
1838     }
1839   }
1840
1841   /**
1842    * Returns the number of structure files in the structure viewer and mapped to
1843    * Jalview. This may be zero if the files are still in the process of loading
1844    * in the viewer.
1845    * 
1846    * @return
1847    */
1848   public int getMappedStructureCount()
1849   {
1850     String[] files = getStructureFiles();
1851     return files == null ? 0 : files.length;
1852   }
1853
1854   /**
1855    * Starts a thread that waits for the external viewer program process to
1856    * finish, so that we can then close the associated resources. This avoids
1857    * leaving orphaned viewer panels in Jalview if the user closes the external
1858    * viewer.
1859    * 
1860    * @param p
1861    */
1862   protected void startExternalViewerMonitor(Process p)
1863   {
1864     externalViewerMonitor = new Thread(new Runnable()
1865     {
1866
1867       @Override
1868       public void run()
1869       {
1870         try
1871         {
1872           p.waitFor();
1873           JalviewStructureDisplayI display = getViewer();
1874           if (display != null)
1875           {
1876             display.closeViewer(false);
1877           }
1878         } catch (InterruptedException e)
1879         {
1880           // exit thread if Chimera Viewer is closed in Jalview
1881         }
1882       }
1883     });
1884     externalViewerMonitor.start();
1885   }
1886
1887   /**
1888    * If supported by the external structure viewer, sends it commands to notify
1889    * model or selection changes to the specified URL (where Jalview has started
1890    * a listener)
1891    * 
1892    * @param uri
1893    */
1894   protected void startListening(String uri)
1895   {
1896     List<StructureCommandI> commands = getCommandGenerator()
1897             .startNotifications(uri);
1898     if (commands != null)
1899     {
1900       executeCommands(commands, false, null);
1901     }
1902   }
1903
1904   /**
1905    * If supported by the external structure viewer, sends it commands to stop
1906    * notifying model or selection changes
1907    */
1908   protected void stopListening()
1909   {
1910     List<StructureCommandI> commands = getCommandGenerator()
1911             .stopNotifications();
1912     if (commands != null)
1913     {
1914       executeCommands(commands, false, null);
1915     }
1916   }
1917
1918   /**
1919    * If supported by the structure viewer, queries it for all residue attributes
1920    * with the given attribute name, and creates features on corresponding
1921    * residues of the alignment. Returns the number of features added.
1922    * 
1923    * @param attName
1924    * @param alignmentPanel
1925    * @return
1926    */
1927   public int copyStructureAttributesToFeatures(String attName,
1928           AlignmentPanel alignmentPanel)
1929   {
1930     StructureCommandI cmd = getCommandGenerator()
1931             .getResidueAttributes(attName);
1932     if (cmd == null)
1933     {
1934       return 0;
1935     }
1936     List<String> residueAttributes = executeCommand(cmd, true);
1937
1938     int featuresAdded = createFeaturesForAttributes(attName,
1939             residueAttributes);
1940     if (featuresAdded > 0)
1941     {
1942       alignmentPanel.getFeatureRenderer().featuresAdded();
1943     }
1944     return featuresAdded;
1945   }
1946
1947   /**
1948    * Parses {@code residueAttributes} and creates sequence features on any
1949    * mapped alignment residues. Returns the number of features created.
1950    * <p>
1951    * {@code residueAttributes} is the reply from the structure viewer to a
1952    * command to list any residue attributes for the given attribute name. Syntax
1953    * and parsing of this is viewer-specific.
1954    * 
1955    * @param attName
1956    * @param residueAttributes
1957    * @return
1958    */
1959   protected int createFeaturesForAttributes(String attName,
1960           List<String> residueAttributes)
1961   {
1962     return 0;
1963   }
1964 }