JAL-1645 Version-Rel Version 2.9 Year-Rel 2015 Licensing glob
[jalview.git] / src / MCview / PDBCanvas.java
old mode 100755 (executable)
new mode 100644 (file)
index ee556a3..fdd673b
 /*
-* Jalview - A Sequence Alignment Editor and Viewer
-* Copyright (C) 2006 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 2
-* of the License, or (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
-*/
+ * Jalview - A Sequence Alignment Editor and Viewer (Version 2.9)
+ * Copyright (C) 2015 The Jalview Authors
+ * 
+ * This file is part of Jalview.
+ * 
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License 
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *  
+ * Jalview is distributed in the hope that it will be useful, but 
+ * WITHOUT ANY WARRANTY; without even the implied warranty 
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
+ * PURPOSE.  See the GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
 package MCview;
 
 import jalview.analysis.AlignSeq;
+import jalview.datamodel.PDBEntry;
+import jalview.datamodel.SequenceI;
+import jalview.gui.AlignmentPanel;
+import jalview.gui.FeatureRenderer;
+import jalview.gui.SequenceRenderer;
+import jalview.structure.AtomSpec;
+import jalview.structure.StructureListener;
+import jalview.structure.StructureMapping;
+import jalview.structure.StructureSelectionManager;
+
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Event;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+// JBPNote TODO: This class is quite noisy - needs proper log.info/log.debug
+import java.awt.Image;
+import java.awt.RenderingHints;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.io.PrintStream;
+import java.util.List;
+import java.util.Vector;
+
+import javax.swing.JPanel;
+import javax.swing.ToolTipManager;
+
+public class PDBCanvas extends JPanel implements MouseListener,
+        MouseMotionListener, StructureListener
+{
+  boolean redrawneeded = true;
 
-import jalview.datamodel.*;
+  int omx = 0;
 
-// JBPNote TODO: This class is quite noisy - needs proper log.info/log.debug
-import java.awt.*;
-import java.awt.event.*;
+  int mx = 0;
 
-import java.io.*;
+  int omy = 0;
 
-import java.util.*;
+  int my = 0;
 
-import javax.swing.*;
+  public PDBfile pdb;
 
+  PDBEntry pdbentry;
 
-public class PDBCanvas extends JPanel implements MouseListener, MouseMotionListener
-{
-    MCMatrix idmat = new MCMatrix(3, 3);
-    MCMatrix objmat = new MCMatrix(3, 3);
-    boolean redrawneeded = true;
-    int omx = 0;
-    int mx = 0;
-    int omy = 0;
-    int my = 0;
-    public PDBfile pdb;
-    int bsize;
-    Image img;
-    Graphics ig;
-    Dimension prefsize;
-    float[] centre = new float[3];
-    float[] width = new float[3];
-    float maxwidth;
-    float scale;
-    String inStr;
-    String inType;
-    boolean bysequence = true;
-    boolean depthcue = true;
-    boolean wire = false;
-    boolean bymolecule = false;
-    boolean zbuffer = true;
-    boolean dragging;
-    int xstart;
-    int xend;
-    int ystart;
-    int yend;
-    int xmid;
-    int ymid;
-    Font font = new Font("Helvetica", Font.PLAIN, 10);
-    jalview.gui.SeqCanvas seqcanvas;
-    public Sequence sequence;
-    final StringBuffer mappingDetails = new StringBuffer();
-    PDBChain mainchain;
-    Vector highlightRes;
-    boolean pdbAction = false;
-    boolean seqColoursReady = false;
-    jalview.gui.FeatureRenderer fr;
-    Color backgroundColour = Color.black;
-
-    public PDBCanvas(jalview.gui.SeqCanvas seqcanvas, Sequence seq)
-    {
-      this.seqcanvas = seqcanvas;
-      this.sequence = seq;
-      seqcanvas.setPDBCanvas(this);
-    }
-
-  public void setPDBFile(PDBfile pdb)
-   {
-        int max = -10;
-        int maxchain = -1;
-        int pdbstart = 0;
-        int pdbend = 0;
-        int seqstart = 0;
-        int seqend = 0;
-        AlignSeq maxAlignseq = null;
-
-        for (int i = 0; i < pdb.chains.size(); i++)
-        {
+  int bsize;
 
-          mappingDetails.append("\n\nPDB Sequence is :\nSequence = " + ((PDBChain) pdb.chains.elementAt(i)).sequence.getSequenceAsString());
-          mappingDetails.append("\nNo of residues = " + ((PDBChain) pdb.chains.elementAt(i)).residues.size()+"\n\n");
+  Image img;
 
-            // Now lets compare the sequences to get
-            // the start and end points.
-            // Align the sequence to the pdb
-            AlignSeq as = new AlignSeq(sequence,
-                    ((PDBChain) pdb.chains.elementAt(i)).sequence, AlignSeq.PEP);
-            as.calcScoreMatrix();
-            as.traceAlignment();
-            PrintStream  ps = new PrintStream(System.out)
-           {
-              public void print(String x) {
-                   mappingDetails.append(x);
-               }
-               public void println()
-               {
-                 mappingDetails.append("\n");
-               }
-            };
+  Graphics ig;
 
-            as.printAlignment(ps);
+  Dimension prefsize;
 
+  float[] centre = new float[3];
 
+  float[] width = new float[3];
 
-            if (as.maxscore > max)
-            {
-                max = as.maxscore;
-                maxchain = i;
-                pdbstart = as.seq2start;
-                pdbend = as.seq2end;
-                seqstart = as.seq1start + sequence.getStart()-1;
-                seqend = as.seq1end + sequence.getEnd()-1;
-                maxAlignseq = as;
-            }
+  float maxwidth;
 
-            mappingDetails.append("\nPDB start/end "  + pdbstart + " " + pdbend);
-            mappingDetails.append("\nSEQ start/end "+ seqstart + " " + seqend);
-        }
+  float scale;
 
-        mainchain = (PDBChain) pdb.chains.elementAt(maxchain);
-
-        mainchain.pdbstart = pdbstart;
-        mainchain.pdbend = pdbend;
-        mainchain.seqstart = seqstart;
-        mainchain.seqend = seqend;
-        mainchain.isVisible = true;
-        mainchain.makeExactMapping(maxAlignseq, sequence);
-        mainchain.transferRESNUMFeatures(sequence, null);
-        seqcanvas.getFeatureRenderer().featuresAdded();
-        this.pdb = pdb;
-        this.prefsize = new Dimension(getWidth(), getHeight());
-
-        //Initialize the matrices to identity
-        for (int i = 0; i < 3; i++) {
-            for (int j = 0; j < 3; j++) {
-                if (i != j) {
-                    idmat.addElement(i, j, 0);
-                    objmat.addElement(i, j, 0);
-                } else {
-                    idmat.addElement(i, j, 1);
-                    objmat.addElement(i, j, 1);
-                }
-            }
-        }
+  String inStr;
 
-        addMouseMotionListener(this);
-        addMouseListener(this);
+  String inType;
 
-        addMouseWheelListener(new MouseWheelListener()
-        {
-          public void mouseWheelMoved(MouseWheelEvent e)
-          {
-            if (e.getWheelRotation() > 0)
-            {
-              scale = (float) (scale * 1.1);
-              redrawneeded = true;
-              repaint();
-            }
+  boolean bysequence = true;
 
-            else
-            {
-              scale = (float) (scale * 0.9);
-              redrawneeded = true;
-              repaint();
-            }
-          }
-       });
+  boolean depthcue = true;
 
+  boolean wire = false;
 
-        findCentre();
-        findWidth();
+  boolean bymolecule = false;
 
-        setupBonds();
+  boolean zbuffer = true;
 
-        scale = findScale();
+  boolean dragging;
 
-        ToolTipManager.sharedInstance().registerComponent(this);
-        ToolTipManager.sharedInstance().setInitialDelay(0);
-        ToolTipManager.sharedInstance().setDismissDelay(10000);
-    }
+  int xstart;
 
+  int xend;
 
-    Vector visiblebonds;
-    void setupBonds()
-    {
-      seqColoursReady = false;
-      // Sort the bonds by z coord
-      visiblebonds = new Vector();
+  int ystart;
 
-      for (int ii = 0; ii < pdb.chains.size(); ii++)
-      {
-        if ( ( (PDBChain) pdb.chains.elementAt(ii)).isVisible)
-        {
-          Vector tmp = ( (PDBChain) pdb.chains.elementAt(ii)).bonds;
+  int yend;
 
-          for (int i = 0; i < tmp.size(); i++)
-          {
-            visiblebonds.addElement(tmp.elementAt(i));
-          }
-        }
-      }
+  int xmid;
 
-      updateSeqColours();
-      seqColoursReady = true;
-      redrawneeded = true;
-      repaint();
-    }
+  int ymid;
 
+  Font font = new Font("Helvetica", Font.PLAIN, 10);
 
-    public void findWidth() {
-        float[] max = new float[3];
-        float[] min = new float[3];
+  jalview.gui.SeqCanvas seqcanvas;
 
-        max[0] = (float) -1e30;
-        max[1] = (float) -1e30;
-        max[2] = (float) -1e30;
+  public SequenceI[] sequence;
 
-        min[0] = (float) 1e30;
-        min[1] = (float) 1e30;
-        min[2] = (float) 1e30;
+  final StringBuffer mappingDetails = new StringBuffer();
 
-        for (int ii = 0; ii < pdb.chains.size(); ii++) {
-            if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) {
-                Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds;
+  PDBChain mainchain;
 
-                for (int i = 0; i < bonds.size(); i++) {
-                    Bond tmp = (Bond) bonds.elementAt(i);
+  Vector<String> highlightRes;
 
-                    if (tmp.start[0] >= max[0]) {
-                        max[0] = tmp.start[0];
-                    }
+  boolean pdbAction = false;
 
-                    if (tmp.start[1] >= max[1]) {
-                        max[1] = tmp.start[1];
-                    }
+  boolean seqColoursReady = false;
 
-                    if (tmp.start[2] >= max[2]) {
-                        max[2] = tmp.start[2];
-                    }
+  jalview.renderer.seqfeatures.FeatureRenderer fr;
 
-                    if (tmp.start[0] <= min[0]) {
-                        min[0] = tmp.start[0];
-                    }
+  Color backgroundColour = Color.black;
 
-                    if (tmp.start[1] <= min[1]) {
-                        min[1] = tmp.start[1];
-                    }
+  AlignmentPanel ap;
 
-                    if (tmp.start[2] <= min[2]) {
-                        min[2] = tmp.start[2];
-                    }
+  StructureSelectionManager ssm;
 
-                    if (tmp.end[0] >= max[0]) {
-                        max[0] = tmp.end[0];
-                    }
+  String errorMessage;
 
-                    if (tmp.end[1] >= max[1]) {
-                        max[1] = tmp.end[1];
-                    }
+  void init(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
+          AlignmentPanel ap, String protocol)
+  {
+    this.ap = ap;
+    this.pdbentry = pdbentry;
+    this.sequence = seq;
 
-                    if (tmp.end[2] >= max[2]) {
-                        max[2] = tmp.end[2];
-                    }
+    ssm = ap.av.getStructureSelectionManager();
 
-                    if (tmp.end[0] <= min[0]) {
-                        min[0] = tmp.end[0];
-                    }
+    try
+    {
+      pdb = ssm.setMapping(seq, chains, pdbentry.getFile(), protocol);
 
-                    if (tmp.end[1] <= min[1]) {
-                        min[1] = tmp.end[1];
-                    }
+      if (protocol.equals(jalview.io.AppletFormatAdapter.PASTE))
+      {
+        pdbentry.setFile("INLINE" + pdb.id);
+      }
 
-                    if (tmp.end[2] <= min[2]) {
-                        min[2] = tmp.end[2];
-                    }
-                }
-            }
-        }
-        /*
-        System.out.println("xmax " + max[0] + " min " + min[0]);
-        System.out.println("ymax " + max[1] + " min " + min[1]);
-        System.out.println("zmax " + max[2] + " min " + min[2]);*/
+    } catch (Exception ex)
+    {
+      ex.printStackTrace();
+      return;
+    }
 
-        width[0] = (float) Math.abs(max[0] - min[0]);
-        width[1] = (float) Math.abs(max[1] - min[1]);
-        width[2] = (float) Math.abs(max[2] - min[2]);
+    if (pdb == null)
+    {
+      errorMessage = "Error loading file: " + pdbentry.getId();
+      return;
+    }
+    pdbentry.setId(pdb.id);
 
-        maxwidth = width[0];
+    ssm.addStructureViewerListener(this);
 
-        if (width[1] > width[0]) {
-            maxwidth = width[1];
-        }
+    colourBySequence();
 
-        if (width[2] > width[1]) {
-            maxwidth = width[2];
-        }
+    int max = -10;
+    int maxchain = -1;
+    int pdbstart = 0;
+    int pdbend = 0;
+    int seqstart = 0;
+    int seqend = 0;
 
-       // System.out.println("Maxwidth = " + maxwidth);
-    }
+    // JUST DEAL WITH ONE SEQUENCE FOR NOW
+    SequenceI sequence = seq[0];
 
-    public float findScale() {
-        int dim;
-        int width;
-        int height;
+    for (int i = 0; i < pdb.chains.size(); i++)
+    {
 
-        if (getWidth() != 0) {
-            width = getWidth();
-            height = getHeight();
-        } else {
-            width = prefsize.width;
-            height = prefsize.height;
+      mappingDetails.append("\n\nPDB Sequence is :\nSequence = "
+              + pdb.chains.elementAt(i).sequence.getSequenceAsString());
+      mappingDetails.append("\nNo of residues = "
+              + pdb.chains.elementAt(i).residues.size() + "\n\n");
+
+      // Now lets compare the sequences to get
+      // the start and end points.
+      // Align the sequence to the pdb
+      AlignSeq as = new AlignSeq(sequence,
+              pdb.chains.elementAt(i).sequence, "pep");
+      as.calcScoreMatrix();
+      as.traceAlignment();
+      PrintStream ps = new PrintStream(System.out)
+      {
+        public void print(String x)
+        {
+          mappingDetails.append(x);
         }
 
-        if (width < height) {
-            dim = width;
-        } else {
-            dim = height;
+        public void println()
+        {
+          mappingDetails.append("\n");
         }
+      };
+
+      as.printAlignment(ps);
 
-        return (float) (dim / (1.5d * maxwidth));
+      if (as.maxscore > max)
+      {
+        max = as.maxscore;
+        maxchain = i;
+
+        pdbstart = as.seq2start;
+        pdbend = as.seq2end;
+        seqstart = as.seq1start + sequence.getStart() - 1;
+        seqend = as.seq1end + sequence.getEnd() - 1;
+      }
+
+      mappingDetails.append("\nPDB start/end " + pdbstart + " " + pdbend);
+      mappingDetails.append("\nSEQ start/end " + seqstart + " " + seqend);
     }
 
-    public void findCentre() {
-        float xtot = 0;
-        float ytot = 0;
-        float ztot = 0;
+    mainchain = pdb.chains.elementAt(maxchain);
+
+    mainchain.pdbstart = pdbstart;
+    mainchain.pdbend = pdbend;
+    mainchain.seqstart = seqstart;
+    mainchain.seqend = seqend;
+    mainchain.isVisible = true;
+
+    this.pdb = pdb;
+    this.prefsize = new Dimension(getSize().width, getSize().height);
+
+    addMouseMotionListener(this);
+    addMouseListener(this);
 
-        int bsize = 0;
+    addKeyListener(new KeyAdapter()
+    {
+      public void keyPressed(KeyEvent evt)
+      {
+        keyPressed(evt);
+      }
+    });
 
-        //Find centre coordinate
-        for (int ii = 0; ii < pdb.chains.size(); ii++) {
-            if (((PDBChain) pdb.chains.elementAt(ii)).isVisible) {
-                Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds;
+    findCentre();
+    findWidth();
 
-                bsize += bonds.size();
+    setupBonds();
 
-                for (int i = 0; i < bonds.size(); i++) {
-                    xtot = xtot + ((Bond) bonds.elementAt(i)).start[0] +
-                        ((Bond) bonds.elementAt(i)).end[0];
+    scale = findScale();
 
-                    ytot = ytot + ((Bond) bonds.elementAt(i)).start[1] +
-                        ((Bond) bonds.elementAt(i)).end[1];
+    ToolTipManager.sharedInstance().registerComponent(this);
+    ToolTipManager.sharedInstance().setInitialDelay(0);
+    ToolTipManager.sharedInstance().setDismissDelay(10000);
+  }
 
-                    ztot = ztot + ((Bond) bonds.elementAt(i)).start[2] +
-                        ((Bond) bonds.elementAt(i)).end[2];
-                }
-            }
-        }
+  Vector<Bond> visiblebonds;
 
-        centre[0] = xtot / (2 * (float) bsize);
-        centre[1] = ytot / (2 * (float) bsize);
-        centre[2] = ztot / (2 * (float) bsize);
-    }
+  void setupBonds()
+  {
+    seqColoursReady = false;
+    // Sort the bonds by z coord
+    visiblebonds = new Vector<Bond>();
 
-    public void paintComponent(Graphics g)
+    for (PDBChain chain : pdb.chains)
     {
-      super.paintComponent(g);
-
-      if(!seqColoursReady)
+      if (chain.isVisible)
       {
-        g.setColor(Color.black);
-        g.setFont(new Font("Verdana", Font.BOLD, 14));
-        g.drawString("Retrieving PDB data....", 20, getHeight()/2);
-        return;
+        for (Bond bond : chain.bonds)
+        {
+          visiblebonds.addElement(bond);
+        }
       }
+    }
+
+    updateSeqColours();
+    seqColoursReady = true;
+    redrawneeded = true;
+    repaint();
+  }
 
+  public void findWidth()
+  {
+    float[] max = new float[3];
+    float[] min = new float[3];
 
-        //Only create the image at the beginning -
-        //this saves much memory usage
-        if ((img == null)
-            || (prefsize.width != getWidth())
-            || (prefsize.height != getHeight()))
+    max[0] = (float) -1e30;
+    max[1] = (float) -1e30;
+    max[2] = (float) -1e30;
 
+    min[0] = (float) 1e30;
+    min[1] = (float) 1e30;
+    min[2] = (float) 1e30;
+
+    for (PDBChain chain : pdb.chains)
+    {
+      if (chain.isVisible)
       {
-            prefsize.width = getWidth();
-            prefsize.height = getHeight();
+        for (Bond tmp : chain.bonds)
+        {
+          if (tmp.start[0] >= max[0])
+          {
+            max[0] = tmp.start[0];
+          }
 
-            scale = findScale();
-            img = createImage(prefsize.width, prefsize.height);
-            ig = img.getGraphics();
-            Graphics2D ig2 = (Graphics2D) ig;
+          if (tmp.start[1] >= max[1])
+          {
+            max[1] = tmp.start[1];
+          }
 
-            ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
-                                 RenderingHints.VALUE_ANTIALIAS_ON);
+          if (tmp.start[2] >= max[2])
+          {
+            max[2] = tmp.start[2];
+          }
 
-            redrawneeded = true;
-        }
+          if (tmp.start[0] <= min[0])
+          {
+            min[0] = tmp.start[0];
+          }
 
+          if (tmp.start[1] <= min[1])
+          {
+            min[1] = tmp.start[1];
+          }
 
-        if (redrawneeded)
-        {
-          drawAll(ig, prefsize.width, prefsize.height);
-          redrawneeded = false;
+          if (tmp.start[2] <= min[2])
+          {
+            min[2] = tmp.start[2];
+          }
+
+          if (tmp.end[0] >= max[0])
+          {
+            max[0] = tmp.end[0];
+          }
+
+          if (tmp.end[1] >= max[1])
+          {
+            max[1] = tmp.end[1];
+          }
+
+          if (tmp.end[2] >= max[2])
+          {
+            max[2] = tmp.end[2];
+          }
+
+          if (tmp.end[0] <= min[0])
+          {
+            min[0] = tmp.end[0];
+          }
+
+          if (tmp.end[1] <= min[1])
+          {
+            min[1] = tmp.end[1];
+          }
+
+          if (tmp.end[2] <= min[2])
+          {
+            min[2] = tmp.end[2];
+          }
         }
+      }
+    }
+    /*
+     * System.out.println("xmax " + max[0] + " min " + min[0]);
+     * System.out.println("ymax " + max[1] + " min " + min[1]);
+     * System.out.println("zmax " + max[2] + " min " + min[2]);
+     */
+
+    width[0] = Math.abs(max[0] - min[0]);
+    width[1] = Math.abs(max[1] - min[1]);
+    width[2] = Math.abs(max[2] - min[2]);
 
-        g.drawImage(img, 0, 0, this);
+    maxwidth = width[0];
 
-        pdbAction = false;
+    if (width[1] > width[0])
+    {
+      maxwidth = width[1];
     }
 
-    public void drawAll(Graphics g, int width, int height)
+    if (width[2] > width[1])
     {
-      g.setColor(backgroundColour);
-      g.fillRect(0, 0, width, height);
-      drawScene(g);
-      drawLabels(g);
+      maxwidth = width[2];
     }
 
+    // System.out.println("Maxwidth = " + maxwidth);
+  }
 
-    public void updateSeqColours()
+  public float findScale()
+  {
+    int dim;
+    int width;
+    int height;
+
+    if (getWidth() != 0)
     {
-      if(pdbAction)
-      {
-        return;
-      }
+      width = getWidth();
+      height = getHeight();
+    }
+    else
+    {
+      width = prefsize.width;
+      height = prefsize.height;
+    }
+
+    if (width < height)
+    {
+      dim = width;
+    }
+    else
+    {
+      dim = height;
+    }
+
+    return (float) (dim / (1.5d * maxwidth));
+  }
+
+  public void findCentre()
+  {
+    float xtot = 0;
+    float ytot = 0;
+    float ztot = 0;
 
-     // System.out.println("update seq colours");
-      if(bysequence && pdb!=null)
+    int bsize = 0;
+
+    // Find centre coordinate
+    for (PDBChain chain : pdb.chains)
+    {
+      if (chain.isVisible)
       {
-        for (int ii = 0; ii < pdb.chains.size(); ii++)
+        bsize += chain.bonds.size();
+
+        for (Bond bond : chain.bonds)
         {
-          colourBySequence( (PDBChain) pdb.chains.elementAt(ii));
+          xtot = xtot + bond.start[0] + bond.end[0];
+          ytot = ytot + bond.start[1] + bond.end[1];
+          ztot = ztot + bond.start[2] + bond.end[2];
         }
       }
+    }
 
-      redrawneeded=true;
-      repaint();
+    centre[0] = xtot / (2 * (float) bsize);
+    centre[1] = ytot / (2 * (float) bsize);
+    centre[2] = ztot / (2 * (float) bsize);
+  }
+
+  public void paintComponent(Graphics g)
+  {
+    super.paintComponent(g);
+
+    if (!seqColoursReady || errorMessage != null)
+    {
+      g.setColor(Color.black);
+      g.setFont(new Font("Verdana", Font.BOLD, 14));
+      g.drawString(errorMessage == null ? "Retrieving PDB data...."
+              : errorMessage, 20, getHeight() / 2);
+      return;
     }
 
-    int findTrueIndex(int pos)
+    // Only create the image at the beginning -
+    // this saves much memory usage
+    if ((img == null) || (prefsize.width != getWidth())
+            || (prefsize.height != getHeight()))
+
     {
-      // returns the alignment position for a residue
-      int j = sequence.getStart(); // first position in PDB atom coordinate sequence
-      int i = 0;
+      prefsize.width = getWidth();
+      prefsize.height = getHeight();
 
-      while ( (i < sequence.getLength()) && (j <= pos+1))
-      {
-        if (!jalview.util.Comparison.isGap(sequence.getCharAt(i)))
-        {
-          j++;
-        }
+      scale = findScale();
+      img = createImage(prefsize.width, prefsize.height);
+      ig = img.getGraphics();
+      Graphics2D ig2 = (Graphics2D) ig;
 
-        i++;
-      }
+      ig2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+              RenderingHints.VALUE_ANTIALIAS_ON);
 
-      if(i>1)
-         i--;
+      redrawneeded = true;
+    }
 
-      if (j < pos)
-      {
-        return sequence.getEnd() + 1;
-      }
-      else
-      {
-        return i;
-      }
+    if (redrawneeded)
+    {
+      drawAll(ig, prefsize.width, prefsize.height);
+      redrawneeded = false;
     }
 
-    // This method has been taken out of PDBChain to allow
-    // Applet and Application specific sequence renderers to be used
-    void colourBySequence(PDBChain chain)
+    g.drawImage(img, 0, 0, this);
+
+    pdbAction = false;
+  }
+
+  public void drawAll(Graphics g, int width, int height)
+  {
+    g.setColor(backgroundColour);
+    g.fillRect(0, 0, width, height);
+    drawScene(g);
+    drawLabels(g);
+  }
+
+  public void updateSeqColours()
+  {
+    if (pdbAction)
     {
-     // System.out.println("colour by seq");
-     boolean showFeatures = false;
-     if(seqcanvas.getViewport().getShowSequenceFeatures())
-     {
-       showFeatures = true;
-       if (fr == null)
-         fr = new jalview.gui.FeatureRenderer(seqcanvas.getViewport());
+      return;
+    }
 
-       fr.transferSettings( seqcanvas.getFeatureRenderer() );
-     }
+    colourBySequence();
 
-      Bond tmp;
-      for (int i = 0; i < chain.bonds.size(); i++)
-      {
-        tmp = (Bond) chain.bonds.elementAt(i);
+    redrawneeded = true;
+    repaint();
+  }
 
-        if(chain!=mainchain)
-          continue;
+  // This method has been taken out of PDBChain to allow
+  // Applet and Application specific sequence renderers to be used
+  void colourBySequence()
+  {
+    SequenceRenderer sr = new SequenceRenderer(ap.av);
 
-        //if ( (tmp.at1.resNumber >= ( (chain.offset + chain.pdbstart) - 1)) &&
-        //    (tmp.at1.resNumber <= ( (chain.offset + chain.pdbend) - 1)))
-        {
-            int index = findTrueIndex(tmp.at1.alignmentMapping);
-                //sequence.findIndex(tmp.at1.alignmentMapping);
-            if (index != -1)
-            {
-              tmp.startCol = seqcanvas.getSequenceRenderer().
-                  getResidueBoxColour( sequence, index);
+    StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
 
-              if(showFeatures)
-                tmp.startCol = fr.findFeatureColour(tmp.startCol, sequence, index);
+    boolean showFeatures = false;
+    if (ap.av.isShowSequenceFeatures())
+    {
+      if (fr == null)
+      {
+        fr = new FeatureRenderer(ap);
+      }
 
-              if(tmp.startCol==null)
-                tmp.startCol = Color.white;
-            }
-        }
+      fr.transferSettings(ap.alignFrame.getFeatureRenderer());
+
+      showFeatures = true;
+    }
+
+    PDBChain chain;
+    if (bysequence && pdb != null)
+    {
+      for (int ii = 0; ii < pdb.chains.size(); ii++)
+      {
+        chain = pdb.chains.elementAt(ii);
 
-        //if ( (tmp.at2.resNumber >= ( (chain.offset + chain.pdbstart) - 1)) &&
-        //    (tmp.at2.resNumber <= ( (chain.pdbend + chain.offset) - 1)))
+        for (int i = 0; i < chain.bonds.size(); i++)
         {
+          Bond tmp = chain.bonds.elementAt(i);
+          tmp.startCol = Color.lightGray;
+          tmp.endCol = Color.lightGray;
+          if (chain != mainchain)
+          {
+            continue;
+          }
 
-            int index =  findTrueIndex(tmp.at2.alignmentMapping);
-                //sequence.findIndex( tmp.at2.alignmentMapping );
-            if (index != -1)
+          for (int s = 0; s < sequence.length; s++)
+          {
+            for (int m = 0; m < mapping.length; m++)
             {
-              tmp.endCol = seqcanvas.getSequenceRenderer().
-                  getResidueBoxColour( sequence, index);
-
-              if(showFeatures)
-                tmp.endCol = fr.findFeatureColour(tmp.endCol, sequence, index);
+              if (mapping[m].getSequence() == sequence[s])
+              {
+                int pos = mapping[m].getSeqPos(tmp.at1.resNumber) - 1;
+                if (pos > 0)
+                {
+                  pos = sequence[s].findIndex(pos);
+                  tmp.startCol = sr.getResidueBoxColour(sequence[s], pos);
+                  if (showFeatures)
+                  {
+                    tmp.startCol = fr.findFeatureColour(tmp.startCol,
+                            sequence[s], pos);
+                  }
+                }
+                pos = mapping[m].getSeqPos(tmp.at2.resNumber) - 1;
+                if (pos > 0)
+                {
+                  pos = sequence[s].findIndex(pos);
+                  tmp.endCol = sr.getResidueBoxColour(sequence[s], pos);
+                  if (showFeatures)
+                  {
+                    tmp.endCol = fr.findFeatureColour(tmp.endCol,
+                            sequence[s], pos);
+                  }
+                }
 
-              if(tmp.endCol==null)
-                tmp.endCol = Color.white;
+              }
             }
+          }
         }
       }
     }
+  }
 
+  Zsort zsort;
 
-    Zsort zsort;
-    public void drawScene(Graphics g)
+  public void drawScene(Graphics g)
+  {
+    if (zbuffer)
     {
-      if (zbuffer)
+      if (zsort == null)
       {
-        if (zsort == null)
-          zsort = new Zsort();
-
-        zsort.Zsort(visiblebonds);
+        zsort = new Zsort();
       }
 
-      Bond tmpBond = null;
-      for (int i = 0; i < visiblebonds.size(); i++)
-      {
-        tmpBond = (Bond) visiblebonds.elementAt(i);
+      zsort.sort(visiblebonds);
+    }
 
-        xstart = (int) ( ( (tmpBond.start[0] - centre[0]) * scale) +
-                        (getWidth() / 2));
-        ystart = (int) ( ( (tmpBond.start[1] - centre[1]) * scale) +
-                        (getHeight() / 2));
+    Bond tmpBond = null;
+    for (int i = 0; i < visiblebonds.size(); i++)
+    {
+      tmpBond = visiblebonds.elementAt(i);
 
-        xend = (int) ( ( (tmpBond.end[0] - centre[0]) * scale) +
-                      (getWidth() / 2));
-        yend = (int) ( ( (tmpBond.end[1] - centre[1]) * scale) +
-                      (getHeight() / 2));
+      xstart = (int) (((tmpBond.start[0] - centre[0]) * scale) + (getWidth() / 2));
+      ystart = (int) (((centre[1] - tmpBond.start[1]) * scale) + (getHeight() / 2));
 
-        xmid = (xend + xstart) / 2;
-        ymid = (yend + ystart) / 2;
-        if (depthcue && !bymolecule)
-        {
-          if (tmpBond.start[2] < (centre[2] - (maxwidth / 6)))
-          {
-
-            g.setColor(tmpBond.startCol.darker().darker());
-            drawLine(g, xstart, ystart, xmid, ymid);
-            g.setColor(tmpBond.endCol.darker().darker());
-            drawLine(g, xmid, ymid, xend, yend);
+      xend = (int) (((tmpBond.end[0] - centre[0]) * scale) + (getWidth() / 2));
+      yend = (int) (((centre[1] - tmpBond.end[1]) * scale) + (getHeight() / 2));
 
-          }
-          else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6)))
-          {
-            g.setColor(tmpBond.startCol.darker());
-            drawLine(g, xstart, ystart, xmid, ymid);
+      xmid = (xend + xstart) / 2;
+      ymid = (yend + ystart) / 2;
+      if (depthcue && !bymolecule)
+      {
+        if (tmpBond.start[2] < (centre[2] - (maxwidth / 6)))
+        {
 
-            g.setColor(tmpBond.endCol.darker());
-            drawLine(g, xmid, ymid, xend, yend);
-          }
-          else
-          {
-            g.setColor(tmpBond.startCol);
-            drawLine(g, xstart, ystart, xmid, ymid);
+          g.setColor(tmpBond.startCol.darker().darker());
+          drawLine(g, xstart, ystart, xmid, ymid);
+          g.setColor(tmpBond.endCol.darker().darker());
+          drawLine(g, xmid, ymid, xend, yend);
 
-            g.setColor(tmpBond.endCol);
-            drawLine(g, xmid, ymid, xend, yend);
-          }
         }
-        else if (depthcue && bymolecule)
+        else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6)))
         {
-          if (tmpBond.start[2] < (centre[2] - (maxwidth / 6)))
-          {
-            g.setColor(Color.green.darker().darker());
-            drawLine(g, xstart, ystart, xend, yend);
-          }
-          else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6)))
-          {
-            g.setColor(Color.green.darker());
-            drawLine(g, xstart, ystart, xend, yend);
-          }
-          else
-          {
-            g.setColor(Color.green);
-            drawLine(g, xstart, ystart, xend, yend);
-          }
+          g.setColor(tmpBond.startCol.darker());
+          drawLine(g, xstart, ystart, xmid, ymid);
+
+          g.setColor(tmpBond.endCol.darker());
+          drawLine(g, xmid, ymid, xend, yend);
         }
-        else if (!depthcue && !bymolecule)
+        else
         {
           g.setColor(tmpBond.startCol);
           drawLine(g, xstart, ystart, xmid, ymid);
+
           g.setColor(tmpBond.endCol);
           drawLine(g, xmid, ymid, xend, yend);
         }
-        else
+      }
+      else if (depthcue && bymolecule)
+      {
+        if (tmpBond.start[2] < (centre[2] - (maxwidth / 6)))
         {
+          g.setColor(Color.green.darker().darker());
           drawLine(g, xstart, ystart, xend, yend);
         }
-
-        if (highlightBond1 != null && highlightBond1 == tmpBond)
+        else if (tmpBond.start[2] < (centre[2] + (maxwidth / 6)))
         {
-          g.setColor(tmpBond.endCol.brighter().brighter().brighter().brighter());
-          drawLine(g, xmid, ymid, xend, yend);
+          g.setColor(Color.green.darker());
+          drawLine(g, xstart, ystart, xend, yend);
         }
-
-        if (highlightBond2 != null && highlightBond2 == tmpBond)
+        else
         {
-          g.setColor(tmpBond.startCol.brighter().brighter().brighter().brighter());
-          drawLine(g, xstart, ystart, xmid, ymid);
+          g.setColor(Color.green);
+          drawLine(g, xstart, ystart, xend, yend);
         }
-
+      }
+      else if (!depthcue && !bymolecule)
+      {
+        g.setColor(tmpBond.startCol);
+        drawLine(g, xstart, ystart, xmid, ymid);
+        g.setColor(tmpBond.endCol);
+        drawLine(g, xmid, ymid, xend, yend);
+      }
+      else
+      {
+        drawLine(g, xstart, ystart, xend, yend);
       }
 
+      if (highlightBond1 != null && highlightBond1 == tmpBond)
+      {
+        g.setColor(tmpBond.endCol.brighter().brighter().brighter()
+                .brighter());
+        drawLine(g, xmid, ymid, xend, yend);
+      }
 
-    }
-
-    public void drawLine(Graphics g, int x1, int y1, int x2, int y2) {
-        if (!wire) {
-            if (((float) Math.abs(y2 - y1) / (float) Math.abs(x2 - x1)) < 0.5) {
-                g.drawLine(x1, y1, x2, y2);
-                g.drawLine(x1 + 1, y1 + 1, x2 + 1, y2 + 1);
-                g.drawLine(x1, y1 - 1, x2, y2 - 1);
-            } else {
-                g.setColor(g.getColor().brighter());
-                g.drawLine(x1, y1, x2, y2);
-                g.drawLine(x1 + 1, y1, x2 + 1, y2);
-                g.drawLine(x1 - 1, y1, x2 - 1, y2);
-            }
-        } else {
-            g.drawLine(x1, y1, x2, y2);
-        }
-    }
+      if (highlightBond2 != null && highlightBond2 == tmpBond)
+      {
+        g.setColor(tmpBond.startCol.brighter().brighter().brighter()
+                .brighter());
+        drawLine(g, xstart, ystart, xmid, ymid);
+      }
 
-    public Dimension minimumsize() {
-        return prefsize;
     }
 
-    public Dimension preferredsize() {
-        return prefsize;
-    }
+  }
 
-    public void keyPressed(KeyEvent evt)
+  public void drawLine(Graphics g, int x1, int y1, int x2, int y2)
+  {
+    if (!wire)
     {
-      if (evt.getKeyCode() == KeyEvent.VK_UP)
+      if (((float) Math.abs(y2 - y1) / (float) Math.abs(x2 - x1)) < 0.5)
       {
-        scale = (float) (scale * 1.1);
-        redrawneeded = true;
-        repaint();
+        g.drawLine(x1, y1, x2, y2);
+        g.drawLine(x1 + 1, y1 + 1, x2 + 1, y2 + 1);
+        g.drawLine(x1, y1 - 1, x2, y2 - 1);
       }
-      else if (evt.getKeyCode() == KeyEvent.VK_DOWN)
+      else
       {
-        scale = (float) (scale * 0.9);
-        redrawneeded = true;
-        repaint();
+        g.setColor(g.getColor().brighter());
+        g.drawLine(x1, y1, x2, y2);
+        g.drawLine(x1 + 1, y1, x2 + 1, y2);
+        g.drawLine(x1 - 1, y1, x2 - 1, y2);
       }
     }
-
-    public void mousePressed(MouseEvent e)
+    else
     {
-        pdbAction = true;
-        Atom fatom = findAtom(e.getX(), e.getY());
-        if(fatom!=null)
-        {
-          fatom.isSelected = !fatom.isSelected;
+      g.drawLine(x1, y1, x2, y2);
+    }
+  }
 
-          redrawneeded = true;
-          repaint();
-          if (foundchain != -1)
-          {
-            PDBChain chain = (PDBChain) pdb.chains.elementAt(foundchain);
-            if (chain == mainchain)
-            {
-              if (fatom.alignmentMapping != -1)
-              {
-                if (highlightRes == null)
-                  highlightRes = new Vector();
+  public Dimension minimumsize()
+  {
+    return prefsize;
+  }
 
-                if (highlightRes.contains(fatom.alignmentMapping+""))
-                  highlightRes.remove(fatom.alignmentMapping + "");
-                else
-                  highlightRes.add(fatom.alignmentMapping + "");
-              }
-            }
-          }
+  public Dimension preferredsize()
+  {
+    return prefsize;
+  }
 
-        }
-        mx = e.getX();
-        my = e.getY();
-        omx = mx;
-        omy = my;
-        dragging = false;
+  public void keyPressed(KeyEvent evt)
+  {
+    if (evt.getKeyCode() == KeyEvent.VK_UP)
+    {
+      scale = (float) (scale * 1.1);
+      redrawneeded = true;
+      repaint();
     }
-
-    public void mouseMoved(MouseEvent e)
+    else if (evt.getKeyCode() == KeyEvent.VK_DOWN)
     {
-      pdbAction = true;
-      if(highlightBond1!=null)
-      {
-        highlightBond1.at2.isSelected = false;
-        highlightBond2.at1.isSelected = false;
-        highlightBond1 = null;
-        highlightBond2 = null;
-      }
+      scale = (float) (scale * 0.9);
+      redrawneeded = true;
+      repaint();
+    }
+  }
 
-        Atom fatom = findAtom(e.getX(), e.getY());
+  public void mousePressed(MouseEvent e)
+  {
+    pdbAction = true;
+    Atom fatom = findAtom(e.getX(), e.getY());
+    if (fatom != null)
+    {
+      fatom.isSelected = !fatom.isSelected;
 
-        PDBChain chain = null;
-        if(foundchain!=-1)
+      redrawneeded = true;
+      repaint();
+      if (foundchain != -1)
+      {
+        PDBChain chain = pdb.chains.elementAt(foundchain);
+        if (chain == mainchain)
         {
-          chain = (PDBChain) pdb.chains.elementAt(foundchain);
-          if(chain == mainchain)
+          if (fatom.alignmentMapping != -1)
           {
-            highlightSeqcanvas( fatom.alignmentMapping );
+            if (highlightRes == null)
+            {
+              highlightRes = new Vector<String>();
+            }
+
+            final String atomString = Integer
+                    .toString(fatom.alignmentMapping);
+            if (highlightRes.contains(atomString))
+            {
+              highlightRes.remove(atomString);
+            }
+            else
+            {
+              highlightRes.add(atomString);
+            }
           }
         }
+      }
 
-        if (fatom != null)
-        {
-            this.setToolTipText(chain.id+":"+ fatom.resNumber+" "+ fatom.resName);
-        } else
-        {
-            highlightSeqcanvas( -1);
-            this.setToolTipText(null);
-        }
     }
+    mx = e.getX();
+    my = e.getY();
+    omx = mx;
+    omy = my;
+    dragging = false;
+  }
 
-
-    void highlightSeqcanvas(int pos)
+  public void mouseMoved(MouseEvent e)
+  {
+    pdbAction = true;
+    if (highlightBond1 != null)
     {
-      SearchResults searchResults = new SearchResults();
-      if(highlightRes!=null)
-      {
-        for (int i = 0; i < highlightRes.size(); i++)
-        {
-          int a = Integer.parseInt(highlightRes.elementAt(
-              i).toString())+1;
+      highlightBond1.at2.isSelected = false;
+      highlightBond2.at1.isSelected = false;
+      highlightBond1 = null;
+      highlightBond2 = null;
+    }
 
-          searchResults.addResult(sequence, a, a);
-        }
-      }
+    Atom fatom = findAtom(e.getX(), e.getY());
 
-      if(pos!=-1)
+    PDBChain chain = null;
+    if (foundchain != -1)
+    {
+      chain = pdb.chains.elementAt(foundchain);
+      if (chain == mainchain)
       {
-        searchResults.addResult(sequence, pos+1, pos+1);
+        mouseOverStructure(fatom.resNumber, chain.id);
       }
+    }
 
-      seqcanvas.highlightSearchResults(searchResults);
+    if (fatom != null)
+    {
+      this.setToolTipText(chain.id + ":" + fatom.resNumber + " "
+              + fatom.resName);
+    }
+    else
+    {
+      mouseOverStructure(-1, chain != null ? chain.id : null);
+      this.setToolTipText(null);
     }
+  }
 
+  public void mouseClicked(MouseEvent e)
+  {
+  }
 
-    public void mouseClicked(MouseEvent e)  { }
+  public void mouseEntered(MouseEvent e)
+  {
+  }
+
+  public void mouseExited(MouseEvent e)
+  {
+  }
+
+  public void mouseDragged(MouseEvent evt)
+  {
+    int x = evt.getX();
+    int y = evt.getY();
+    mx = x;
+    my = y;
 
-    public void mouseEntered(MouseEvent e) {  }
+    MCMatrix objmat = new MCMatrix(3, 3);
+    objmat.setIdentity();
 
-    public void mouseExited(MouseEvent e) { }
+    if ((evt.getModifiers() & Event.META_MASK) != 0)
+    {
+      objmat.rotatez(((mx - omx)));
+    }
+    else
+    {
+      objmat.rotatex(((my - omy)));
+      objmat.rotatey(((omx - mx)));
+    }
 
-    public void mouseDragged(MouseEvent evt)
+    // Alter the bonds
+    for (PDBChain chain : pdb.chains)
     {
-        int x = evt.getX();
-        int y = evt.getY();
-        mx = x;
-        my = y;
+      for (Bond tmpBond : chain.bonds)
+      {
+        // Translate the bond so the centre is 0,0,0
+        tmpBond.translate(-centre[0], -centre[1], -centre[2]);
 
+        // Now apply the rotation matrix
+        tmpBond.start = objmat.vectorMultiply(tmpBond.start);
+        tmpBond.end = objmat.vectorMultiply(tmpBond.end);
 
-        MCMatrix objmat = new MCMatrix(3, 3);
-        objmat.setIdentity();
+        // Now translate back again
+        tmpBond.translate(centre[0], centre[1], centre[2]);
+      }
+    }
 
-        if ((evt.getModifiers() & Event.META_MASK) != 0) {
-            objmat.rotatez((float) ((mx - omx)));
-        } else {
-            objmat.rotatex((float) ((my - omy)));
-            objmat.rotatey((float) ((omx - mx)));
-        }
+    objmat = null;
 
-        //Alter the bonds
-        for (int ii = 0; ii < pdb.chains.size(); ii++) {
-            Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds;
+    omx = mx;
+    omy = my;
 
-            for (int i = 0; i < bonds.size(); i++) {
-                Bond tmpBond = (Bond) bonds.elementAt(i);
+    dragging = true;
 
-                //Translate the bond so the centre is 0,0,0
-                tmpBond.translate(-centre[0], -centre[1], -centre[2]);
+    redrawneeded = true;
 
-                //Now apply the rotation matrix
-                tmpBond.start = objmat.vectorMultiply(tmpBond.start);
-                tmpBond.end = objmat.vectorMultiply(tmpBond.end);
+    repaint();
+  }
 
-                //Now translate back again
-                tmpBond.translate(centre[0], centre[1], centre[2]);
-            }
-        }
+  public void mouseReleased(MouseEvent evt)
+  {
+    dragging = false;
+    return;
+  }
 
-        objmat = null;
+  void drawLabels(Graphics g)
+  {
 
-        omx = mx;
-        omy = my;
+    for (PDBChain chain : pdb.chains)
+    {
+      if (chain.isVisible)
+      {
+        for (Bond tmpBond : chain.bonds)
+        {
+          if (tmpBond.at1.isSelected)
+          {
+            labelAtom(g, tmpBond, 1);
+          }
 
-        dragging = true;
+          if (tmpBond.at2.isSelected)
+          {
+            labelAtom(g, tmpBond, 2);
+          }
+        }
+      }
+    }
+  }
 
-        redrawneeded = true;
+  public void labelAtom(Graphics g, Bond b, int n)
+  {
+    g.setFont(font);
+    g.setColor(Color.red);
+    if (n == 1)
+    {
+      int xstart = (int) (((b.start[0] - centre[0]) * scale) + (getWidth() / 2));
+      int ystart = (int) (((centre[1] - b.start[1]) * scale) + (getHeight() / 2));
 
-        repaint();
+      g.drawString(b.at1.resName + "-" + b.at1.resNumber, xstart, ystart);
     }
 
-    public void mouseReleased(MouseEvent evt)
+    if (n == 2)
     {
-        dragging = false;
-        return;
+      int xstart = (int) (((b.end[0] - centre[0]) * scale) + (getWidth() / 2));
+      int ystart = (int) (((centre[1] - b.end[1]) * scale) + (getHeight() / 2));
+
+      g.drawString(b.at2.resName + "-" + b.at2.resNumber, xstart, ystart);
     }
+  }
 
-    void drawLabels(Graphics g) {
+  int foundchain = -1;
 
-        for (int ii = 0; ii < pdb.chains.size(); ii++)
-        {
-            PDBChain chain = (PDBChain) pdb.chains.elementAt(ii);
+  public Atom findAtom(int x, int y)
+  {
+    Atom fatom = null;
 
-            if (chain.isVisible)
-            {
-              Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds;
+    foundchain = -1;
 
-              for (int i = 0; i < bonds.size(); i++)
-              {
-                  Bond tmpBond = (Bond) bonds.elementAt(i);
+    for (int ii = 0; ii < pdb.chains.size(); ii++)
+    {
+      PDBChain chain = pdb.chains.elementAt(ii);
+      int truex;
+      Bond tmpBond = null;
 
-                  if (tmpBond.at1.isSelected)
-                  {
-                      labelAtom(g, tmpBond, 1);
-                  }
+      if (chain.isVisible)
+      {
+        for (Bond bond : chain.bonds)
+        {
+          tmpBond = bond;
 
-                  if (tmpBond.at2.isSelected)
-                  {
+          truex = (int) (((tmpBond.start[0] - centre[0]) * scale) + (getWidth() / 2));
 
-                      labelAtom(g, tmpBond, 2);
-                  }
-                }
+          if (Math.abs(truex - x) <= 2)
+          {
+            int truey = (int) (((centre[1] - tmpBond.start[1]) * scale) + (getHeight() / 2));
+
+            if (Math.abs(truey - y) <= 2)
+            {
+              fatom = tmpBond.at1;
+              foundchain = ii;
+              break;
             }
+          }
         }
-    }
 
-    public void labelAtom(Graphics g, Bond b, int n) {
-        g.setFont(font);
-        g.setColor(Color.red);
-        if (n == 1)
+        // Still here? Maybe its the last bond
+
+        truex = (int) (((tmpBond.end[0] - centre[0]) * scale) + (getWidth() / 2));
+
+        if (Math.abs(truex - x) <= 2)
         {
-            int xstart = (int) (((b.start[0] - centre[0]) * scale) +
-                (getWidth() / 2));
-            int ystart = (int) (((b.start[1] - centre[1]) * scale) +
-                (getHeight() / 2));
+          int truey = (int) (((tmpBond.end[1] - centre[1]) * scale) + (getHeight() / 2));
 
-            g.drawString(b.at1.resName + "-" + b.at1.resNumber, xstart, ystart);
+          if (Math.abs(truey - y) <= 2)
+          {
+            fatom = tmpBond.at2;
+            foundchain = ii;
+            break;
+          }
         }
 
-        if (n == 2) {
-            int xstart = (int) (((b.end[0] - centre[0]) * scale) +
-                (getWidth() / 2));
-            int ystart = (int) (((b.end[1] - centre[1]) * scale) +
-                (getHeight() / 2));
+      }
 
-            g.drawString(b.at2.resName + "-" + b.at2.resNumber, xstart, ystart);
-        }
+      if (fatom != null) // )&& chain.ds != null)
+      { // dead code? value of chain is either overwritten or discarded
+        chain = pdb.chains.elementAt(foundchain);
+      }
     }
 
-    int foundchain = -1;
-    public Atom findAtom(int x, int y) {
-        Atom fatom = null;
+    return fatom;
+  }
+
+  Bond highlightBond1, highlightBond2;
+
+  public void highlightRes(int ii)
+  {
+    if (!seqColoursReady)
+    {
+      return;
+    }
 
-        foundchain = -1;
+    if (highlightRes != null && highlightRes.contains((ii - 1) + ""))
+    {
+      return;
+    }
 
-        for (int ii = 0; ii < pdb.chains.size(); ii++)
+    int index = -1;
+    Bond tmpBond;
+    for (index = 0; index < mainchain.bonds.size(); index++)
+    {
+      tmpBond = mainchain.bonds.elementAt(index);
+      if (tmpBond.at1.alignmentMapping == ii - 1)
+      {
+        if (highlightBond1 != null)
         {
-            PDBChain chain = (PDBChain) pdb.chains.elementAt(ii);
-            int truex;
-            Bond tmpBond=null;
+          highlightBond1.at2.isSelected = false;
+        }
 
-            if (chain.isVisible)
-            {
-                Vector bonds = ((PDBChain) pdb.chains.elementAt(ii)).bonds;
+        if (highlightBond2 != null)
+        {
+          highlightBond2.at1.isSelected = false;
+        }
 
-                for (int i = 0; i < bonds.size(); i++)
-                {
-                    tmpBond = (Bond) bonds.elementAt(i);
-
-                    truex = (int) (((tmpBond.start[0] - centre[0]) * scale) +
-                        (getWidth() / 2));
-
-                    if (Math.abs(truex - x) <= 2)
-                    {
-                        int truey = (int) (((tmpBond.start[1] - centre[1]) * scale) +
-                            (getHeight() / 2));
-
-                        if (Math.abs(truey - y) <= 2)
-                        {
-                            fatom = tmpBond.at1;
-                            foundchain = ii;
-                            break;
-                        }
-                    }
-                }
+        highlightBond1 = null;
+        highlightBond2 = null;
 
-                // Still here? Maybe its the last bond
+        if (index > 0)
+        {
+          highlightBond1 = mainchain.bonds.elementAt(index - 1);
+          highlightBond1.at2.isSelected = true;
+        }
 
-                truex = (int) ( ( (tmpBond.end[0] - centre[0]) * scale) +
-                               (getWidth() / 2));
+        if (index != mainchain.bonds.size())
+        {
+          highlightBond2 = mainchain.bonds.elementAt(index);
+          highlightBond2.at1.isSelected = true;
+        }
 
-                if (Math.abs(truex - x) <= 2)
-                {
-                  int truey = (int) ( ( (tmpBond.end[1] - centre[1]) * scale) +
-                                     (getHeight() / 2));
+        break;
+      }
+    }
 
-                  if (Math.abs(truey - y) <= 2)
-                  {
-                    fatom = tmpBond.at2;
-                    foundchain = ii;
-                    break;
-                  }
-                }
+    redrawneeded = true;
+    repaint();
+  }
 
-            }
+  public void setAllchainsVisible(boolean b)
+  {
+    for (int ii = 0; ii < pdb.chains.size(); ii++)
+    {
+      PDBChain chain = pdb.chains.elementAt(ii);
+      chain.isVisible = b;
+    }
+    mainchain.isVisible = true;
+    findCentre();
+    setupBonds();
+  }
 
-            if (fatom != null) //)&& chain.ds != null)
-             {
-                chain = (PDBChain) pdb.chains.elementAt(foundchain);
-            }
-        }
+  // ////////////////////////////////
+  // /StructureListener
+  public String[] getPdbFile()
+  {
+    return new String[] { pdbentry.getFile() };
+  }
 
-        return fatom;
+  String lastMessage;
+
+  public void mouseOverStructure(int pdbResNum, String chain)
+  {
+    if (lastMessage == null || !lastMessage.equals(pdbResNum + chain))
+    {
+      ssm.mouseOverStructure(pdbResNum, chain, pdbentry.getFile());
     }
 
-   Bond highlightBond1, highlightBond2;
-   public void highlightRes(int ii)
+    lastMessage = pdbResNum + chain;
+  }
+
+  StringBuffer resetLastRes = new StringBuffer();
+
+  StringBuffer eval = new StringBuffer();
+
+  /**
+   * Highlight the specified atoms in the structure.
+   * 
+   * @param atoms
+   */
+  @Override
+  public void highlightAtoms(List<AtomSpec> atoms)
   {
-    if( !seqColoursReady )
+    if (!seqColoursReady)
+    {
       return;
+    }
 
-    if (highlightRes != null
-        && highlightRes.contains((ii-1) + ""))
+    for (AtomSpec atom : atoms)
     {
-      return;
+      int atomIndex = atom.getAtomIndex();
+      if (highlightRes != null
+              && highlightRes.contains((atomIndex - 1) + ""))
+      {
+        continue;
+      }
+
+      highlightAtom(atomIndex);
     }
 
+    redrawneeded = true;
+    repaint();
+  }
+
+  /**
+   * Highlight the atom at the specified index.
+   * 
+   * @param atomIndex
+   */
+  protected void highlightAtom(int atomIndex)
+  {
     int index = -1;
     Bond tmpBond;
-    for(index=0; index<mainchain.bonds.size(); index++)
+    for (index = 0; index < mainchain.bonds.size(); index++)
     {
-      tmpBond = (Bond) mainchain.bonds.elementAt(index);
-      if (tmpBond.at1.alignmentMapping == ii - 1)
+      tmpBond = mainchain.bonds.elementAt(index);
+      if (tmpBond.at1.atomIndex == atomIndex)
       {
         if (highlightBond1 != null)
+        {
           highlightBond1.at2.isSelected = false;
+        }
 
         if (highlightBond2 != null)
+        {
           highlightBond2.at1.isSelected = false;
+        }
 
         highlightBond1 = null;
         highlightBond2 = null;
 
         if (index > 0)
         {
-          highlightBond1 = (Bond) mainchain.bonds.elementAt(index - 1);
+          highlightBond1 = mainchain.bonds.elementAt(index - 1);
           highlightBond1.at2.isSelected = true;
         }
 
         if (index != mainchain.bonds.size())
         {
-          highlightBond2 = (Bond) mainchain.bonds.elementAt(index);
+          highlightBond2 = mainchain.bonds.elementAt(index);
           highlightBond2.at1.isSelected = true;
         }
 
         break;
       }
     }
+  }
 
+  public Color getColour(int atomIndex, int pdbResNum, String chain,
+          String pdbfile)
+  {
+    return Color.white;
+    // if (!pdbfile.equals(pdbentry.getFile()))
+    // return null;
+
+    // return new Color(viewer.getAtomArgb(atomIndex));
+  }
+
+  public void updateColours(Object source)
+  {
+    colourBySequence();
     redrawneeded = true;
     repaint();
   }
 
-    public void setAllchainsVisible(boolean b)
+  @Override
+  public void releaseReferences(Object svl)
+  {
+    // TODO Auto-generated method stub
+
+  }
+
+  @Override
+  public boolean isListeningFor(SequenceI seq)
+  {
+    if (sequence != null)
     {
-      for (int ii = 0; ii < pdb.chains.size(); ii++)
+      for (SequenceI s : sequence)
       {
-        PDBChain chain = (PDBChain) pdb.chains.elementAt(ii);
-        chain.isVisible = b;
+        if (s == seq)
+        {
+          return true;
+        }
       }
-      mainchain.isVisible = true;
-      findCentre();
-      setupBonds();
     }
+    return false;
+  }
 }