call to release any explicit event handler references
[jalview.git] / src / jalview / ext / jmol / JalviewJmolBinding.java
index 31f91ee..67327c1 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
+ * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
  * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
  * 
  * This file is part of Jalview.
@@ -26,6 +26,7 @@ import java.awt.event.*;
 
 import javax.swing.JPanel;
 
+import jalview.api.AlignmentViewPanel;
 import jalview.api.FeatureRenderer;
 import jalview.api.SequenceRenderer;
 import jalview.api.SequenceStructureBinding;
@@ -43,7 +44,8 @@ import org.jmol.viewer.Viewer;
 import jalview.schemes.*;
 
 public abstract class JalviewJmolBinding implements StructureListener,
-        JmolStatusListener, SequenceStructureBinding, JmolSelectionListener
+        JmolStatusListener, SequenceStructureBinding,
+        JmolSelectionListener, ComponentListener
 
 {
   /**
@@ -80,6 +82,8 @@ public abstract class JalviewJmolBinding implements StructureListener,
 
   public Vector chainNames;
 
+  Hashtable chainFile;
+
   /**
    * array of target chains for seuqences - tied to pdbentry and sequence[]
    */
@@ -113,7 +117,7 @@ public abstract class JalviewJmolBinding implements StructureListener,
   public PDBEntry[] pdbentry;
 
   /**
-   * datasource protocol for access to PDBEntry
+   * datasource protocol for access to PDBEntrylatest
    */
   String protocol = null;
 
@@ -210,8 +214,9 @@ public abstract class JalviewJmolBinding implements StructureListener,
         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(":" + lbl.substring(mlength + 1) + " /"
-              + getModelNum(lbl.substring(0, mlength)) + " or ");
+              + (1 + getModelNum((String) chainFile.get(lbl))) + " or ");
     }
     if (cmd.length() > 0)
       cmd.setLength(cmd.length() - 4);
@@ -229,8 +234,15 @@ public abstract class JalviewJmolBinding implements StructureListener,
     viewer.setJmolStatusListener(null);
     lastCommand = null;
     viewer = null;
+    releaseUIResources();
   }
 
+  /**
+   * called by JalviewJmolbinding after closeViewer is called - release any
+   * resources and references so they can be garbage collected.
+   */
+  protected abstract void releaseUIResources();
+
   public void colourByChain()
   {
     colourBySequence = false;
@@ -282,198 +294,242 @@ public abstract class JalviewJmolBinding implements StructureListener,
   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)
+  {
     String[] files = getPdbFile();
-    if (refStructure >= files.length)
-    {
-      System.err.println("Invalid reference structure value "
-              + refStructure);
-      refStructure = -1;
-    }
-    if (refStructure < -1)
+    StringBuffer selectioncom = new StringBuffer();
+    assert (_alignment.length == _refStructure.length && _alignment.length != _hiddenCols.length);
+    // union of all aligned positions are collected together.
+    for (int a = 0; a < _alignment.length; a++)
     {
-      refStructure = -1;
-    }
-    StringBuffer command = new StringBuffer(), selectioncom = new StringBuffer();
+      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 "
+                + refStructure);
+        refStructure = -1;
+      }
+      if (refStructure < -1)
+      {
+        refStructure = -1;
+      }
+      StringBuffer command = new StringBuffer();
 
-    boolean matched[] = new boolean[alignment.getWidth()];
-    for (int m = 0; m < matched.length; m++)
-    {
+      boolean matched[] = new boolean[alignment.getWidth()];
+      for (int m = 0; m < matched.length; m++)
+      {
 
-      matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
-    }
+        matched[m] = (hiddenCols != null) ? hiddenCols.isVisible(m) : true;
+      }
 
-    int commonrpositions[][] = new int[files.length][alignment.getWidth()];
-    String isel[] = new String[files.length];
-    // reference structure - all others are superposed in it
-    String[] targetC = new String[files.length];
-    for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
-    {
-      StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
+      int commonrpositions[][] = new int[files.length][alignment.getWidth()];
+      String isel[] = new String[files.length];
+      // reference structure - all others are superposed in it
+      String[] targetC = new String[files.length];
+      String[] chainNames = new String[files.length];
+      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+      {
+        StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
 
-      if (mapping == null || mapping.length < 1)
-        continue;
+        if (mapping == null || mapping.length < 1)
+          continue;
 
-      int lastPos = -1;
-      for (int s = 0; s < sequence[pdbfnum].length; s++)
-      {
-        for (int sp, m = 0; m < mapping.length; m++)
+        int lastPos = -1;
+        for (int s = 0; s < sequence[pdbfnum].length; s++)
         {
-          if (mapping[m].getSequence() == sequence[pdbfnum][s]
-                  && (sp = alignment.findIndex(sequence[pdbfnum][s])) > -1)
+          for (int sp, m = 0; m < mapping.length; m++)
           {
-            if (refStructure == -1)
+            if (mapping[m].getSequence() == sequence[pdbfnum][s]
+                    && (sp = alignment.findIndex(sequence[pdbfnum][s])) > -1)
             {
-              refStructure = pdbfnum;
-            }
-            SequenceI asp = alignment.getSequenceAt(sp);
-            for (int r = 0; r < matched.length; r++)
-            {
-              if (!matched[r])
+              if (refStructure == -1)
               {
-                continue;
+                refStructure = pdbfnum;
               }
-              matched[r] = false; // assume this is not a good site
-              if (r >= asp.getLength())
+              SequenceI asp = alignment.getSequenceAt(sp);
+              for (int r = 0; r < matched.length; r++)
               {
-                continue;
-              }
+                if (!matched[r])
+                {
+                  continue;
+                }
+                matched[r] = false; // assume this is not a good site
+                if (r >= asp.getLength())
+                {
+                  continue;
+                }
 
-              if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
+                if (jalview.util.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 + 1) + ".1";
+              if (mapping[m].getChain() == null
+                      || mapping[m].getChain().trim().length() == 0)
               {
-                // no mapping to gaps in sequence
-                continue;
+                targetC[pdbfnum] = "";
               }
-              int t = asp.findPosition(r); // sequence position
-              int apos = mapping[m].getAtomNum(t);
-              int pos = mapping[m].getPDBResNum(t);
-
-              if (pos < 1 || pos == lastPos)
+              else
               {
-                // can't align unmapped sequence
-                continue;
+                targetC[pdbfnum] = ":" + mapping[m].getChain();
               }
-              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 + 1) + ".1";
-            if (mapping[m].getChain() == null
-                    || mapping[m].getChain().trim().length() == 0)
-            {
-              targetC[pdbfnum] = "";
+              chainNames[pdbfnum] = mapping[m].getPdbId()
+                      + targetC[pdbfnum];
+              // move on to next pdb file
+              s = sequence[pdbfnum].length;
+              break;
             }
-            else
-            {
-              targetC[pdbfnum] = ":" + mapping[m].getChain();
-            }
-            // move on to next pdb file
-            s = sequence[pdbfnum].length;
-            break;
           }
         }
       }
-    }
-    String[] selcom = new String[files.length];
-    int nmatched = 0;
-    // generate select statements to select regions to superimpose structures
-    {
-      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+      String[] selcom = new String[files.length];
+      int nmatched = 0;
+      // generate select statements to select regions to superimpose structures
       {
-        String chainCd = targetC[pdbfnum];
-        int lpos = -1;
-        boolean run = false;
-        StringBuffer molsel = new StringBuffer();
-        molsel.append("{");
-        for (int r = 0; r < matched.length; r++)
+        for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
         {
-          if (matched[r])
+          String chainCd = targetC[pdbfnum];
+          int lpos = -1;
+          boolean run = false;
+          StringBuffer molsel = new StringBuffer();
+          molsel.append("{");
+          for (int r = 0; r < matched.length; r++)
           {
-            if (pdbfnum == 0)
-            {
-              nmatched++;
-            }
-            if (lpos != commonrpositions[pdbfnum][r] - 1)
+            if (matched[r])
             {
-              // discontinuity
-              if (lpos != -1)
+              if (pdbfnum == 0)
               {
-                molsel.append(lpos);
-                molsel.append(chainCd);
-                // molsel.append("} {");
-                molsel.append("|");
+                nmatched++;
               }
-            }
-            else
-            {
-              // continuous run - and lpos >-1
-              if (!run)
+              if (lpos != commonrpositions[pdbfnum][r] - 1)
               {
-                // at the beginning, so add dash
-                molsel.append(lpos);
-                molsel.append("-");
+                // discontinuity
+                if (lpos != -1)
+                {
+                  molsel.append(lpos);
+                  molsel.append(chainCd);
+                  // molsel.append("} {");
+                  molsel.append("|");
+                }
               }
-              run = true;
+              else
+              {
+                // continuous run - and lpos >-1
+                if (!run)
+                {
+                  // at the beginning, so add dash
+                  molsel.append(lpos);
+                  molsel.append("-");
+                }
+                run = true;
+              }
+              lpos = commonrpositions[pdbfnum][r];
+              // molsel.append(lpos);
             }
-            lpos = commonrpositions[pdbfnum][r];
-            // molsel.append(lpos);
+          }
+          // add final selection phrase
+          if (lpos != -1)
+          {
+            molsel.append(lpos);
+            molsel.append(chainCd);
+            molsel.append("}");
+          }
+          selcom[pdbfnum] = molsel.toString();
+          selectioncom.append("((");
+          selectioncom.append(selcom[pdbfnum].substring(1,
+                  selcom[pdbfnum].length() - 1));
+          selectioncom.append(" )& ");
+          selectioncom.append(pdbfnum + 1);
+          selectioncom.append(".1)");
+          if (pdbfnum < files.length - 1)
+          {
+            selectioncom.append("|");
           }
         }
-        // add final selection phrase
-        if (lpos != -1)
+      }
+      // TODO: consider bailing if nmatched less than 4 because superposition
+      // not
+      // well defined.
+      // TODO: refactor superposable position search (above) from jmol selection
+      // construction (below)
+      for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
+      {
+        if (pdbfnum == refStructure)
         {
-          molsel.append(lpos);
-          molsel.append(chainCd);
-          molsel.append("}");
+          continue;
         }
-        selcom[pdbfnum] = molsel.toString();
-        selectioncom.append("((");
-        selectioncom.append(selcom[pdbfnum].substring(1,
-                selcom[pdbfnum].length() - 1));
-        selectioncom.append(" )& ");
-        selectioncom.append(pdbfnum + 1);
-        selectioncom.append(".1)");
-        if (pdbfnum < files.length - 1)
+        command.append("echo ");
+        command.append("\"Superposing (");
+        command.append(chainNames[pdbfnum]);
+        command.append(") against reference (");
+        command.append(chainNames[refStructure]);
+        command.append(")\";\ncompare ");
+        command.append("{");
+        command.append(1 + pdbfnum);
+        command.append(".1} {");
+        command.append(1 + refStructure);
+        command.append(".1} SUBSET {*.CA | *.P} ATOMS ");
+
+        // form the matched pair strings
+        String sep = "";
+        for (int s = 0; s < 2; s++)
         {
-          selectioncom.append("|");
+          command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
         }
+        command.append(" ROTATE TRANSLATE;\n");
       }
+      System.out.println("Select regions:\n" + selectioncom.toString());
+      evalStateCommand("select *; cartoons off; backbone; select ("
+              + selectioncom.toString() + "); cartoons; ");
+      // selcom.append("; ribbons; ");
+      System.out.println("Superimpose command(s):\n" + command.toString());
+
+      evalStateCommand(command.toString());
     }
-    // TODO: consider bailing if nmatched less than 4 because superposition not
-    // well defined.
-    // TODO: refactor superposable position search (above) from jmol selection
-    // construction (below)
-    for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
-    {
-      if (pdbfnum == refStructure)
-      {
-        continue;
-      }
-      command.append("compare ");
-      command.append("{");
-      command.append(1 + pdbfnum);
-      command.append(".1} {");
-      command.append(1 + refStructure);
-      command.append(".1} SUBSET {*.CA | *.P} ATOMS ");
-
-      // form the matched pair strings
-      String sep = "";
-      for (int s = 0; s < 2; s++)
+    if (selectioncom.length() > 0)
+    {// finally, mark all regions that were superposed.
+      if (selectioncom.substring(selectioncom.length() - 1).equals("|"))
       {
-        command.append(selcom[(s == 0 ? pdbfnum : refStructure)]);
+        selectioncom.setLength(selectioncom.length() - 1);
       }
-      command.append(" ROTATE TRANSLATE;\n");
+      System.out.println("Select regions:\n" + selectioncom.toString());
+      evalStateCommand("select *; cartoons off; backbone; select ("
+              + selectioncom.toString() + "); cartoons; ");
+      // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
     }
-    System.out.println("Select regions:\n" + selectioncom.toString());
-    evalStateCommand("select *; cartoons off; backbone; select ("
-            + selectioncom.toString() + "); cartoons; ");
-    // selcom.append("; ribbons; ");
-    System.out.println("Superimpose command(s):\n" + command.toString());
-
-    evalStateCommand(command.toString());
-
-    // evalStateCommand("select *; backbone; select "+selcom.toString()+"; cartoons; center "+selcom.toString());
   }
 
   public void evalStateCommand(String command)
@@ -492,7 +548,8 @@ public abstract class JalviewJmolBinding implements StructureListener,
    * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
    * if colourBySequence is enabled.
    */
-  public void colourBySequence(boolean showFeatures, AlignmentI alignment)
+  public void colourBySequence(boolean showFeatures,
+          jalview.api.AlignmentViewPanel alignmentv)
   {
     if (!colourBySequence)
       return;
@@ -501,14 +558,15 @@ public abstract class JalviewJmolBinding implements StructureListener,
       return;
     }
     String[] files = getPdbFile();
-    SequenceRenderer sr = getSequenceRenderer();
+
+    SequenceRenderer sr = getSequenceRenderer(alignmentv);
 
     FeatureRenderer fr = null;
     if (showFeatures)
     {
-      fr = getFeatureRenderer();
+      fr = getFeatureRenderer(alignmentv);
     }
-
+    AlignmentI alignment = alignmentv.getAlignment();
     StringBuffer command = new StringBuffer();
 
     for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
@@ -543,7 +601,7 @@ public abstract class JalviewJmolBinding implements StructureListener,
 
               Color col = sr.getResidueBoxColour(sequence[pdbfnum][s], r);
 
-              if (showFeatures)
+              if (showFeatures && fr != null)
                 col = fr.findFeatureColour(col, sequence[pdbfnum][s], r);
               String newSelcom = (mapping[m].getChain() != " " ? ":"
                       + mapping[m].getChain() : "")
@@ -655,9 +713,12 @@ public abstract class JalviewJmolBinding implements StructureListener,
    * returns the current featureRenderer that should be used to colour the
    * structures
    * 
+   * @param alignment
+   * 
    * @return
    */
-  public abstract FeatureRenderer getFeatureRenderer();
+  public abstract FeatureRenderer getFeatureRenderer(
+          AlignmentViewPanel alignment);
 
   /**
    * instruct the Jalview binding to update the pdbentries vector if necessary
@@ -733,9 +794,12 @@ public abstract class JalviewJmolBinding implements StructureListener,
    * returns the current sequenceRenderer that should be used to colour the
    * structures
    * 
+   * @param alignment
+   * 
    * @return
    */
-  public abstract SequenceRenderer getSequenceRenderer();
+  public abstract SequenceRenderer getSequenceRenderer(
+          AlignmentViewPanel alignment);
 
   // ///////////////////////////////
   // JmolStatusListener
@@ -830,6 +894,7 @@ public abstract class JalviewJmolBinding implements StructureListener,
   public void mouseOverStructure(int atomIndex, String strInfo)
   {
     int pdbResNum;
+    int alocsep = strInfo.indexOf("^");
     int mdlSep = strInfo.indexOf("/");
     int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
 
@@ -842,9 +907,18 @@ public abstract class JalviewJmolBinding implements StructureListener,
         chainSeparator = mdlSep;
       }
     }
-    pdbResNum = Integer.parseInt(strInfo.substring(
-            strInfo.indexOf("]") + 1, chainSeparator));
+    // handle insertion codes
+    if (alocsep != -1)
+    {
+      pdbResNum = Integer.parseInt(strInfo.substring(
+              strInfo.indexOf("]") + 1, alocsep));
 
+    }
+    else
+    {
+      pdbResNum = Integer.parseInt(strInfo.substring(
+              strInfo.indexOf("]") + 1, chainSeparator));
+    }
     String chainId;
 
     if (strInfo.indexOf(":") > -1)
@@ -1051,6 +1125,7 @@ public abstract class JalviewJmolBinding implements StructureListener,
     String[] oldmodels = modelFileNames;
     modelFileNames = null;
     chainNames = new Vector();
+    chainFile = new Hashtable();
     boolean notifyLoaded = false;
     String[] modelfilenames = getPdbFile();
     ssm = StructureSelectionManager.getStructureSelectionManager();
@@ -1160,8 +1235,10 @@ public abstract class JalviewJmolBinding implements StructureListener,
             // add an entry for every chain in the model
             for (int i = 0; i < pdb.chains.size(); i++)
             {
-              chainNames.addElement(new String(pdb.id + ":"
-                      + ((MCview.PDBChain) pdb.chains.elementAt(i)).id));
+              String chid = new String(pdb.id + ":"
+                      + ((MCview.PDBChain) pdb.chains.elementAt(i)).id);
+              chainFile.put(chid, pdbentry[pe].getFile());
+              chainNames.addElement(chid);
             }
             notifyLoaded = true;
           }
@@ -1199,7 +1276,7 @@ public abstract class JalviewJmolBinding implements StructureListener,
     ssm.addStructureViewerListener(this);
     if (notifyLoaded)
     {
-      FeatureRenderer fr = getFeatureRenderer();
+      FeatureRenderer fr = getFeatureRenderer(null);
       if (fr != null)
       {
         fr.featuresAdded();
@@ -1314,7 +1391,7 @@ public abstract class JalviewJmolBinding implements StructureListener,
    * @param codeBase
    * @param commandOptions
    */
-  public void allocateViewer(Component renderPanel, boolean jmolfileio,
+  public void allocateViewer(Container renderPanel, boolean jmolfileio,
           String htmlName, URL documentBase, URL codeBase,
           String commandOptions)
   {
@@ -1337,7 +1414,7 @@ public abstract class JalviewJmolBinding implements StructureListener,
    * @param buttonsToShow
    *          - buttons to show on the console, in ordr
    */
-  public void allocateViewer(Component renderPanel, boolean jmolfileio,
+  public void allocateViewer(Container renderPanel, boolean jmolfileio,
           String htmlName, URL documentBase, URL codeBase,
           String commandOptions, final Container consolePanel,
           String buttonsToShow)
@@ -1348,75 +1425,38 @@ public abstract class JalviewJmolBinding implements StructureListener,
             commandOptions, this);
 
     console = createJmolConsole(viewer, consolePanel, buttonsToShow);
-    if (console != null)
+    if (consolePanel != null)
     {
-      viewer.setConsole(new JmolAppConsoleInterface()
-      {
-
-        @Override
-        public JmolScriptEditorInterface getScriptEditor()
-        {
-          return console.getScriptEditor();
-        }
-
-        @Override
-        public JmolAppConsoleInterface getAppConsole(Viewer viewer,
-                Component display)
-        {
-          return console;
-        }
-
-        public String getText()
-        {
-          return console.getText();
-        }
+      consolePanel.addComponentListener(this);
 
-        @Override
-        public Object getMyMenuBar()
-        {
-          return console.getMyMenuBar();
-        }
-
-        @Override
-        public void setVisible(boolean b)
-        {
-          showConsole(b);
-        }
+    }
 
-        @Override
-        public void sendConsoleEcho(String strEcho)
-        {
-          console.sendConsoleEcho(strEcho);
+  }
 
-        }
+  protected abstract JmolAppConsoleInterface createJmolConsole(
+          JmolViewer viewer2, Container consolePanel, String buttonsToShow);
 
-        @Override
-        public void sendConsoleMessage(String strInfo)
-        {
-          console.sendConsoleMessage(strInfo);
-        }
+  protected org.jmol.api.JmolAppConsoleInterface console = null;
 
-        @Override
-        public void zap()
-        {
-          console.zap();
-        }
+  public void componentResized(ComponentEvent e)
+  {
 
-        @Override
-        public void dispose()
-        {
-          console.dispose();
-        }
+  }
 
-      });
-    }
+  public void componentMoved(ComponentEvent e)
+  {
 
   }
 
-  protected abstract JmolAppConsoleInterface createJmolConsole(
-          JmolViewer viewer2, Container consolePanel, String buttonsToShow);
+  public void componentShown(ComponentEvent e)
+  {
+    showConsole(true);
+  }
 
-  protected org.jmol.api.JmolAppConsoleInterface console = null;
+  public void componentHidden(ComponentEvent e)
+  {
+    showConsole(false);
+  }
 
   public void setLoadingFromArchive(boolean loadingFromArchive)
   {