JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / src / jalview / ext / rbvi / chimera / JalviewChimeraBinding.java
index b649a64..415fc1b 100644 (file)
@@ -1,6 +1,6 @@
 /*
- * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
- * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
+ * Copyright (C) 2015 The Jalview Authors
  * 
  * This file is part of Jalview.
  * 
  */
 package jalview.ext.rbvi.chimera;
 
-import java.awt.Color;
-import java.net.BindException;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
-import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
-import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
-import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
-
 import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureRenderer;
 import jalview.api.SequenceRenderer;
@@ -44,15 +32,30 @@ import jalview.httpserver.AbstractRequestHandler;
 import jalview.schemes.ColourSchemeI;
 import jalview.schemes.ResidueProperties;
 import jalview.structure.AtomSpec;
-import jalview.structure.StructureMapping;
 import jalview.structure.StructureMappingcommandSet;
 import jalview.structure.StructureSelectionManager;
 import jalview.structures.models.AAStructureBindingModel;
-import jalview.util.Comparison;
 import jalview.util.MessageManager;
 
+import java.awt.Color;
+import java.net.BindException;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import ext.edu.ucsf.rbvi.strucviz2.ChimeraManager;
+import ext.edu.ucsf.rbvi.strucviz2.ChimeraModel;
+import ext.edu.ucsf.rbvi.strucviz2.StructureManager;
+import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
+
 public abstract class JalviewChimeraBinding extends AAStructureBindingModel
 {
+  // Chimera clause to exclude alternate locations in atom selection
+  private static final String NO_ALTLOCS = "&~@.B-Z&~@.2-9";
+
+  private static final String COLOURING_CHIMERA = MessageManager
+          .getString("status.colouring_chimera");
 
   private static final boolean debug = false;
 
@@ -60,8 +63,6 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
 
   private static final String ALPHACARBON = "CA";
 
-  private StructureManager csm;
-
   /*
    * Object through which we talk to Chimera
    */
@@ -85,17 +86,6 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
    */
   private boolean loadingFinished = true;
 
-  /*
-   * state flag used to check if the Chimera viewer's paint method can be called
-   */
-  private boolean finishedInit = false;
-
-  private List<String> atomsPicked = new ArrayList<String>();
-
-  private List<String> chainNames;
-
-  private Map<String, String> chainFile;
-
   public String fileLoadingError;
 
   /*
@@ -215,7 +205,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   {
     super(ssm, pdbentry, sequenceIs, chains, protocol);
     viewer = new ChimeraManager(
-            csm = new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
+            new ext.edu.ucsf.rbvi.strucviz2.StructureManager(true));
   }
 
   /**
@@ -236,20 +226,6 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   }
 
   /**
-   * Constructor
-   * 
-   * @param ssm
-   * @param theViewer
-   */
-  public JalviewChimeraBinding(StructureSelectionManager ssm,
-          ChimeraManager theViewer)
-  {
-    super(ssm, null);
-    viewer = theViewer;
-    csm = viewer.getStructureManager();
-  }
-
-  /**
    * Construct a title string for the viewer window based on the data Jalview
    * knows about
    * 
@@ -262,35 +238,37 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   }
 
   /**
-   * prepare the view for a given set of models/chains. chainList contains
-   * strings of the form 'pdbfilename:Chaincode'
+   * Tells Chimera to display only the specified chains
    * 
    * @param toshow
-   *          list of chains to make visible
    */
-  public void centerViewer(List<String> toshow)
+  public void showChains(List<String> toshow)
   {
+    /*
+     * Construct a chimera command like
+     * 
+     * ~display #*;~ribbon #*;ribbon :.A,:.B
+     */
     StringBuilder cmd = new StringBuilder(64);
-    int mlength, p;
-    for (String lbl : toshow)
+    boolean first = true;
+    for (String chain : toshow)
     {
-      mlength = 0;
-      do
+      if (!first)
       {
-        p = mlength;
-        mlength = lbl.indexOf(":", p);
-      } while (p < mlength && mlength < (lbl.length() - 2));
-      // TODO: lookup each pdb id and recover proper model number for it.
-      cmd.append("#" + getModelNum(chainFile.get(lbl)) + "."
-              + lbl.substring(mlength + 1) + " or ");
-    }
-    if (cmd.length() > 0)
-    {
-      cmd.setLength(cmd.length() - 4);
+        cmd.append(",");
+      }
+      cmd.append(":.").append(chain);
+      first = false;
     }
-    String cmdstring = cmd.toString();
-    evalStateCommand("~display #*; ~ribbon #*; ribbon " + cmdstring
-            + ";focus " + cmdstring, false);
+
+    /*
+     * could append ";focus" to this command to resize the display to fill the
+     * window, but it looks more helpful not to (easier to relate chains to the
+     * whole)
+     */
+    final String command = "~display #*; ~ribbon #*; ribbon "
+            + cmd.toString();
+    sendChimeraCommand(command, false);
   }
 
   /**
@@ -318,287 +296,182 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   public void colourByChain()
   {
     colourBySequence = false;
-    evalStateCommand("rainbow chain", false);
-  }
-
-  public void colourByCharge()
-  {
-    colourBySequence = false;
-    evalStateCommand(
-            "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS",
-            false);
+    sendAsynchronousCommand("rainbow chain", COLOURING_CHIMERA);
   }
 
   /**
-   * superpose the structures associated with sequences in the alignment
-   * according to their corresponding positions.
+   * Constructs and sends a Chimera command to colour by charge
+   * <ul>
+   * <li>Aspartic acid and Glutamic acid (negative charge) red</li>
+   * <li>Lysine and Arginine (positive charge) blue</li>
+   * <li>Cysteine - yellow</li>
+   * <li>all others - white</li>
+   * </ul>
    */
-  public void superposeStructures(AlignmentI alignment)
-  {
-    superposeStructures(alignment, -1, null);
-  }
-
-  /**
-   * superpose the structures associated with sequences in the alignment
-   * according to their corresponding positions. ded)
-   * 
-   * @param refStructure
-   *          - select which pdb file to use as reference (default is -1 - the
-   *          first structure in the alignment)
-   */
-  public void superposeStructures(AlignmentI alignment, int refStructure)
+  public void colourByCharge()
   {
-    superposeStructures(alignment, refStructure, null);
+    colourBySequence = false;
+    String command = "color white;color red ::ASP;color red ::GLU;color blue ::LYS;color blue ::ARG;color yellow ::CYS";
+    sendAsynchronousCommand(command, COLOURING_CHIMERA);
   }
 
   /**
-   * superpose the structures associated with sequences in the alignment
-   * according to their corresponding positions. ded)
+   * Construct and send a command to align structures against a reference
+   * structure, based on one or more sequence alignments
    * 
-   * @param refStructure
-   *          - select which pdb file to use as reference (default is -1 - the
-   *          first structure in the alignment)
-   * @param hiddenCols
-   *          TODO
+   * @param _alignment
+   *          an array of alignments to process
+   * @param _refStructure
+   *          an array of corresponding reference structures (index into pdb
+   *          file array); if a negative value is passed, the first PDB file
+   *          mapped to an alignment sequence is used as the reference for
+   *          superposition
+   * @param _hiddenCols
+   *          an array of corresponding hidden columns for each alignment
    */
-  public void superposeStructures(AlignmentI alignment, int refStructure,
-          ColumnSelection hiddenCols)
-  {
-    superposeStructures(new AlignmentI[]
-    { alignment }, new int[]
-    { refStructure }, new ColumnSelection[]
-    { hiddenCols });
-  }
-
   public void superposeStructures(AlignmentI[] _alignment,
           int[] _refStructure, ColumnSelection[] _hiddenCols)
   {
-    assert (_alignment.length == _refStructure.length && _alignment.length != _hiddenCols.length);
-    StringBuilder allComs = new StringBuilder(128); // Chimera superposition cmd
+    StringBuilder allComs = new StringBuilder(128);
     String[] files = getPdbFile();
-    // check to see if we are still waiting for Chimera files
-    long starttime = System.currentTimeMillis();
-    boolean waiting = true;
-    do
-    {
-      waiting = false;
-      for (String file : files)
-      {
-        try
-        {
-          // HACK - in Jalview 2.8 this call may not be threadsafe so we catch
-          // every possible exception
-          StructureMapping[] sm = getSsm().getMapping(file);
-          if (sm == null || sm.length == 0)
-          {
-            waiting = true;
-          }
-        } catch (Exception x)
-        {
-          waiting = true;
-        } catch (Error q)
-        {
-          waiting = true;
-        }
-      }
-      // we wait around for a reasonable time before we give up
-    } while (waiting
-            && System.currentTimeMillis() < (10000 + 1000 * files.length + starttime));
-    if (waiting)
+
+    if (!waitForFileLoad(files))
     {
-      System.err
-              .println("RUNTIME PROBLEM: Chimera seems to be taking a long time to process all the structures.");
       return;
     }
+
     refreshPdbEntries();
-    StringBuffer selectioncom = new StringBuffer();
+    StringBuilder selectioncom = new StringBuilder(256);
     for (int a = 0; a < _alignment.length; a++)
     {
       int refStructure = _refStructure[a];
       AlignmentI alignment = _alignment[a];
       ColumnSelection hiddenCols = _hiddenCols[a];
-      if (a > 0
-              && selectioncom.length() > 0
-              && !selectioncom.substring(selectioncom.length() - 1).equals(
-                      " "))
-      {
-        selectioncom.append(" ");
-      }
-      // process this alignment
+
       if (refStructure >= files.length)
       {
-        System.err.println("Invalid reference structure value "
+        System.err.println("Ignoring invalid reference structure value "
                 + refStructure);
         refStructure = -1;
       }
-      if (refStructure < -1)
-      {
-        refStructure = -1;
-      }
 
+      /*
+       * 'matched' array will hold 'true' for visible alignment columns where
+       * all sequences have a residue with a mapping to the PDB structure
+       */
       boolean matched[] = new boolean[alignment.getWidth()];
       for (int m = 0; m < matched.length; m++)
       {
-
         matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
       }
 
-      int commonrpositions[][] = new int[files.length][alignment.getWidth()];
-      String isel[] = new String[files.length];
-      String[] targetC = new String[files.length];
-      String[] chainNames = new String[files.length];
-      String[] atomSpec = new String[files.length];
-      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+      SuperposeData[] structures = new SuperposeData[files.length];
+      for (int f = 0; f < files.length; f++)
       {
-        StructureMapping[] mapping = getSsm().getMapping(files[pdbfnum]);
-        // RACE CONDITION - getMapping only returns Jmol loaded filenames once
-        // Jmol callback has completed.
-        if (mapping == null || mapping.length < 1)
-        {
-          throw new Error(MessageManager.getString("error.implementation_error_chimera_getting_data"));
-        }
-        int lastPos = -1;
-        final int seqCountForPdbFile = getSequence()[pdbfnum].length;
-        for (int s = 0; s < seqCountForPdbFile; s++)
+        structures[f] = new SuperposeData(alignment.getWidth());
+      }
+
+      /*
+       * Calculate the superposable alignment columns ('matched'), and the
+       * corresponding structure residue positions (structures.pdbResNo)
+       */
+      int candidateRefStructure = findSuperposableResidues(alignment,
+              matched, structures);
+      if (refStructure < 0)
+      {
+        /*
+         * If no reference structure was specified, pick the first one that has
+         * a mapping in the alignment
+         */
+        refStructure = candidateRefStructure;
+      }
+
+      int nmatched = 0;
+      for (boolean b : matched)
+      {
+        if (b)
         {
-          for (int sp, m = 0; m < mapping.length; m++)
-          {
-            final SequenceI theSequence = getSequence()[pdbfnum][s];
-            if (mapping[m].getSequence() == theSequence
-                    && (sp = alignment.findIndex(theSequence)) > -1)
-            {
-              if (refStructure == -1)
-              {
-                refStructure = pdbfnum;
-              }
-              SequenceI asp = alignment.getSequenceAt(sp);
-              for (int r = 0; r < matched.length; r++)
-              {
-                if (!matched[r])
-                {
-                  continue;
-                }
-                matched[r] = false; // assume this is not a good site
-                if (r >= asp.getLength())
-                {
-                  continue;
-                }
-
-                if (Comparison.isGap(asp.getCharAt(r)))
-                {
-                  // no mapping to gaps in sequence
-                  continue;
-                }
-                int t = asp.findPosition(r); // sequence position
-                int apos = mapping[m].getAtomNum(t);
-                int pos = mapping[m].getPDBResNum(t);
-
-                if (pos < 1 || pos == lastPos)
-                {
-                  // can't align unmapped sequence
-                  continue;
-                }
-                matched[r] = true; // this is a good ite
-                lastPos = pos;
-                // just record this residue position
-                commonrpositions[pdbfnum][r] = pos;
-              }
-              // create model selection suffix
-              isel[pdbfnum] = "#" + pdbfnum;
-              if (mapping[m].getChain() == null
-                      || mapping[m].getChain().trim().length() == 0)
-              {
-                targetC[pdbfnum] = "";
-              }
-              else
-              {
-                targetC[pdbfnum] = "." + mapping[m].getChain();
-              }
-              chainNames[pdbfnum] = mapping[m].getPdbId()
-                      + targetC[pdbfnum];
-              atomSpec[pdbfnum] = asp.getRNA() != null ? PHOSPHORUS : ALPHACARBON;
-              // move on to next pdb file
-              s = seqCountForPdbFile;
-              break;
-            }
-          }
+          nmatched++;
         }
       }
+      if (nmatched < 4)
+      {
+        // TODO: bail out here because superposition illdefined?
+      }
 
-      // TODO: consider bailing if nmatched less than 4 because superposition
-      // not
-      // well defined.
-      // TODO: refactor superposable position search (above) from jmol selection
-      // construction (below)
-
+      /*
+       * Generate select statements to select regions to superimpose structures
+       */
       String[] selcom = new String[files.length];
-      int nmatched = 0;
-      String sep = "";
-      // generate select statements to select regions to superimpose structures
+      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
       {
-        for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+        String chainCd = "." + structures[pdbfnum].chain;
+        int lpos = -1;
+        boolean run = false;
+        StringBuilder molsel = new StringBuilder();
+        for (int r = 0; r < matched.length; r++)
         {
-          String chainCd = targetC[pdbfnum];
-          int lpos = -1;
-          boolean run = false;
-          StringBuffer molsel = new StringBuffer();
-          for (int r = 0; r < matched.length; r++)
+          if (matched[r])
           {
-            if (matched[r])
+            int pdbResNum = structures[pdbfnum].pdbResNo[r];
+            if (lpos != pdbResNum - 1)
             {
-              if (pdbfnum == 0)
-              {
-                nmatched++;
-              }
-              if (lpos != commonrpositions[pdbfnum][r] - 1)
-              {
-                // discontinuity
-                if (lpos != -1)
-                {
-                  molsel.append((run ? "" : ":") + lpos);
-                  molsel.append(chainCd);
-                  molsel.append(",");
-                }
-              }
-              else
+              /*
+               * discontiguous - append last residue now
+               */
+              if (lpos != -1)
               {
-                // continuous run - and lpos >-1
-                if (!run)
-                {
-                  // at the beginning, so add dash
-                  molsel.append(":" + lpos);
-                  molsel.append("-");
-                }
-                run = true;
+                molsel.append(String.valueOf(lpos));
+                molsel.append(chainCd);
+                molsel.append(",");
               }
-              lpos = commonrpositions[pdbfnum][r];
-              // molsel.append(lpos);
+              run = false;
             }
-          }
-          // add final selection phrase
-          if (lpos != -1)
-          {
-            molsel.append((run ? "" : ":") + lpos);
-            molsel.append(chainCd);
-            // molsel.append("");
-          }
-          if (molsel.length() > 1)
-          {
-            selcom[pdbfnum] = molsel.toString();
-            selectioncom.append("#" + pdbfnum);
-            selectioncom.append(selcom[pdbfnum]);
-            selectioncom.append(" ");
-            if (pdbfnum < files.length - 1)
+            else
             {
-              selectioncom.append("| ");
+              /*
+               * extending a contiguous run
+               */
+              if (!run)
+              {
+                /*
+                 * start the range selection
+                 */
+                molsel.append(String.valueOf(lpos));
+                molsel.append("-");
+              }
+              run = true;
             }
+            lpos = pdbResNum;
           }
-          else
+        }
+
+        /*
+         * and terminate final selection
+         */
+        if (lpos != -1)
+        {
+          molsel.append(String.valueOf(lpos));
+          molsel.append(chainCd);
+        }
+        if (molsel.length() > 1)
+        {
+          selcom[pdbfnum] = molsel.toString();
+          selectioncom.append("#").append(String.valueOf(pdbfnum))
+                  .append(":");
+          selectioncom.append(selcom[pdbfnum]);
+          selectioncom.append(" ");
+          if (pdbfnum < files.length - 1)
           {
-            selcom[pdbfnum] = null;
+            selectioncom.append("| ");
           }
         }
+        else
+        {
+          selcom[pdbfnum] = null;
+        }
       }
+
       StringBuilder command = new StringBuilder(256);
       for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
       {
@@ -614,20 +487,24 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
 
         /*
          * Form Chimera match command, from the 'new' structure to the
-         * 'reference' structure e.g. (residues 1-91, chain B/A, alphacarbons):
+         * 'reference' structure e.g. (50 residues, chain B/A, alphacarbons):
          * 
-         * match #1:1-91.B@CA #0:1-91.A@CA
+         * match #1:1-30.B,81-100.B@CA #0:21-40.A,61-90.A@CA
          * 
          * @see
          * https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/match.html
          */
-        command.append("match #" + pdbfnum /* +".1" */);
-        // TODO: handle sub-models
+        command.append("match ").append(getModelSpec(pdbfnum)).append(":");
         command.append(selcom[pdbfnum]);
-        command.append("@" + atomSpec[pdbfnum]);
-        command.append(" #" + refStructure /* +".1" */);
+        command.append("@").append(
+                structures[pdbfnum].isRna ? PHOSPHORUS : ALPHACARBON);
+        // JAL-1757 exclude alternate CA locations
+        command.append(NO_ALTLOCS);
+        command.append(" ").append(getModelSpec(refStructure)).append(":");
         command.append(selcom[refStructure]);
-        command.append("@" + atomSpec[refStructure]);
+        command.append("@").append(
+                structures[refStructure].isRna ? PHOSPHORUS : ALPHACARBON);
+        command.append(NO_ALTLOCS);
       }
       if (selectioncom.length() > 0)
       {
@@ -637,13 +514,14 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
           System.out.println("Superimpose command(s):\n"
                   + command.toString());
         }
-        allComs.append("~display all; chain @CA|P; ribbon "
-                + selectioncom.toString() + ";"+command.toString());
-        // selcom.append("; ribbons; ");
+        allComs.append("~display all; chain @CA|P; ribbon ")
+                .append(selectioncom.toString())
+                .append(";" + command.toString());
       }
     }
     if (selectioncom.length() > 0)
-    {// finally, mark all regions that were superposed.
+    {
+      // TODO: visually distinguish regions that were superposed
       if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
       {
         selectioncom.setLength(selectioncom.length() - 1);
@@ -652,24 +530,63 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
       {
         System.out.println("Select regions:\n" + selectioncom.toString());
       }
-      allComs.append("; ~display all; chain @CA|P; ribbon "
-              + selectioncom.toString() + "; focus");
-      // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
-      evalStateCommand(allComs.toString(), true /* false */);
+      allComs.append("; ~display all; chain @CA|P; ribbon ")
+              .append(selectioncom.toString()).append("; focus");
+      sendChimeraCommand(allComs.toString(), false);
+    }
+
+  }
+
+  /**
+   * Helper method to construct model spec in Chimera format:
+   * <ul>
+   * <li>#0 (#1 etc) for a PDB file with no sub-models</li>
+   * <li>#0.1 (#1.1 etc) for a PDB file with sub-models</li>
+   * <ul>
+   * Note for now we only ever choose the first of multiple models. This
+   * corresponds to the hard-coded Jmol equivalent (compare {1.1}). Refactor in
+   * future if there is a need to select specific sub-models.
+   * 
+   * @param pdbfnum
+   * @return
+   */
+  protected String getModelSpec(int pdbfnum)
+  {
+    if (pdbfnum < 0 || pdbfnum >= getPdbCount())
+    {
+      return "";
     }
-    
+
+    /*
+     * For now, the test for having sub-models is whether multiple Chimera
+     * models are mapped for the PDB file; the models are returned as a response
+     * to the Chimera command 'list models type molecule', see
+     * ChimeraManager.getModelList().
+     */
+    List<ChimeraModel> maps = chimeraMaps.get(getPdbFile()[pdbfnum]);
+    boolean hasSubModels = maps != null && maps.size() > 1;
+    return "#" + String.valueOf(pdbfnum) + (hasSubModels ? ".1" : "");
   }
 
-  private void checkLaunched()
+  /**
+   * Launch Chimera, unless an instance linked to this object is already
+   * running. Returns true if chimera is successfully launched, or already
+   * running, else false.
+   * 
+   * @return
+   */
+  public boolean launchChimera()
   {
     if (!viewer.isChimeraLaunched())
     {
-      viewer.launchChimera(StructureManager.getChimeraPaths());
+      return viewer.launchChimera(StructureManager.getChimeraPaths());
     }
-    if (!viewer.isChimeraLaunched())
+    if (viewer.isChimeraLaunched())
     {
-      log("Failed to launch Chimera!");
+      return true;
     }
+    log("Failed to launch Chimera!");
+    return false;
   }
 
   /**
@@ -684,21 +601,24 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   }
 
   /**
-   * Send a command to Chimera, launching it first if necessary, and optionally
-   * log any responses.
+   * Send a command to Chimera, and optionally log any responses.
    * 
    * @param command
    * @param logResponse
    */
-  public void evalStateCommand(final String command, boolean logResponse)
+  public void sendChimeraCommand(final String command, boolean logResponse)
   {
+    if (viewer == null)
+    {
+      // ? thread running after viewer shut down
+      return;
+    }
     viewerCommandHistory(false);
-    checkLaunched();
     if (lastCommand == null || !lastCommand.equals(command))
     {
       // trim command or it may never find a match in the replyLog!!
       lastReply = viewer.sendChimeraCommand(command.trim(), logResponse);
-      if (debug && logResponse)
+      if (logResponse && debug)
       {
         log("Response from command ('" + command + "') was:\n" + lastReply);
       }
@@ -708,6 +628,16 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   }
 
   /**
+   * Send a Chimera command asynchronously in a new thread. If the progress
+   * message is not null, display this message while the command is executing.
+   * 
+   * @param command
+   * @param progressMsg
+   */
+  protected abstract void sendAsynchronousCommand(String command,
+          String progressMsg);
+
+  /**
    * colour any structures associated with sequences in the given alignment
    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
    * if colourBySequence is enabled.
@@ -739,7 +669,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
     {
       for (String command : cpdbbyseq.commands)
       {
-        executeWhenReady(command);
+        sendAsynchronousCommand(command, COLOURING_CHIMERA);
       }
     }
   }
@@ -765,7 +695,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   protected void executeWhenReady(String command)
   {
     waitForChimera();
-    evalStateCommand(command, false);
+    sendChimeraCommand(command, false);
     waitForChimera();
   }
 
@@ -773,15 +703,15 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   {
     while (viewer != null && viewer.isBusy())
     {
-      try {
+      try
+      {
         Thread.sleep(15);
       } catch (InterruptedException q)
-      {}
+      {
+      }
     }
   }
 
-
-
   // End StructureListener
   // //////////////////////////
 
@@ -809,7 +739,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
 
   /**
    * instruct the Jalview binding to update the pdbentries vector if necessary
-   * prior to matching the jmol view's contents to the list of structure files
+   * prior to matching the viewer's contents to the list of structure files
    * Jalview knows about.
    */
   public abstract void refreshPdbEntries();
@@ -840,6 +770,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
 
   // ////////////////////////////////
   // /StructureListener
+  @Override
   public synchronized String[] getPdbFile()
   {
     if (viewer == null)
@@ -884,46 +815,63 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
           AlignmentViewPanel alignment);
 
   /**
-   * Construct and send a command to highlight an atom.
+   * Construct and send a command to highlight zero, one or more atoms.
    * 
    * <pre>
    * Done by generating a command like (to 'highlight' position 44)
-   *   ~show #0:43.C;show #0:44.C
-   * Note this removes the highlight from the previous position.
+   *   show #0:44.C
    * </pre>
    */
-  public void highlightAtom(int atomIndex, int pdbResNum, String chain,
-          String pdbfile)
+  @Override
+  public void highlightAtoms(List<AtomSpec> atoms)
   {
-    List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
-    if (cms != null)
+    if (atoms == null)
+    {
+      return;
+    }
+    StringBuilder atomSpecs = new StringBuilder();
+    boolean first = true;
+    for (AtomSpec atom : atoms)
     {
-      StringBuilder sb = new StringBuilder();
-      sb.append(" #" + cms.get(0).getModelNumber());
-      sb.append(":" + pdbResNum);
-      if (!chain.equals(" "))
+      int pdbResNum = atom.getPdbResNum();
+      String chain = atom.getChain();
+      String pdbfile = atom.getPdbFile();
+      List<ChimeraModel> cms = chimeraMaps.get(pdbfile);
+      if (cms != null && !cms.isEmpty())
       {
-        sb.append("." + chain);
+        /*
+         * Formatting as #0:34.A,#1:33.A doesn't work as desired, so instead we
+         * concatenate multiple 'show' commands
+         */
+        atomSpecs.append(first ? "" : ";show ");
+        first = false;
+        atomSpecs.append("#" + cms.get(0).getModelNumber());
+        atomSpecs.append(":" + pdbResNum);
+        if (!chain.equals(" "))
+        {
+          atomSpecs.append("." + chain);
+        }
       }
-      String atomSpec = sb.toString();
+    }
+    String atomSpec = atomSpecs.toString();
 
-      StringBuilder command = new StringBuilder(32);
-      if (lastMousedOverAtomSpec != null)
-      {
-        command.append("~show " + lastMousedOverAtomSpec + ";");
-      }
-      viewerCommandHistory(false);
+    /*
+     * Avoid repeated commands for the same residue
+     */
+    if (atomSpec.equals(lastMousedOverAtomSpec))
+    {
+      return;
+    }
+
+    StringBuilder command = new StringBuilder(32);
+    viewerCommandHistory(false);
+    if (atomSpec.length() > 0)
+    {
       command.append("show ").append(atomSpec);
-      String cmd = command.toString();
-      if (cmd.length() > 0)
-      {
-        viewer.stopListening(chimeraListener.getUri());
-        viewer.sendChimeraCommand(cmd, false);
-        viewer.startListening(chimeraListener.getUri());
-      }
-      viewerCommandHistory(true);
-      this.lastMousedOverAtomSpec = atomSpec;
+      viewer.sendChimeraCommand(command.toString(), false);
     }
+    viewerCommandHistory(true);
+    this.lastMousedOverAtomSpec = atomSpec;
   }
 
   /**
@@ -948,26 +896,28 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
       {
         continue; // malformed
       }
-    
+
       int hashPos = atomSpec.indexOf("#");
       String modelSubmodel = atomSpec.substring(hashPos + 1, colonPos);
       int dotPos = modelSubmodel.indexOf(".");
       int modelId = 0;
-      try {
+      try
+      {
         modelId = Integer.valueOf(dotPos == -1 ? modelSubmodel
                 : modelSubmodel.substring(0, dotPos));
-      } catch (NumberFormatException e) {
+      } catch (NumberFormatException e)
+      {
         // ignore, default to model 0
       }
-    
+
       String residueChain = atomSpec.substring(colonPos + 1);
       dotPos = residueChain.indexOf(".");
       int pdbResNum = Integer.parseInt(dotPos == -1 ? residueChain
               : residueChain.substring(0, dotPos));
-    
+
       String chainId = dotPos == -1 ? "" : residueChain
               .substring(dotPos + 1);
-    
+
       /*
        * Work out the pdbfilename from the model number
        */
@@ -1033,7 +983,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
               / normalise + " ::" + res + ";");
     }
 
-    evalStateCommand(command.toString(),false);
+    sendAsynchronousCommand(command.toString(), COLOURING_CHIMERA);
     viewerCommandHistory(true);
   }
 
@@ -1073,7 +1023,7 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   /**
    * Send the Chimera 'background solid <color>" command.
    * 
-   * @see https
+   * @see https 
    *      ://www.cgl.ucsf.edu/chimera/current/docs/UsersGuide/midas/background
    *      .html
    * @param col
@@ -1082,25 +1032,14 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
   {
     viewerCommandHistory(false);
     double normalise = 255D;
-    final String command = "background solid " + col.getRed() / normalise + ","
-            + col.getGreen() / normalise + "," + col.getBlue()
+    final String command = "background solid " + col.getRed() / normalise
+            + "," + col.getGreen() / normalise + "," + col.getBlue()
             / normalise + ";";
     viewer.sendChimeraCommand(command, false);
     viewerCommandHistory(true);
   }
 
   /**
-   * 
-   * @param pdbfile
-   * @return text report of alignment between pdbfile and any associated
-   *         alignment sequences
-   */
-  public String printMapping(String pdbfile)
-  {
-    return getSsm().printMapping(pdbfile);
-  }
-
-  /**
    * Ask Chimera to save its session to the given file. Returns true if
    * successful, else false.
    * 
@@ -1135,24 +1074,45 @@ public abstract class JalviewChimeraBinding extends AAStructureBindingModel
    */
   public boolean openSession(String filepath)
   {
-    evalStateCommand("open " + filepath, true);
+    sendChimeraCommand("open " + filepath, true);
     // todo: test for failure - how?
     return true;
   }
 
-  public boolean isFinishedInit()
-  {
-    return finishedInit;
-  }
-
-  public void setFinishedInit(boolean finishedInit)
+  /**
+   * Returns a list of chains mapped in this viewer. Note this list is not
+   * currently scoped per structure.
+   * 
+   * @return
+   */
+  public List<String> getChainNames()
   {
-    this.finishedInit = finishedInit;
+    List<String> names = new ArrayList<String>();
+    String[][] allNames = getChains();
+    if (allNames != null)
+    {
+      for (String[] chainsForPdb : allNames)
+      {
+        if (chainsForPdb != null)
+        {
+          for (String chain : chainsForPdb)
+          {
+            if (chain != null && !names.contains(chain))
+            {
+              names.add(chain);
+            }
+          }
+        }
+      }
+    }
+    return names;
   }
 
-  public List<String> getChainNames()
+  /**
+   * Send a 'focus' command to Chimera to recentre the visible display
+   */
+  public void focusView()
   {
-    return chainNames;
+    sendChimeraCommand("focus", false);
   }
-
 }