JAL-2422 pull-up refactoring of structure commands (continued)
[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 jalview.api.AlignmentViewPanel;
24 import jalview.api.FeatureRenderer;
25 import jalview.api.SequenceRenderer;
26 import jalview.api.StructureSelectionManagerProvider;
27 import jalview.api.structures.JalviewStructureDisplayI;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.PDBEntry;
31 import jalview.datamodel.SequenceI;
32 import jalview.io.DataSourceType;
33 import jalview.schemes.ColourSchemeI;
34 import jalview.schemes.ResidueProperties;
35 import jalview.structure.AtomSpec;
36 import jalview.structure.StructureCommandsI;
37 import jalview.structure.StructureListener;
38 import jalview.structure.StructureMapping;
39 import jalview.structure.StructureSelectionManager;
40 import jalview.util.Comparison;
41 import jalview.util.MessageManager;
42
43 import java.awt.Color;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.BitSet;
47 import java.util.HashMap;
48 import java.util.List;
49 import java.util.Map;
50
51 import javax.swing.SwingUtilities;
52
53 /**
54  * 
55  * A base class to hold common function for protein structure model binding.
56  * Initial version created by refactoring JMol and Chimera binding models, but
57  * other structure viewers could in principle be accommodated in future.
58  * 
59  * @author gmcarstairs
60  *
61  */
62 public abstract class AAStructureBindingModel
63         extends SequenceStructureBindingModel
64         implements StructureListener, StructureSelectionManagerProvider
65 {
66   private static final String COLOURING_STRUCTURES = MessageManager
67           .getString("status.colouring_structures");
68
69   /*
70    * the Jalview panel through which the user interacts
71    * with the structure viewer
72    */
73   private JalviewStructureDisplayI viewer;
74
75   /*
76    * helper that generates command syntax
77    */
78   private StructureCommandsI commandGenerator;
79
80   private StructureSelectionManager ssm;
81
82   /*
83    * modelled chains, formatted as "pdbid:chainCode"
84    */
85   private List<String> chainNames;
86
87   /*
88    * lookup of pdb file name by key "pdbid:chainCode"
89    */
90   private Map<String, String> chainFile;
91
92   /*
93    * distinct PDB entries (pdb files) associated
94    * with sequences
95    */
96   private PDBEntry[] pdbEntry;
97
98   /*
99    * sequences mapped to each pdbentry
100    */
101   private SequenceI[][] sequence;
102
103   /*
104    * array of target chains for sequences - tied to pdbentry and sequence[]
105    */
106   private String[][] chains;
107
108   /*
109    * datasource protocol for access to PDBEntrylatest
110    */
111   DataSourceType protocol = null;
112
113   protected boolean colourBySequence = true;
114
115   private boolean nucleotide;
116
117   private boolean finishedInit = false;
118
119   /**
120    * current set of model filenames loaded in the Jmol instance
121    */
122   protected String[] modelFileNames = null;
123
124   public String fileLoadingError;
125
126   /**
127    * Data bean class to simplify parameterisation in superposeStructures
128    */
129   protected class SuperposeData
130   {
131     /**
132      * Constructor with alignment width argument
133      * 
134      * @param width
135      */
136     public SuperposeData(int width)
137     {
138       pdbResNo = new int[width];
139     }
140
141     public String filename;
142
143     public String pdbId;
144
145     public String chain = "";
146
147     public boolean isRna;
148
149     /*
150      * The pdb residue number (if any) mapped to each column of the alignment
151      */
152     public int[] pdbResNo;
153   }
154
155   /**
156    * Constructor
157    * 
158    * @param ssm
159    * @param seqs
160    */
161   public AAStructureBindingModel(StructureSelectionManager ssm,
162           SequenceI[][] seqs)
163   {
164     this.ssm = ssm;
165     this.sequence = seqs;
166     chainNames = new ArrayList<>();
167     chainFile = new HashMap<>();
168   }
169
170   /**
171    * Constructor
172    * 
173    * @param ssm
174    * @param pdbentry
175    * @param sequenceIs
176    * @param protocol
177    */
178   public AAStructureBindingModel(StructureSelectionManager ssm,
179           PDBEntry[] pdbentry, SequenceI[][] sequenceIs,
180           DataSourceType protocol)
181   {
182     this(ssm, sequenceIs);
183     this.nucleotide = Comparison.isNucleotide(sequenceIs);
184     this.pdbEntry = pdbentry;
185     this.protocol = protocol;
186     resolveChains();
187   }
188
189   private boolean resolveChains()
190   {
191     /**
192      * final count of chain mappings discovered
193      */
194     int chainmaps = 0;
195     // JBPNote: JAL-2693 - this should be a list of chain mappings per
196     // [pdbentry][sequence]
197     String[][] newchains = new String[pdbEntry.length][];
198     int pe = 0;
199     for (PDBEntry pdb : pdbEntry)
200     {
201       SequenceI[] seqsForPdb = sequence[pe];
202       if (seqsForPdb != null)
203       {
204         newchains[pe] = new String[seqsForPdb.length];
205         int se = 0;
206         for (SequenceI asq : seqsForPdb)
207         {
208           String chain = (chains != null && chains[pe] != null)
209                   ? chains[pe][se]
210                   : null;
211           SequenceI sq = (asq.getDatasetSequence() == null) ? asq
212                   : asq.getDatasetSequence();
213           if (sq.getAllPDBEntries() != null)
214           {
215             for (PDBEntry pdbentry : sq.getAllPDBEntries())
216             {
217               if (pdb.getFile() != null && pdbentry.getFile() != null
218                       && pdb.getFile().equals(pdbentry.getFile()))
219               {
220                 String chaincode = pdbentry.getChainCode();
221                 if (chaincode != null && chaincode.length() > 0)
222                 {
223                   chain = chaincode;
224                   chainmaps++;
225                   break;
226                 }
227               }
228             }
229           }
230           newchains[pe][se] = chain;
231           se++;
232         }
233         pe++;
234       }
235     }
236
237     chains = newchains;
238     return chainmaps > 0;
239   }
240   public StructureSelectionManager getSsm()
241   {
242     return ssm;
243   }
244
245   /**
246    * Returns the i'th PDBEntry (or null)
247    * 
248    * @param i
249    * @return
250    */
251   public PDBEntry getPdbEntry(int i)
252   {
253     return (pdbEntry != null && pdbEntry.length > i) ? pdbEntry[i] : null;
254   }
255
256   /**
257    * Answers true if this binding includes the given PDB id, else false
258    * 
259    * @param pdbId
260    * @return
261    */
262   public boolean hasPdbId(String pdbId)
263   {
264     if (pdbEntry != null)
265     {
266       for (PDBEntry pdb : pdbEntry)
267       {
268         if (pdb.getId().equals(pdbId))
269         {
270           return true;
271         }
272       }
273     }
274     return false;
275   }
276
277   /**
278    * Returns the number of modelled PDB file entries.
279    * 
280    * @return
281    */
282   public int getPdbCount()
283   {
284     return pdbEntry == null ? 0 : pdbEntry.length;
285   }
286
287   public SequenceI[][] getSequence()
288   {
289     return sequence;
290   }
291
292   public String[][] getChains()
293   {
294     return chains;
295   }
296
297   public DataSourceType getProtocol()
298   {
299     return protocol;
300   }
301
302   // TODO may remove this if calling methods can be pulled up here
303   protected void setPdbentry(PDBEntry[] pdbentry)
304   {
305     this.pdbEntry = pdbentry;
306   }
307
308   protected void setSequence(SequenceI[][] sequence)
309   {
310     this.sequence = sequence;
311   }
312
313   protected void setChains(String[][] chains)
314   {
315     this.chains = chains;
316   }
317
318   /**
319    * Construct a title string for the viewer window based on the data Jalview
320    * knows about
321    * 
322    * @param viewerName
323    *          TODO
324    * @param verbose
325    * 
326    * @return
327    */
328   public String getViewerTitle(String viewerName, boolean verbose)
329   {
330     if (getSequence() == null || getSequence().length < 1
331             || getPdbCount() < 1 || getSequence()[0].length < 1)
332     {
333       return ("Jalview " + viewerName + " Window");
334     }
335     // TODO: give a more informative title when multiple structures are
336     // displayed.
337     StringBuilder title = new StringBuilder(64);
338     final PDBEntry pdbe = getPdbEntry(0);
339     title.append(viewerName + " view for " + getSequence()[0][0].getName()
340             + ":" + pdbe.getId());
341
342     if (verbose)
343     {
344       String method = (String) pdbe.getProperty("method");
345       if (method != null)
346       {
347         title.append(" Method: ").append(method);
348       }
349       String chain = (String) pdbe.getProperty("chains");
350       if (chain != null)
351       {
352         title.append(" Chain:").append(chain);
353       }
354     }
355     return title.toString();
356   }
357
358   /**
359    * Called by after closeViewer is called, to release any resources and
360    * references so they can be garbage collected. Override if needed.
361    */
362   protected void releaseUIResources()
363   {
364
365   }
366
367   public boolean isColourBySequence()
368   {
369     return colourBySequence;
370   }
371
372   public void setColourBySequence(boolean colourBySequence)
373   {
374     this.colourBySequence = colourBySequence;
375   }
376
377   protected void addSequenceAndChain(int pe, SequenceI[] seq,
378           String[] tchain)
379   {
380     if (pe < 0 || pe >= getPdbCount())
381     {
382       throw new Error(MessageManager.formatMessage(
383               "error.implementation_error_no_pdbentry_from_index",
384               new Object[]
385               { Integer.valueOf(pe).toString() }));
386     }
387     final String nullChain = "TheNullChain";
388     List<SequenceI> s = new ArrayList<>();
389     List<String> c = new ArrayList<>();
390     if (getChains() == null)
391     {
392       setChains(new String[getPdbCount()][]);
393     }
394     if (getSequence()[pe] != null)
395     {
396       for (int i = 0; i < getSequence()[pe].length; i++)
397       {
398         s.add(getSequence()[pe][i]);
399         if (getChains()[pe] != null)
400         {
401           if (i < getChains()[pe].length)
402           {
403             c.add(getChains()[pe][i]);
404           }
405           else
406           {
407             c.add(nullChain);
408           }
409         }
410         else
411         {
412           if (tchain != null && tchain.length > 0)
413           {
414             c.add(nullChain);
415           }
416         }
417       }
418     }
419     for (int i = 0; i < seq.length; i++)
420     {
421       if (!s.contains(seq[i]))
422       {
423         s.add(seq[i]);
424         if (tchain != null && i < tchain.length)
425         {
426           c.add(tchain[i] == null ? nullChain : tchain[i]);
427         }
428       }
429     }
430     SequenceI[] tmp = s.toArray(new SequenceI[s.size()]);
431     getSequence()[pe] = tmp;
432     if (c.size() > 0)
433     {
434       String[] tch = c.toArray(new String[c.size()]);
435       for (int i = 0; i < tch.length; i++)
436       {
437         if (tch[i] == nullChain)
438         {
439           tch[i] = null;
440         }
441       }
442       getChains()[pe] = tch;
443     }
444     else
445     {
446       getChains()[pe] = null;
447     }
448   }
449
450   /**
451    * add structures and any known sequence associations
452    * 
453    * @returns the pdb entries added to the current set.
454    */
455   public synchronized PDBEntry[] addSequenceAndChain(PDBEntry[] pdbe,
456           SequenceI[][] seq, String[][] chns)
457   {
458     List<PDBEntry> v = new ArrayList<>();
459     List<int[]> rtn = new ArrayList<>();
460     for (int i = 0; i < getPdbCount(); i++)
461     {
462       v.add(getPdbEntry(i));
463     }
464     for (int i = 0; i < pdbe.length; i++)
465     {
466       int r = v.indexOf(pdbe[i]);
467       if (r == -1 || r >= getPdbCount())
468       {
469         rtn.add(new int[] { v.size(), i });
470         v.add(pdbe[i]);
471       }
472       else
473       {
474         // just make sure the sequence/chain entries are all up to date
475         addSequenceAndChain(r, seq[i], chns[i]);
476       }
477     }
478     pdbe = v.toArray(new PDBEntry[v.size()]);
479     setPdbentry(pdbe);
480     if (rtn.size() > 0)
481     {
482       // expand the tied sequence[] and string[] arrays
483       SequenceI[][] sqs = new SequenceI[getPdbCount()][];
484       String[][] sch = new String[getPdbCount()][];
485       System.arraycopy(getSequence(), 0, sqs, 0, getSequence().length);
486       System.arraycopy(getChains(), 0, sch, 0, this.getChains().length);
487       setSequence(sqs);
488       setChains(sch);
489       pdbe = new PDBEntry[rtn.size()];
490       for (int r = 0; r < pdbe.length; r++)
491       {
492         int[] stri = (rtn.get(r));
493         // record the pdb file as a new addition
494         pdbe[r] = getPdbEntry(stri[0]);
495         // and add the new sequence/chain entries
496         addSequenceAndChain(stri[0], seq[stri[1]], chns[stri[1]]);
497       }
498     }
499     else
500     {
501       pdbe = null;
502     }
503     return pdbe;
504   }
505
506   /**
507    * Add sequences to the pe'th pdbentry's sequence set.
508    * 
509    * @param pe
510    * @param seq
511    */
512   public void addSequence(int pe, SequenceI[] seq)
513   {
514     addSequenceAndChain(pe, seq, null);
515   }
516
517   /**
518    * add the given sequences to the mapping scope for the given pdb file handle
519    * 
520    * @param pdbFile
521    *          - pdbFile identifier
522    * @param seq
523    *          - set of sequences it can be mapped to
524    */
525   public void addSequenceForStructFile(String pdbFile, SequenceI[] seq)
526   {
527     for (int pe = 0; pe < getPdbCount(); pe++)
528     {
529       if (getPdbEntry(pe).getFile().equals(pdbFile))
530       {
531         addSequence(pe, seq);
532       }
533     }
534   }
535
536   @Override
537   public abstract void highlightAtoms(List<AtomSpec> atoms);
538
539   protected boolean isNucleotide()
540   {
541     return this.nucleotide;
542   }
543
544   /**
545    * Returns a readable description of all mappings for the wrapped pdbfile to
546    * any mapped sequences
547    * 
548    * @param pdbfile
549    * @param seqs
550    * @return
551    */
552   public String printMappings()
553   {
554     if (pdbEntry == null)
555     {
556       return "";
557     }
558     StringBuilder sb = new StringBuilder(128);
559     for (int pdbe = 0; pdbe < getPdbCount(); pdbe++)
560     {
561       String pdbfile = getPdbEntry(pdbe).getFile();
562       List<SequenceI> seqs = Arrays.asList(getSequence()[pdbe]);
563       sb.append(getSsm().printMappings(pdbfile, seqs));
564     }
565     return sb.toString();
566   }
567
568   /**
569    * Returns the mapped structure position for a given aligned column of a given
570    * sequence, or -1 if the column is gapped, beyond the end of the sequence, or
571    * not mapped to structure.
572    * 
573    * @param seq
574    * @param alignedPos
575    * @param mapping
576    * @return
577    */
578   protected int getMappedPosition(SequenceI seq, int alignedPos,
579           StructureMapping mapping)
580   {
581     if (alignedPos >= seq.getLength())
582     {
583       return -1;
584     }
585
586     if (Comparison.isGap(seq.getCharAt(alignedPos)))
587     {
588       return -1;
589     }
590     int seqPos = seq.findPosition(alignedPos);
591     int pos = mapping.getPDBResNum(seqPos);
592     return pos;
593   }
594
595   /**
596    * Helper method to identify residues that can participate in a structure
597    * superposition command. For each structure, identify a sequence in the
598    * alignment which is mapped to the structure. Identify non-gapped columns in
599    * the sequence which have a mapping to a residue in the structure. Returns
600    * the index of the first structure that has a mapping to the alignment.
601    * 
602    * @param alignment
603    *          the sequence alignment which is the basis of structure
604    *          superposition
605    * @param matched
606    *          a BitSet, where bit j is set to indicate that every structure has
607    *          a mapped residue present in column j (so the column can
608    *          participate in structure alignment)
609    * @param structures
610    *          an array of data beans corresponding to pdb file index
611    * @return
612    */
613   protected int findSuperposableResidues(AlignmentI alignment,
614           BitSet matched, SuperposeData[] structures)
615   {
616     int refStructure = -1;
617     String[] files = getStructureFiles();
618     if (files == null)
619     {
620       return -1;
621     }
622     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
623     {
624       StructureMapping[] mappings = getSsm().getMapping(files[pdbfnum]);
625       int lastPos = -1;
626
627       /*
628        * Find the first mapped sequence (if any) for this PDB entry which is in
629        * the alignment
630        */
631       final int seqCountForPdbFile = getSequence()[pdbfnum].length;
632       for (int s = 0; s < seqCountForPdbFile; s++)
633       {
634         for (StructureMapping mapping : mappings)
635         {
636           final SequenceI theSequence = getSequence()[pdbfnum][s];
637           if (mapping.getSequence() == theSequence
638                   && alignment.findIndex(theSequence) > -1)
639           {
640             if (refStructure < 0)
641             {
642               refStructure = pdbfnum;
643             }
644             for (int r = 0; r < alignment.getWidth(); r++)
645             {
646               if (!matched.get(r))
647               {
648                 continue;
649               }
650               int pos = getMappedPosition(theSequence, r, mapping);
651               if (pos < 1 || pos == lastPos)
652               {
653                 matched.clear(r);
654                 continue;
655               }
656               lastPos = pos;
657               structures[pdbfnum].pdbResNo[r] = pos;
658             }
659             String chain = mapping.getChain();
660             if (chain != null && chain.trim().length() > 0)
661             {
662               structures[pdbfnum].chain = chain;
663             }
664             structures[pdbfnum].pdbId = mapping.getPdbId();
665             structures[pdbfnum].isRna = theSequence.getRNA() != null;
666
667             /*
668              * move on to next pdb file (ignore sequences for other chains
669              * for the same structure)
670              */
671             s = seqCountForPdbFile;
672             break;
673           }
674         }
675       }
676     }
677     return refStructure;
678   }
679
680   /**
681    * Returns true if the structure viewer has loaded all of the files of
682    * interest (identified by the file mapping having been set up), or false if
683    * any are still not loaded after a timeout interval.
684    * 
685    * @param files
686    */
687   protected boolean waitForFileLoad(String[] files)
688   {
689     /*
690      * give up after 10 secs plus 1 sec per file
691      */
692     long starttime = System.currentTimeMillis();
693     long endTime = 10000 + 1000 * files.length + starttime;
694     String notLoaded = null;
695
696     boolean waiting = true;
697     while (waiting && System.currentTimeMillis() < endTime)
698     {
699       waiting = false;
700       for (String file : files)
701       {
702         notLoaded = file;
703         if (file == null)
704         {
705           continue;
706         }
707         try
708         {
709           StructureMapping[] sm = getSsm().getMapping(file);
710           if (sm == null || sm.length == 0)
711           {
712             waiting = true;
713           }
714         } catch (Throwable x)
715         {
716           waiting = true;
717         }
718       }
719     }
720
721     if (waiting)
722     {
723       System.err.println(
724               "Timed out waiting for structure viewer to load file "
725                       + notLoaded);
726       return false;
727     }
728     return true;
729   }
730
731   @Override
732   public boolean isListeningFor(SequenceI seq)
733   {
734     if (sequence != null)
735     {
736       for (SequenceI[] seqs : sequence)
737       {
738         if (seqs != null)
739         {
740           for (SequenceI s : seqs)
741           {
742             if (s == seq || (s.getDatasetSequence() != null
743                     && s.getDatasetSequence() == seq.getDatasetSequence()))
744             {
745               return true;
746             }
747           }
748         }
749       }
750     }
751     return false;
752   }
753
754   public boolean isFinishedInit()
755   {
756     return finishedInit;
757   }
758
759   public void setFinishedInit(boolean fi)
760   {
761     this.finishedInit = fi;
762   }
763
764   /**
765    * Returns a list of chains mapped in this viewer, formatted as
766    * "pdbid:chainCode"
767    * 
768    * @return
769    */
770   public List<String> getChainNames()
771   {
772     return chainNames;
773   }
774
775   /**
776    * Returns the Jalview panel hosting the structure viewer (if any)
777    * 
778    * @return
779    */
780   public JalviewStructureDisplayI getViewer()
781   {
782     return viewer;
783   }
784
785   public void setViewer(JalviewStructureDisplayI v)
786   {
787     viewer = v;
788   }
789
790   /**
791    * Constructs and sends a command to align structures against a reference
792    * structure, based on one or more sequence alignments. May optionally return
793    * an error or warning message for the alignment command.
794    * 
795    * @param alignments
796    *          an array of alignments to process
797    * @param structureIndices
798    *          an array of corresponding reference structures (index into pdb
799    *          file array); if a negative value is passed, the first PDB file
800    *          mapped to an alignment sequence is used as the reference for
801    *          superposition
802    * @param hiddenCols
803    *          an array of corresponding hidden columns for each alignment
804    * @return
805    */
806   public abstract String superposeStructures(AlignmentI[] alignments,
807           int[] structureIndices, HiddenColumns[] hiddenCols);
808
809   /**
810    * returns the current sequenceRenderer that should be used to colour the
811    * structures
812    * 
813    * @param alignment
814    * 
815    * @return
816    */
817   public abstract SequenceRenderer getSequenceRenderer(
818           AlignmentViewPanel alignment);
819
820   /**
821    * Sends a command to the structure viewer to colour each chain with a
822    * distinct colour (to the extent supported by the viewer)
823    */
824   public void colourByChain()
825   {
826     colourBySequence = false;
827
828     // TODO: JAL-628 colour chains distinctly across all visible models
829
830     executeCommand(commandGenerator.colourByChain(), false,
831             COLOURING_STRUCTURES);
832   }
833
834   /**
835    * Sends a command to the structure viewer to colour each chain with a
836    * distinct colour (to the extent supported by the viewer)
837    */
838   public void colourByCharge()
839   {
840     colourBySequence = false;
841
842     executeCommand(commandGenerator.colourByCharge(), false,
843             COLOURING_STRUCTURES);
844   }
845
846   /**
847    * Sends a command to the structure to apply a colour scheme (defined in
848    * Jalview but not necessarily applied to the alignment), which defines a
849    * colour per residue letter. More complex schemes (e.g. that depend on
850    * consensus) cannot be used here and are ignored.
851    * 
852    * @param cs
853    */
854   public void colourByJalviewColourScheme(ColourSchemeI cs)
855   {
856     colourBySequence = false;
857
858     if (cs == null || !cs.isSimple())
859     {
860       return;
861     }
862     
863     /*
864      * build a map of {Residue3LetterCode, Color}
865      */
866     Map<String, Color> colours = new HashMap<>();
867     List<String> residues = ResidueProperties.getResidues(isNucleotide(),
868             false);
869     for (String resName : residues)
870     {
871       char res = resName.length() == 3
872               ? ResidueProperties.getSingleCharacterCode(resName)
873               : resName.charAt(0);
874       Color colour = cs.findColour(res, 0, null, null, 0f);
875       colours.put(resName, colour);
876     }
877
878     /*
879      * pass to the command constructor, and send the command
880      */
881     String cmd = commandGenerator.colourByResidues(colours);
882     executeCommand(cmd, false, COLOURING_STRUCTURES);
883   }
884
885   public void setBackgroundColour(Color col)
886   {
887     String cmd = commandGenerator.setBackgroundColour(col);
888     executeCommand(cmd, false, null);
889   }
890
891   /**
892    * Sends one command to the structure viewer. If {@code getReply} is true, the
893    * command is sent synchronously, otherwise in a deferred thread.
894    * <p>
895    * If a progress message is supplied, this is displayed before command
896    * execution, and removed afterwards.
897    * 
898    * @param cmd
899    * @param getReply
900    * @param msg
901    * @return
902    */
903   private List<String> executeCommand(String cmd, boolean getReply,
904           String msg)
905   {
906     if (getReply)
907     {
908       return executeSynchronous(cmd, msg, getReply);
909     }
910     else
911     {
912       executeAsynchronous(cmd, msg);
913       return null;
914     }
915   }
916
917   /**
918    * Sends the command in the current thread. If a message is supplied, this is
919    * shown before the thread is started, and removed when it completes. May
920    * return a reply to the command if requested.
921    * 
922    * @param cmd
923    * @param msg
924    * @param getReply
925    * @return
926    */
927   private List<String> executeSynchronous(String cmd, String msg, boolean getReply)
928   {
929     final JalviewStructureDisplayI theViewer = getViewer();
930     final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
931     try
932     {
933       return executeCommand(cmd, getReply);
934     } finally
935     {
936       if (msg != null)
937       {
938         theViewer.stopProgressBar(null, handle);
939       }
940     }
941   }
942
943   /**
944    * Sends the command in a separate thread. If a message is supplied, this is
945    * shown before the thread is started, and removed when it completes. No value
946    * is returned.
947    * 
948    * @param cmd
949    * @param msg
950    */
951   private void executeAsynchronous(String cmd, String msg)
952   {
953     final JalviewStructureDisplayI theViewer = getViewer();
954     final long handle = msg == null ? 0 : theViewer.startProgressBar(msg);
955
956     SwingUtilities.invokeLater(new Runnable()
957     {
958       @Override
959       public void run()
960       {
961         try
962         {
963           executeCommand(cmd, false);
964         } finally
965         {
966           if (msg != null)
967           {
968             theViewer.stopProgressBar(null, handle);
969           }
970         }
971       }
972     });
973   }
974
975   protected abstract List<String> executeCommand(String command,
976           boolean getReply);
977
978   protected List<String> executeCommands(boolean getReply,
979           String... commands)
980   {
981     List<String> response = null;
982     for (String cmd : commands)
983     {
984       response = executeCommand(cmd, getReply);
985     }
986     return response;
987   }
988
989   /**
990    * colour any structures associated with sequences in the given alignment
991    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
992    * if colourBySequence is enabled.
993    */
994   public void colourBySequence(AlignmentViewPanel alignmentv)
995   {
996     if (!colourBySequence || !isLoadingFinished())
997     {
998       return;
999     }
1000     if (getSsm() == null)
1001     {
1002       return;
1003     }
1004     String[] files = getStructureFiles();
1005
1006     SequenceRenderer sr = getSequenceRenderer(alignmentv);
1007
1008     String[] colourBySequenceCommands = commandGenerator
1009             .colourBySequence(getSsm(), files, getSequence(), sr,
1010                     alignmentv);
1011     executeCommands(false, colourBySequenceCommands);
1012   }
1013
1014   /**
1015    * Centre the display in the structure viewer
1016    */
1017   public void focusView()
1018   {
1019     executeCommand(commandGenerator.focusView(), false);
1020   }
1021
1022   /**
1023    * Generates and executes a command to show only specified chains in the
1024    * structure viewer. The list of chains to show should contain entries
1025    * formatted as "pdbid:chaincode".
1026    * 
1027    * @param toShow
1028    */
1029   public void showChains(List<String> toShow)
1030   {
1031     // todo or reformat toShow list entries as modelNo:pdbId:chainCode ?
1032
1033     /*
1034      * Reformat the pdbid:chainCode values as modelNo:chainCode
1035      * since this is what is needed to construct the viewer command
1036      * todo: find a less messy way to do this
1037      */
1038     List<String> showThese = new ArrayList<>();
1039     for (String chainId : toShow)
1040     {
1041       String[] tokens = chainId.split("\\:");
1042       if (tokens.length == 2)
1043       {
1044         String pdbFile = getFileForChain(chainId);
1045         int modelNo = getModelNoForFile(pdbFile);
1046         String model = modelNo == -1 ? "" : String.valueOf(modelNo);
1047         showThese.add(model + ":" + tokens[1]);
1048       }
1049     }
1050     executeCommand(commandGenerator.showChains(showThese), false);
1051   }
1052
1053   /**
1054    * Answers the structure viewer's model number given a PDB file name. Returns
1055    * -1 if model number is not found.
1056    * 
1057    * @param chainId
1058    * @return
1059    */
1060   protected abstract int getModelNoForFile(String chainId);
1061
1062   public boolean hasFileLoadingError()
1063   {
1064     return fileLoadingError != null && fileLoadingError.length() > 0;
1065   }
1066
1067   /**
1068    * Returns the FeatureRenderer for the given alignment view, or null if
1069    * feature display is turned off in the view.
1070    * 
1071    * @param avp
1072    * @return
1073    */
1074   public FeatureRenderer getFeatureRenderer(AlignmentViewPanel avp)
1075   {
1076     AlignmentViewPanel ap = (avp == null) ? getViewer().getAlignmentPanel()
1077             : avp;
1078     return ap.getAlignViewport().isShowSequenceFeatures()
1079             ? ap.getFeatureRenderer()
1080             : null;
1081   }
1082
1083   protected void setStructureCommands(StructureCommandsI cmd)
1084   {
1085     commandGenerator = cmd;
1086   }
1087
1088   /**
1089    * Records association of one chain id (formatted as "pdbid:chainCode") with
1090    * the corresponding PDB file name
1091    * 
1092    * @param chainId
1093    * @param fileName
1094    */
1095   public void addChainFile(String chainId, String fileName)
1096   {
1097     chainFile.put(chainId, fileName);
1098   }
1099
1100   /**
1101    * Returns the PDB filename for the given chain id (formatted as
1102    * "pdbid:chainCode"), or null if not found
1103    * 
1104    * @param chainId
1105    * @return
1106    */
1107   protected String getFileForChain(String chainId)
1108   {
1109     return chainFile.get(chainId);
1110   }
1111 }