2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.ext.jmol;
24 import java.awt.event.*;
26 import jalview.api.FeatureRenderer;
27 import jalview.api.SequenceRenderer;
28 import jalview.api.SequenceStructureBinding;
29 import jalview.datamodel.*;
30 import jalview.structure.*;
33 import org.jmol.api.*;
34 import org.jmol.adapter.smarter.SmarterJmolAdapter;
36 import org.jmol.popup.*;
37 import org.jmol.viewer.JmolConstants;
39 import jalview.schemes.*;
41 public abstract class JalviewJmolBinding implements StructureListener,
42 JmolStatusListener, SequenceStructureBinding
46 * set if Jmol state is being restored from some source - instructs binding
47 * not to apply default display style when structure set is updated for first
50 private boolean loadingFromArchive = false;
52 * state flag used to check if the Jmol viewer's paint method can be called
54 private boolean finishedInit=false;
56 public boolean isFinishedInit()
61 public void setFinishedInit(boolean finishedInit)
63 this.finishedInit = finishedInit;
66 boolean allChainsSelected = false;
69 * when true, try to search the associated datamodel for sequences that are
70 * associated with any unknown structures in the Jmol view.
72 private boolean associateNewStructs = false;
74 Vector atomsPicked = new Vector();
76 public Vector chainNames;
80 boolean colourBySequence = true;
82 StringBuffer eval = new StringBuffer();
84 public String fileLoadingError;
87 * the default or current model displayed if the model cannot be identified
88 * from the selection message
92 protected JmolPopup jmolpopup;
101 * current set of model filenames loaded in the Jmol instance
103 String[] modelFileNames = null;
105 public PDBEntry[] pdbentry;
108 * datasource protocol for access to PDBEntry
110 String protocol = null;
112 StringBuffer resetLastRes = new StringBuffer();
114 public SequenceI[] sequence;
116 StructureSelectionManager ssm;
118 public JmolViewer viewer;
120 public JalviewJmolBinding(PDBEntry[] pdbentry, SequenceI[] seq,
121 String[] chains, String protocol)
124 this.chains = chains;
125 this.pdbentry = pdbentry;
126 this.protocol = protocol;
129 * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(),
130 * "jalviewJmol", ap.av.applet .getDocumentBase(),
131 * ap.av.applet.getCodeBase(), "", this);
133 * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true);
138 * construct a title string for the viewer window based on the data jalview knows about
141 public String getViewerTitle() {
142 if (sequence==null || pdbentry==null || sequence.length<1 || pdbentry.length<1)
144 return("Jalview Jmol Window");
146 StringBuffer title = new StringBuffer(sequence[0].getName() + ":"
147 + pdbentry[0].getId());
149 if (pdbentry[0].getProperty() != null)
151 if (pdbentry[0].getProperty().get("method") != null)
153 title.append(" Method: ");
154 title.append(pdbentry[0].getProperty().get("method"));
156 if (pdbentry[0].getProperty().get("chains") != null)
158 title.append(" Chain:");
159 title.append(pdbentry[0].getProperty().get("chains"));
162 return title.toString();
166 * prepare the view for a given set of models/chains. chainList contains
167 * strings of the form 'pdbfilename:Chaincode'
170 * list of chains to make visible
172 public void centerViewer(Vector chainList)
174 StringBuffer cmd = new StringBuffer();
177 for (int i = 0, iSize = chainList.size(); i < iSize; i++)
180 lbl = (String) chainList.elementAt(i);
184 mlength = lbl.indexOf(":", p);
185 } while (p < mlength && mlength < (lbl.length() - 2));
186 cmd.append(":" + lbl.substring(mlength + 1) + " /"
187 + getModelNum(lbl.substring(0, mlength)) + " or ");
189 if (cmd.length() > 0)
190 cmd.setLength(cmd.length() - 4);
191 evalStateCommand("select *;restrict " + cmd + ";cartoon;center "
195 public void closeViewer()
197 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
198 // remove listeners for all structures in viewer
199 StructureSelectionManager.getStructureSelectionManager()
200 .removeStructureViewerListener(this, this.getPdbFile());
201 // and shut down jmol
202 viewer.evalStringQuiet("zap");
203 viewer.setJmolStatusListener(null);
208 public void colourByChain()
210 colourBySequence = false;
211 evalStateCommand("select *;color chain");
214 public void colourByCharge()
216 colourBySequence = false;
217 evalStateCommand("select *;color white;select ASP,GLU;color red;"
218 + "select LYS,ARG;color blue;select CYS;color yellow");
222 * superpose the structures associated with sequences in the alignment
223 * according to their corresponding positions.
225 public void superposeStructures(AlignmentI alignment)
227 String[] files = getPdbFile();
229 StringBuffer command = new StringBuffer();
230 boolean matched[] = new boolean[alignment.getWidth()];
231 String commonpositions[][] = new String[files.length][alignment
233 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
235 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
237 if (mapping == null || mapping.length < 1)
241 for (int s = 0; s < sequence.length; s++)
243 for (int sp, m = 0; m < mapping.length; m++)
245 if (mapping[m].getSequence() == sequence[s]
246 && (sp = alignment.findIndex(sequence[s])) > -1)
248 SequenceI asp = alignment.getSequenceAt(sp);
249 for (int r = 0; r < asp.getLength(); r++)
251 // no mapping to gaps in sequence
252 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
254 matched[r] = false; // exclude from common set
257 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
259 if (pos < 1 || pos == lastPos)
264 commonpositions[m][r] = (mapping[m].getChain() != " " ? ":"
265 + mapping[m].getChain() : "")
266 + "/" + (pdbfnum + 1) + ".1";
273 command.append("select ");
274 // form the matched pair selection strings
276 for (int r = 0; r < matched.length; r++)
282 for (int s = 0; s < commonpositions.length; s++)
286 command.append(" | ");
288 command.append(commonpositions[s][r]);
294 evalStateCommand(command.toString());
297 public void evalStateCommand(String command) {
299 if (lastCommand == null || !lastCommand.equals(command))
301 viewer.evalStringQuiet(command+"\n");
304 lastCommand = command;
307 * colour any structures associated with sequences in the given alignment
308 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
309 * if colourBySequence is enabled.
311 public void colourBySequence(boolean showFeatures, AlignmentI alignment)
313 if (!colourBySequence)
319 String[] files = getPdbFile();
320 SequenceRenderer sr = getSequenceRenderer();
322 FeatureRenderer fr = null;
325 fr = getFeatureRenderer();
328 StringBuffer command = new StringBuffer();
330 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
332 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
334 if (mapping == null || mapping.length < 1)
338 for (int s = 0; s < sequence.length; s++)
340 for (int sp, m = 0; m < mapping.length; m++)
342 if (mapping[m].getSequence() == sequence[s]
343 && (sp = alignment.findIndex(sequence[s])) > -1)
345 SequenceI asp = alignment.getSequenceAt(sp);
346 for (int r = 0; r < asp.getLength(); r++)
348 // no mapping to gaps in sequence
349 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
353 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
355 if (pos < 1 || pos == lastPos)
360 Color col = sr.getResidueBoxColour(sequence[s], r);
363 col = fr.findFeatureColour(col, sequence[s], r);
364 String newSelcom = (mapping[m].getChain() != " " ? ":"
365 + mapping[m].getChain() : "")
374 + col.getBlue() + "]";
375 if (command.toString().endsWith(newSelcom))
377 command = condenseCommand(command.toString(), pos);
380 // TODO: deal with case when buffer is too large for Jmol to parse
381 // - execute command and flush
383 command.append(";select " + pos);
384 command.append(newSelcom);
391 evalStateCommand(command.toString());
394 public boolean isColourBySequence()
396 return colourBySequence;
399 public void setColourBySequence(boolean colourBySequence)
401 this.colourBySequence = colourBySequence;
404 StringBuffer condenseCommand(String command, int pos)
407 StringBuffer sb = new StringBuffer(command.substring(0, command
408 .lastIndexOf("select") + 7));
410 command = command.substring(sb.length());
414 if (command.indexOf("-") > -1)
416 start = command.substring(0, command.indexOf("-"));
420 start = command.substring(0, command.indexOf(":"));
423 sb.append(start + "-" + pos + command.substring(command.indexOf(":")));
428 public void createImage(String file, String type, int quality)
430 System.out.println("JMOL CREATE IMAGE");
433 public String createImage(String fileName, String type,
434 Object textOrBytes, int quality)
436 System.out.println("JMOL CREATE IMAGE");
440 public String eval(String strEval)
442 // System.out.println(strEval);
443 // "# 'eval' is implemented only for the applet.";
447 // End StructureListener
448 // //////////////////////////
450 public float[][] functionXY(String functionName, int x, int y)
455 public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
457 // TODO Auto-generated method stub
461 public Color getColour(int atomIndex, int pdbResNum, String chain,
464 if (getModelNum(pdbfile) < 0)
466 // TODO: verify atomIndex is selecting correct model.
467 return new Color(viewer.getAtomArgb(atomIndex));
471 * returns the current featureRenderer that should be used to colour the
476 public abstract FeatureRenderer getFeatureRenderer();
478 private int getModelNum(String modelFileName)
480 String[] mfn = getPdbFile();
485 for (int i = 0; i < mfn.length; i++)
487 if (mfn[i].equalsIgnoreCase(modelFileName))
493 // ////////////////////////////////
494 // /StructureListener
495 public String[] getPdbFile()
497 if (modelFileNames == null)
499 String mset[] = new String[viewer.getModelCount()];
500 for (int i = 0; i < mset.length; i++)
502 mset[i] = viewer.getModelFileName(i);
504 modelFileNames = mset;
506 return modelFileNames;
509 public Hashtable getRegistryInfo()
511 // TODO Auto-generated method stub
516 * returns the current sequenceRenderer that should be used to colour the
521 public abstract SequenceRenderer getSequenceRenderer();
523 // ///////////////////////////////
524 // JmolStatusListener
526 public void handlePopupMenu(int x, int y)
528 jmolpopup.show(x, y);
532 public void highlightAtom(int atomIndex, int pdbResNum, String chain,
535 if (modelFileNames == null)
540 // look up file model number for this pdbfile
543 // may need to adjust for URLencoding here - we don't worry about that yet.
544 while (mdlNum < modelFileNames.length
545 && !pdbfile.equals(modelFileNames[mdlNum]))
547 // System.out.println("nomatch:"+pdbfile+"\nmodelfn:"+fn);
550 if (mdlNum == modelFileNames.length)
556 // if (!pdbfile.equals(pdbentry.getFile()))
558 if (resetLastRes.length() > 0)
560 viewer.evalStringQuiet(resetLastRes.toString());
564 eval.append("select " + pdbResNum); // +modelNum
566 resetLastRes.setLength(0);
567 resetLastRes.append("select " + pdbResNum); // +modelNum
570 resetLastRes.append(":");
571 if (!chain.equals(" "))
574 resetLastRes.append(chain);
577 eval.append(" /" + (mdlNum + 1));
578 resetLastRes.append("/" + (mdlNum + 1));
580 eval.append(";wireframe 100;" + eval.toString() + " and not hetero;");
582 resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
583 + " and not hetero; spacefill 0;");
585 eval.append("spacefill 200;select none");
587 viewer.evalStringQuiet(eval.toString());
592 boolean debug = true;
594 private void jmolHistory(boolean enable)
596 viewer.evalStringQuiet("History " + ((debug || enable) ? "on" : "off"));
599 public void loadInline(String string)
602 viewer.openStringInline(string);
605 public void mouseOverStructure(int atomIndex, String strInfo)
608 int mdlSep = strInfo.indexOf("/");
609 int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
611 if (chainSeparator == -1)
613 chainSeparator = strInfo.indexOf(".");
614 if (mdlSep > -1 && mdlSep < chainSeparator)
616 chainSeparator1 = chainSeparator;
617 chainSeparator = mdlSep;
620 pdbResNum = Integer.parseInt(strInfo.substring(
621 strInfo.indexOf("]") + 1, chainSeparator));
625 if (strInfo.indexOf(":") > -1)
626 chainId = strInfo.substring(strInfo.indexOf(":") + 1, strInfo
633 String pdbfilename = modelFileNames[frameNo]; // default is first or current
637 if (chainSeparator1 == -1)
639 chainSeparator1 = strInfo.indexOf(".", mdlSep);
641 String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
642 chainSeparator1) : strInfo.substring(mdlSep + 1);
645 // recover PDB filename for the model hovered over.
647 .getModelFileName(new Integer(mdlId).intValue() - 1);
648 } catch (Exception e)
653 if (lastMessage == null || !lastMessage.equals(strInfo))
654 ssm.mouseOverStructure(pdbResNum, chainId, pdbfilename);
656 lastMessage = strInfo;
659 public void notifyAtomHovered(int atomIndex, String strInfo, String data)
663 System.err.println("Ignoring additional hover info: " + data+ " (other info: '" + strInfo + "' pos " + atomIndex + ")");
665 mouseOverStructure(atomIndex, strInfo);
669 * { if (history != null && strStatus != null &&
670 * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
674 public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
677 * this implements the toggle label behaviour copied from the original
678 * structure viewer, MCView
682 System.err.println("Ignoring additional pick data string " + strData);
684 int chainSeparator = strInfo.indexOf(":");
686 if (chainSeparator == -1)
687 chainSeparator = strInfo.indexOf(".");
689 String picked = strInfo.substring(strInfo.indexOf("]") + 1,
691 String mdlString = "";
692 if ((p = strInfo.indexOf(":")) > -1)
693 picked += strInfo.substring(p + 1, strInfo.indexOf("."));
695 if ((p = strInfo.indexOf("/")) > -1)
697 mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
699 picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
703 if (!atomsPicked.contains(picked))
705 viewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
706 atomsPicked.addElement(picked);
710 viewer.evalString("select " + picked + ";label off");
711 atomsPicked.removeElement(picked);
714 // TODO: in application this happens
716 //if (scriptWindow != null)
718 // scriptWindow.sendConsoleMessage(strInfo);
719 // scriptWindow.sendConsoleMessage("\n");
725 public void notifyCallback(int type, Object[] data)
731 case JmolConstants.CALLBACK_LOADSTRUCT:
732 notifyFileLoaded((String) data[1], (String) data[2],
733 (String) data[3], (String) data[4], ((Integer) data[5])
737 case JmolConstants.CALLBACK_PICK:
738 notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
740 // also highlight in alignment
741 case JmolConstants.CALLBACK_HOVER:
742 notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
745 case JmolConstants.CALLBACK_SCRIPT:
746 notifyScriptTermination((String) data[2], ((Integer) data[3])
749 case JmolConstants.CALLBACK_ECHO:
750 sendConsoleEcho((String) data[1]);
752 case JmolConstants.CALLBACK_MESSAGE:
753 sendConsoleMessage((data == null) ? ((String) null)
756 case JmolConstants.CALLBACK_ERROR:
757 // System.err.println("Ignoring error callback.");
759 case JmolConstants.CALLBACK_SYNC:
760 case JmolConstants.CALLBACK_RESIZE:
763 case JmolConstants.CALLBACK_MEASURE:
765 case JmolConstants.CALLBACK_CLICK:
768 System.err.println("Unhandled callback " + type + " " + data[1].toString());
771 } catch (Exception e)
773 System.err.println("Squashed Jmol callback handler error:");
778 public boolean notifyEnabled(int callbackPick)
780 switch (callbackPick)
782 case JmolConstants.CALLBACK_ECHO:
783 case JmolConstants.CALLBACK_LOADSTRUCT:
784 case JmolConstants.CALLBACK_MEASURE:
785 case JmolConstants.CALLBACK_MESSAGE:
786 case JmolConstants.CALLBACK_PICK:
787 case JmolConstants.CALLBACK_SCRIPT:
788 case JmolConstants.CALLBACK_HOVER:
789 case JmolConstants.CALLBACK_ERROR:
791 case JmolConstants.CALLBACK_RESIZE:
792 case JmolConstants.CALLBACK_SYNC:
793 case JmolConstants.CALLBACK_CLICK:
794 case JmolConstants.CALLBACK_ANIMFRAME:
795 case JmolConstants.CALLBACK_MINIMIZATION:
800 public void notifyFileLoaded(String fullPathName, String fileName2,
801 String modelName, String errorMsg, int modelParts)
803 if (errorMsg != null)
805 fileLoadingError = errorMsg;
809 fileLoadingError = null;
810 String[] oldmodels = modelFileNames;
811 modelFileNames = null;
812 chainNames = new Vector();
813 boolean notifyLoaded = false;
814 String[] modelfilenames = getPdbFile();
815 ssm = StructureSelectionManager.getStructureSelectionManager();
816 // first check if we've lost any structures
817 if (oldmodels!=null && oldmodels.length>0)
820 for (int i=0;i<oldmodels.length;i++)
822 for (int n=0;n<modelfilenames.length; n++)
824 if (modelfilenames[n]==oldmodels[i])
830 if (oldmodels[i]!=null)
837 String[] oldmfn = new String[oldm];
839 for (int i=0;i<oldmodels.length; i++)
841 if (oldmodels[i]!=null) {
842 oldmfn[oldm++] = oldmodels[i];
845 // deregister the Jmol instance for these structures - we'll add
846 // ourselves again at the end for the current structure set.
847 ssm.removeStructureViewerListener(this, oldmfn);
850 for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
852 String fileName = modelfilenames[modelnum];
853 if (fileName != null)
855 // search pdbentries and sequences to find correct pdbentry and
856 // sequence[] pair for this filename
857 if (pdbentry != null)
859 boolean foundEntry = false;
860 for (int pe = 0; pe < pdbentry.length; pe++)
862 if (pdbentry[pe].getFile().equals(fileName))
868 // TODO: replace with getData ?
869 pdb = ssm.setMapping(sequence, chains, pdbentry[pe]
870 .getFile(), AppletFormatAdapter.PASTE);
871 pdbentry[pe].setFile("INLINE" + pdb.id);
875 // TODO: Jmol can in principle retrieve from CLASSLOADER but
878 // to be tested. See mantis bug
879 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
880 String protocol = AppletFormatAdapter.URL;
883 File fl = new java.io.File(pdbentry[pe].getFile());
886 protocol = AppletFormatAdapter.FILE;
888 } catch (Exception e)
894 pdb = ssm.setMapping(sequence, chains, pdbentry[pe]
895 .getFile(), protocol);
899 pdbentry[pe].setId(pdb.id);
901 for (int i = 0; i < pdb.chains.size(); i++)
903 chainNames.addElement(new String(pdb.id + ":"
904 + ((MCview.PDBChain) pdb.chains.elementAt(i)).id));
909 if (!foundEntry && associateNewStructs)
911 // this is a foreign pdb file that jalview doesn't know about - add
914 // and try to find a home - either on a matching sequence or as a
917 String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
919 // parse pdb file into a chain, etc.
920 // locate best match for pdb in associated views and add mapping to
922 // if properly registered then
929 // so finally, update the jmol bits and pieces
930 jmolpopup.updateComputedMenus();
931 if (!isLoadingFromArchive())
934 .evalStringQuiet("model 0; select backbone;restrict;cartoon;wireframe off;spacefill off");
936 setLoadingFromArchive(false);
937 // register ourselves as a listener and notify the gui that it needs to
939 ssm.addStructureViewerListener(this);
942 FeatureRenderer fr = getFeatureRenderer();
951 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
953 notifyAtomPicked(iatom, strMeasure, null);
956 public abstract void notifyScriptTermination(String strStatus, int msWalltime);
959 * display a message echoed from the jmol viewer
963 public abstract void sendConsoleEcho(String strEcho); /*
964 * { showConsole(true);
966 * history.append("\n" +
970 // /End JmolStatusListener
971 // /////////////////////////////
975 * status message - usually the response received after a script
978 public abstract void sendConsoleMessage(String strStatus);
980 public void setCallbackFunction(String callbackType,
981 String callbackFunction)
983 System.err.println("Ignoring set-callback request to associate "
984 + callbackType + " with function " + callbackFunction);
988 public void setJalviewColourScheme(ColourSchemeI cs)
990 colourBySequence = false;
999 // TODO: Switch between nucleotide or aa selection expressions
1000 Enumeration en = ResidueProperties.aa3Hash.keys();
1001 StringBuffer command = new StringBuffer("select *;color white;");
1002 while (en.hasMoreElements())
1004 res = en.nextElement().toString();
1005 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
1009 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
1011 command.append("select " + res + ";color[" + col.getRed() + ","
1012 + col.getGreen() + "," + col.getBlue() + "];");
1015 evalStateCommand(command.toString());
1019 public void showHelp()
1021 showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
1025 * open the URL somehow
1029 public abstract void showUrl(String url, String target);
1032 * called when the binding thinks the UI needs to be refreshed after a Jmol
1033 * state change. this could be because structures were loaded, or because an
1034 * error has occured.
1036 public abstract void updateUI();
1038 public void allocateViewer(Component renderPanel, String htmlName,
1039 URL documentBase, URL codeBase, String commandOptions)
1041 viewer = JmolViewer.allocateViewer(renderPanel,
1042 new SmarterJmolAdapter(), htmlName+((Object) this).toString(), documentBase, codeBase,
1043 commandOptions, this);
1046 public void setLoadingFromArchive(boolean loadingFromArchive)
1048 this.loadingFromArchive = loadingFromArchive;
1051 public boolean isLoadingFromArchive()
1053 return loadingFromArchive;
1055 public void setBackgroundColour(java.awt.Color col)
1058 viewer.evalStringQuiet("background [" + col.getRed() + ","
1059 + col.getGreen() + "," + col.getBlue() + "];");