From: jprocter Date: Tue, 29 Jun 2010 16:19:32 +0000 (+0000) Subject: new abstract proxy for use by applet and application X-Git-Tag: Release_2_6~157 X-Git-Url: http://source.jalview.org/gitweb/?a=commitdiff_plain;h=0364f47ccc79b650972680e9950208299c9b851d;p=jalview.git new abstract proxy for use by applet and application --- diff --git a/src/jalview/ext/jmol/JalviewJmolBinding.java b/src/jalview/ext/jmol/JalviewJmolBinding.java new file mode 100644 index 0000000..fbd7176 --- /dev/null +++ b/src/jalview/ext/jmol/JalviewJmolBinding.java @@ -0,0 +1,824 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5) + * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle + * + * 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 . + */ +package jalview.ext.jmol; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; + +import jalview.api.FeatureRenderer; +import jalview.api.SequenceRenderer; +import jalview.api.SequenceStructureBinding; +import jalview.datamodel.*; +import jalview.structure.*; +import jalview.io.*; + +import org.jmol.api.*; +import org.jmol.adapter.smarter.SmarterJmolAdapter; + +import org.jmol.popup.*; +import org.jmol.viewer.JmolConstants; + +import jalview.schemes.*; + +public abstract class JalviewJmolBinding implements StructureListener, + JmolStatusListener, SequenceStructureBinding + +{ + + boolean allChainsSelected = false; + + /** + * when true, try to search the associated datamodel for sequences that are + * associated with any unknown structures in the Jmol view. + */ + private boolean associateNewStructs = false; + + Vector atomsPicked = new Vector(); + + private Vector chainNames; + + String[] chains; + + boolean colourBySequence = true; + + StringBuffer eval = new StringBuffer(); + + String fileLoadingError; + + /** + * the default or current model displayed if the model cannot be identified + * from the selection message + */ + int frameNo = 0; + + JmolPopup jmolpopup; + + String lastCommand; + + String lastMessage; + + boolean loadedInline; + + /** + * current set of model filenames loaded in the Jmol instance + */ + String[] modelFileNames = null; + + PDBEntry[] pdbentry; + + /** + * datasource protocol for access to PDBEntry + */ + String protocol = null; + + StringBuffer resetLastRes = new StringBuffer(); + + SequenceI[] sequence; + + StructureSelectionManager ssm; + + JmolViewer viewer; + + public JalviewJmolBinding(PDBEntry[] pdbentry, SequenceI[] seq, + String[] chains, String protocol) + { + /* + * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(), + * "jalviewJmol", ap.av.applet .getDocumentBase(), + * ap.av.applet.getCodeBase(), "", this); + * + * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true); + */ + } + + /** + * prepare the view for a given set of models/chains. chainList contains + * strings of the form 'pdbfilename:Chaincode' + * + * @param chainList + * list of chains to make visible + */ + void centerViewer(Vector chainList) + { + StringBuffer cmd = new StringBuffer(); + String lbl; + int mlength, p; + for (int i = 0, iSize = chainList.size(); i < iSize; i++) + { + mlength = 0; + lbl = (String) chainList.elementAt(i); + do + { + p = mlength; + mlength = lbl.indexOf(":", p); + } while (p < mlength && mlength < (lbl.length() - 2)); + cmd.append(":" + lbl.substring(mlength + 1) + " /" + + getModelNum(lbl.substring(0, mlength)) + " or "); + } + if (cmd.length() > 0) + cmd.setLength(cmd.length() - 4); + + jmolHistory(false); + viewer + .evalString("select *;restrict " + cmd + ";cartoon;center " + + cmd); + jmolHistory(true); + } + + void closeViewer() + { + viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE); + // remove listeners for all structures in viewer + StructureSelectionManager.getStructureSelectionManager() + .removeStructureViewerListener(this, this.getPdbFile()); + // and shut down jmol + viewer.evalStringQuiet("zap"); + viewer.setJmolStatusListener(null); + + viewer = null; + } + + public void colourByChain() + { + jmolHistory(false); + colourBySequence = false; + viewer.evalStringQuiet("select *;color chain"); + jmolHistory(true); + } + + public void colourByCharge() + { + jmolHistory(false); + colourBySequence = false; + viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;" + + "select LYS,ARG;color blue;select CYS;color yellow"); + jmolHistory(true); + } + + /** + * colour any structures associated with sequences in the given alignment + * using the getFeatureRenderer() and getSequenceRenderer() renderers but only + * if colourBySequence is enabled. + */ + public void colourBySequence(boolean showFeatures, AlignmentI alignment) + { + if (!colourBySequence) + return; + String[] files = getPdbFile(); + SequenceRenderer sr = getSequenceRenderer(); + + FeatureRenderer fr = null; + if (showFeatures) + { + fr = getFeatureRenderer(); + } + + StringBuffer command = new StringBuffer(); + + for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++) + { + StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]); + + if (mapping == null || mapping.length < 1) + continue; + + int lastPos = -1; + for (int s = 0; s < sequence.length; s++) + { + for (int sp, m = 0; m < mapping.length; m++) + { + if (mapping[m].getSequence() == sequence[s] + && (sp = alignment.findIndex(sequence[s])) > -1) + { + SequenceI asp = alignment.getSequenceAt(sp); + for (int r = 0; r < asp.getLength(); r++) + { + // no mapping to gaps in sequence + if (jalview.util.Comparison.isGap(asp.getCharAt(r))) + { + continue; + } + int pos = mapping[m].getPDBResNum(asp.findPosition(r)); + + if (pos < 1 || pos == lastPos) + continue; + + lastPos = pos; + + Color col = sr.getResidueBoxColour(sequence[s], r); + + if (showFeatures) + col = fr.findFeatureColour(col, sequence[s], r); + String newSelcom = (mapping[m].getChain() != " " ? ":" + + mapping[m].getChain() : "") + + "/" + + (pdbfnum + 1) + + ".1" + + ";color[" + + col.getRed() + + "," + + col.getGreen() + + "," + + col.getBlue() + "]"; + if (command.toString().endsWith(newSelcom)) + { + command = condenseCommand(command.toString(), pos); + continue; + } + // TODO: deal with case when buffer is too large for Jmol to parse + // - execute command and flush + + command.append(";select " + pos); + command.append(newSelcom); + } + break; + } + } + } + } + + jmolHistory(false); + if (lastCommand == null || !lastCommand.equals(command.toString())) + { + viewer.evalStringQuiet(command.toString()); + } + jmolHistory(true); + lastCommand = command.toString(); + } + + StringBuffer condenseCommand(String command, int pos) + { + + StringBuffer sb = new StringBuffer(command.substring(0, command + .lastIndexOf("select") + 7)); + + command = command.substring(sb.length()); + + String start; + + if (command.indexOf("-") > -1) + { + start = command.substring(0, command.indexOf("-")); + } + else + { + start = command.substring(0, command.indexOf(":")); + } + + sb.append(start + "-" + pos + command.substring(command.indexOf(":"))); + + return sb; + } + + public void createImage(String file, String type, int quality) + { + } + + public String createImage(String fileName, String type, + Object textOrBytes, int quality) + { + // TODO Auto-generated method stub + return null; + } + + public String eval(String strEval) + { + // System.out.println(strEval); + // "# 'eval' is implemented only for the applet."; + return null; + } + + // End StructureListener + // ////////////////////////// + + public float[][] functionXY(String functionName, int x, int y) + { + return null; + } + + public float[][][] functionXYZ(String functionName, int nx, int ny, int nz) + { + // TODO Auto-generated method stub + return null; + } + + public Color getColour(int atomIndex, int pdbResNum, String chain, + String pdbfile) + { + if (getModelNum(pdbfile) < 0) + return null; + // TODO: verify atomIndex is selecting correct model. + return new Color(viewer.getAtomArgb(atomIndex)); + } + + /** + * returns the current featureRenderer that should be used to colour the + * structures + * + * @return + */ + abstract FeatureRenderer getFeatureRenderer(); + + private int getModelNum(String modelFileName) + { + String[] mfn = getPdbFile(); + if (mfn == null) + { + return -1; + } + for (int i = 0; i < mfn.length; i++) + { + if (mfn[i].equalsIgnoreCase(modelFileName)) + return i; + } + return -1; + } + + // //////////////////////////////// + // /StructureListener + public String[] getPdbFile() + { + if (modelFileNames == null) + { + String mset[] = new String[viewer.getModelCount()]; + for (int i = 0; i < mset.length; i++) + { + mset[i] = viewer.getModelFileName(i); + } + modelFileNames = mset; + } + return modelFileNames; + } + + public Hashtable getRegistryInfo() + { + // TODO Auto-generated method stub + return null; + } + + /** + * returns the current sequenceRenderer that should be used to colour the + * structures + * + * @return + */ + abstract SequenceRenderer getSequenceRenderer(); + + // /////////////////////////////// + // JmolStatusListener + + public void handlePopupMenu(int x, int y) + { + jmolpopup.show(x, y); + } + + // jmol/ssm only + public void highlightAtom(int atomIndex, int pdbResNum, String chain, + String pdbfile) + { + if (modelFileNames == null) + { + return; + } + + // look up file model number for this pdbfile + int mdlNum = 0; + String fn; + // may need to adjust for URLencoding here - we don't worry about that yet. + while (mdlNum < modelFileNames.length + && !pdbfile.equals(modelFileNames[mdlNum])) + { + // System.out.println("nomatch:"+pdbfile+"\nmodelfn:"+fn); + mdlNum++; + } + if (mdlNum == modelFileNames.length) + { + return; + } + + jmolHistory(false); + // if (!pdbfile.equals(pdbentry.getFile())) + // return; + if (resetLastRes.length() > 0) + { + viewer.evalStringQuiet(resetLastRes.toString()); + } + + eval.setLength(0); + eval.append("select " + pdbResNum); // +modelNum + + resetLastRes.setLength(0); + resetLastRes.append("select " + pdbResNum); // +modelNum + + eval.append(":"); + resetLastRes.append(":"); + if (!chain.equals(" ")) + { + eval.append(chain); + resetLastRes.append(chain); + } + { + eval.append(" /" + (mdlNum + 1)); + resetLastRes.append("/" + (mdlNum + 1)); + } + eval.append(";wireframe 100;" + eval.toString() + " and not hetero;"); + + resetLastRes.append(";wireframe 0;" + resetLastRes.toString() + + " and not hetero; spacefill 0;"); + + eval.append("spacefill 200;select none"); + + viewer.evalStringQuiet(eval.toString()); + jmolHistory(true); + + } + + private void jmolHistory(boolean enable) + { + viewer.setBooleanProperty("history", enable); + } + + public void loadInline(String string) + { + loadedInline = true; + viewer.openStringInline(string); + } + + public void mouseOverStructure(int atomIndex, String strInfo) + { + int pdbResNum; + int mdlSep = strInfo.indexOf("/"); + int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1; + + if (chainSeparator == -1) + { + chainSeparator = strInfo.indexOf("."); + if (mdlSep > -1 && mdlSep < chainSeparator) + { + chainSeparator1 = chainSeparator; + chainSeparator = mdlSep; + } + } + pdbResNum = Integer.parseInt(strInfo.substring( + strInfo.indexOf("]") + 1, chainSeparator)); + + String chainId; + + if (strInfo.indexOf(":") > -1) + chainId = strInfo.substring(strInfo.indexOf(":") + 1, strInfo + .indexOf(".")); + else + { + chainId = " "; + } + + String pdbfilename = modelFileNames[frameNo]; // default is first or current + // model + if (mdlSep > -1) + { + if (chainSeparator1 == -1) + { + chainSeparator1 = strInfo.indexOf(".", mdlSep); + } + String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1, + chainSeparator1) : strInfo.substring(mdlSep + 1); + try + { + // recover PDB filename for the model hovered over. + pdbfilename = viewer + .getModelFileName(new Integer(mdlId).intValue() - 1); + } catch (Exception e) + { + } + ; + } + if (lastMessage == null || !lastMessage.equals(strInfo)) + ssm.mouseOverStructure(pdbResNum, chainId, pdbfilename); + + lastMessage = strInfo; + } + + public void notifyAtomHovered(int atomIndex, String strInfo, String data) + { + if (data != null) + { + System.err.println("Ignoring additional hover info: " + data); + } + mouseOverStructure(atomIndex, strInfo); + } + + /* + * { if (history != null && strStatus != null && + * !strStatus.equals("Script completed")) { history.append("\n" + strStatus); + * } } + */ + + public void notifyAtomPicked(int atomIndex, String strInfo, String strData) + { + /** + * this implements the toggle label behaviour copied from the original + * structure viewer, MCView + */ + if (strData != null) + { + System.err.println("Ignoring additional pick data string " + strData); + } + int chainSeparator = strInfo.indexOf(":"); + int p = 0; + if (chainSeparator == -1) + chainSeparator = strInfo.indexOf("."); + + String picked = strInfo.substring(strInfo.indexOf("]") + 1, + chainSeparator); + String mdlString = ""; + if ((p = strInfo.indexOf(":")) > -1) + picked += strInfo.substring(p + 1, strInfo.indexOf(".")); + + if ((p = strInfo.indexOf("/")) > -1) + { + mdlString += strInfo.substring(p, strInfo.indexOf(" #")); + } + picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P" + + mdlString + "))"; + jmolHistory(false); + + if (!atomsPicked.contains(picked)) + { + viewer.evalStringQuiet("select " + picked + ";label %n %r:%c"); + atomsPicked.addElement(picked); + } + else + { + viewer.evalString("select " + picked + ";label off"); + atomsPicked.removeElement(picked); + } + jmolHistory(true); + + } + + public void notifyCallback(int type, Object[] data) + { + try + { + switch (type) + { + case JmolConstants.CALLBACK_LOADSTRUCT: + notifyFileLoaded((String) data[1], (String) data[2], + (String) data[3], (String) data[4], ((Integer) data[5]) + .intValue()); + + break; + case JmolConstants.CALLBACK_PICK: + notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1], + (String) data[0]); + // also highlight in alignment + case JmolConstants.CALLBACK_HOVER: + notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1], + (String) data[0]); + break; + case JmolConstants.CALLBACK_SCRIPT: + notifyScriptTermination((String) data[2], ((Integer) data[3]) + .intValue()); + break; + case JmolConstants.CALLBACK_ECHO: + sendConsoleEcho((String) data[1]); + break; + case JmolConstants.CALLBACK_MESSAGE: + sendConsoleMessage((data == null) ? ((String) null) + : (String) data[1]); + break; + case JmolConstants.CALLBACK_MEASURE: + case JmolConstants.CALLBACK_CLICK: + default: + System.err.println("Unhandled callback " + type + " " + data); + break; + } + } catch (Exception e) + { + System.err.println("Squashed Jmol callback handler error:"); + e.printStackTrace(); + } + } + + public boolean notifyEnabled(int callbackPick) + { + switch (callbackPick) + { + case JmolConstants.CALLBACK_ECHO: + case JmolConstants.CALLBACK_LOADSTRUCT: + case JmolConstants.CALLBACK_MEASURE: + case JmolConstants.CALLBACK_MESSAGE: + case JmolConstants.CALLBACK_PICK: + case JmolConstants.CALLBACK_SCRIPT: + case JmolConstants.CALLBACK_HOVER: + case JmolConstants.CALLBACK_ERROR: + return true; + case JmolConstants.CALLBACK_CLICK: + case JmolConstants.CALLBACK_ANIMFRAME: + case JmolConstants.CALLBACK_MINIMIZATION: + case JmolConstants.CALLBACK_RESIZE: + case JmolConstants.CALLBACK_SYNC: + } + return false; + } + + public void notifyFileLoaded(String fullPathName, String fileName2, + String modelName, String errorMsg, int modelParts) + { + if (errorMsg != null) + { + fileLoadingError = errorMsg; + updateUI(); + return; + } + fileLoadingError = null; + modelFileNames = null; + chainNames = new Vector(); + boolean notifyLoaded = false; + String[] modelfilenames = getPdbFile(); + ssm = StructureSelectionManager.getStructureSelectionManager(); + for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++) + { + String fileName = modelfilenames[modelnum]; + if (fileName != null) + { + // search pdbentries and sequences to find correct pdbentry and + // sequence[] pair for this filename + if (pdbentry != null) + { + boolean foundEntry = false; + for (int pe = 0; pe < pdbentry.length; pe++) + { + if (pdbentry[pe].getFile().equals(fileName)) + { + foundEntry = true; + MCview.PDBfile pdb; + if (loadedInline) + { + // TODO: replace with getData ? + pdb = ssm.setMapping(sequence, chains, pdbentry[pe] + .getFile(), AppletFormatAdapter.PASTE); + pdbentry[pe].setFile("INLINE" + pdb.id); + } + else + { + // TODO: Jmol can in principle retrieve from CLASSLOADER but + // this + // needs + // to be tested. See mantis bug + // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605 + + pdb = ssm.setMapping(sequence, chains, pdbentry[pe] + .getFile(), AppletFormatAdapter.URL); + + } + + pdbentry[pe].setId(pdb.id); + + for (int i = 0; i < pdb.chains.size(); i++) + { + chainNames.addElement(new String(pdb.id + ":" + + ((MCview.PDBChain) pdb.chains.elementAt(i)).id)); + } + notifyLoaded = true; + } + } + if (!foundEntry && associateNewStructs) + { + // this is a foreign pdb file that jalview doesn't know about - add + // it + // to the dataset + // and try to find a home - either on a matching sequence or as a + // new + // sequence. + String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1", + "PDB"); + // parse pdb file into a chain, etc. + // locate best match for pdb in associated views and add mapping to + // ssm + // if properly registered then notifyLoaded=true; + } + } + } + } + // FILE LOADED OK + // so finally, update the jmol bits and pieces + jmolpopup.updateComputedMenus(); + viewer + .evalStringQuiet("model 0; select backbone;restrict;cartoon;wireframe off;spacefill off"); + // register ourselves as a listener and notify the gui that it needs to + // update itself. + ssm.addStructureViewerListener(this); + if (notifyLoaded) + { + updateUI(); + } + + } + + public void notifyNewPickingModeMeasurement(int iatom, String strMeasure) + { + notifyAtomPicked(iatom, strMeasure, null); + } + + public void notifyScriptTermination(String strStatus, int msWalltime) + { + } + + /** + * display a message echoed from the jmol viewer + * + * @param strEcho + */ + public abstract void sendConsoleEcho(String strEcho); /* + * { showConsole(true); + * + * history.append("\n" + + * strEcho); } + */ + + // /End JmolStatusListener + // ///////////////////////////// + + /** + * @param strStatus + * status message - usually the response received after a script + * executed + */ + public abstract void sendConsoleMessage(String strStatus); + + public void setCallbackFunction(String callbackType, + String callbackFunction) + { + System.err.println("Ignoring set-callback request to associate " + + callbackType + " with function " + callbackFunction); + + } + + public void setJalviewColourScheme(ColourSchemeI cs) + { + colourBySequence = false; + + if (cs == null) + return; + + String res; + int index; + Color col; + jmolHistory(false); + + Enumeration en = ResidueProperties.aa3Hash.keys(); + StringBuffer command = new StringBuffer("select *;color white;"); + while (en.hasMoreElements()) + { + res = en.nextElement().toString(); + index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue(); + if (index > 20) + continue; + + col = cs.findColour(ResidueProperties.aa[index].charAt(0)); + + command.append("select " + res + ";color[" + col.getRed() + "," + + col.getGreen() + "," + col.getBlue() + "];"); + } + + viewer.evalStringQuiet(command.toString()); + jmolHistory(true); + } + + public void showHelp() + { + showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp"); + } + + /** + * open the URL somehow + * + * @param target + */ + public abstract void showUrl(String url, String target); + + /** + * called when the binding thinks the UI needs to be refreshed after a Jmol + * state change. this could be because structures were loaded, or because an + * error has occured. + */ + abstract void updateUI(); + +}