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