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;
22 import java.awt.event.*;
24 import jalview.api.FeatureRenderer;
25 import jalview.api.SequenceRenderer;
26 import jalview.api.SequenceStructureBinding;
27 import jalview.datamodel.*;
28 import jalview.structure.*;
31 import org.jmol.api.*;
32 import org.jmol.adapter.smarter.SmarterJmolAdapter;
34 import org.jmol.popup.*;
35 import org.jmol.viewer.JmolConstants;
37 import jalview.schemes.*;
39 public abstract class JalviewJmolBinding implements StructureListener,
40 JmolStatusListener, SequenceStructureBinding
44 boolean allChainsSelected = false;
47 * when true, try to search the associated datamodel for sequences that are
48 * associated with any unknown structures in the Jmol view.
50 private boolean associateNewStructs = false;
52 Vector atomsPicked = new Vector();
54 private Vector chainNames;
58 boolean colourBySequence = true;
60 StringBuffer eval = new StringBuffer();
62 String fileLoadingError;
65 * the default or current model displayed if the model cannot be identified
66 * from the selection message
79 * current set of model filenames loaded in the Jmol instance
81 String[] modelFileNames = null;
86 * datasource protocol for access to PDBEntry
88 String protocol = null;
90 StringBuffer resetLastRes = new StringBuffer();
94 StructureSelectionManager ssm;
98 public JalviewJmolBinding(PDBEntry[] pdbentry, SequenceI[] seq,
99 String[] chains, String protocol)
102 * viewer = JmolViewer.allocateViewer(renderPanel, new SmarterJmolAdapter(),
103 * "jalviewJmol", ap.av.applet .getDocumentBase(),
104 * ap.av.applet.getCodeBase(), "", this);
106 * jmolpopup = JmolPopup.newJmolPopup(viewer, true, "Jmol", true);
111 * prepare the view for a given set of models/chains. chainList contains
112 * strings of the form 'pdbfilename:Chaincode'
115 * list of chains to make visible
117 void centerViewer(Vector chainList)
119 StringBuffer cmd = new StringBuffer();
122 for (int i = 0, iSize = chainList.size(); i < iSize; i++)
125 lbl = (String) chainList.elementAt(i);
129 mlength = lbl.indexOf(":", p);
130 } while (p < mlength && mlength < (lbl.length() - 2));
131 cmd.append(":" + lbl.substring(mlength + 1) + " /"
132 + getModelNum(lbl.substring(0, mlength)) + " or ");
134 if (cmd.length() > 0)
135 cmd.setLength(cmd.length() - 4);
139 .evalString("select *;restrict " + cmd + ";cartoon;center "
146 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
147 // remove listeners for all structures in viewer
148 StructureSelectionManager.getStructureSelectionManager()
149 .removeStructureViewerListener(this, this.getPdbFile());
150 // and shut down jmol
151 viewer.evalStringQuiet("zap");
152 viewer.setJmolStatusListener(null);
157 public void colourByChain()
160 colourBySequence = false;
161 viewer.evalStringQuiet("select *;color chain");
165 public void colourByCharge()
168 colourBySequence = false;
169 viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
170 + "select LYS,ARG;color blue;select CYS;color yellow");
175 * colour any structures associated with sequences in the given alignment
176 * using the getFeatureRenderer() and getSequenceRenderer() renderers but only
177 * if colourBySequence is enabled.
179 public void colourBySequence(boolean showFeatures, AlignmentI alignment)
181 if (!colourBySequence)
183 String[] files = getPdbFile();
184 SequenceRenderer sr = getSequenceRenderer();
186 FeatureRenderer fr = null;
189 fr = getFeatureRenderer();
192 StringBuffer command = new StringBuffer();
194 for (int pdbfnum = 0; pdbfnum < files.length; pdbfnum++)
196 StructureMapping[] mapping = ssm.getMapping(files[pdbfnum]);
198 if (mapping == null || mapping.length < 1)
202 for (int s = 0; s < sequence.length; s++)
204 for (int sp, m = 0; m < mapping.length; m++)
206 if (mapping[m].getSequence() == sequence[s]
207 && (sp = alignment.findIndex(sequence[s])) > -1)
209 SequenceI asp = alignment.getSequenceAt(sp);
210 for (int r = 0; r < asp.getLength(); r++)
212 // no mapping to gaps in sequence
213 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
217 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
219 if (pos < 1 || pos == lastPos)
224 Color col = sr.getResidueBoxColour(sequence[s], r);
227 col = fr.findFeatureColour(col, sequence[s], r);
228 String newSelcom = (mapping[m].getChain() != " " ? ":"
229 + mapping[m].getChain() : "")
238 + col.getBlue() + "]";
239 if (command.toString().endsWith(newSelcom))
241 command = condenseCommand(command.toString(), pos);
244 // TODO: deal with case when buffer is too large for Jmol to parse
245 // - execute command and flush
247 command.append(";select " + pos);
248 command.append(newSelcom);
257 if (lastCommand == null || !lastCommand.equals(command.toString()))
259 viewer.evalStringQuiet(command.toString());
262 lastCommand = command.toString();
265 StringBuffer condenseCommand(String command, int pos)
268 StringBuffer sb = new StringBuffer(command.substring(0, command
269 .lastIndexOf("select") + 7));
271 command = command.substring(sb.length());
275 if (command.indexOf("-") > -1)
277 start = command.substring(0, command.indexOf("-"));
281 start = command.substring(0, command.indexOf(":"));
284 sb.append(start + "-" + pos + command.substring(command.indexOf(":")));
289 public void createImage(String file, String type, int quality)
293 public String createImage(String fileName, String type,
294 Object textOrBytes, int quality)
296 // TODO Auto-generated method stub
300 public String eval(String strEval)
302 // System.out.println(strEval);
303 // "# 'eval' is implemented only for the applet.";
307 // End StructureListener
308 // //////////////////////////
310 public float[][] functionXY(String functionName, int x, int y)
315 public float[][][] functionXYZ(String functionName, int nx, int ny, int nz)
317 // TODO Auto-generated method stub
321 public Color getColour(int atomIndex, int pdbResNum, String chain,
324 if (getModelNum(pdbfile) < 0)
326 // TODO: verify atomIndex is selecting correct model.
327 return new Color(viewer.getAtomArgb(atomIndex));
331 * returns the current featureRenderer that should be used to colour the
336 abstract FeatureRenderer getFeatureRenderer();
338 private int getModelNum(String modelFileName)
340 String[] mfn = getPdbFile();
345 for (int i = 0; i < mfn.length; i++)
347 if (mfn[i].equalsIgnoreCase(modelFileName))
353 // ////////////////////////////////
354 // /StructureListener
355 public String[] getPdbFile()
357 if (modelFileNames == null)
359 String mset[] = new String[viewer.getModelCount()];
360 for (int i = 0; i < mset.length; i++)
362 mset[i] = viewer.getModelFileName(i);
364 modelFileNames = mset;
366 return modelFileNames;
369 public Hashtable getRegistryInfo()
371 // TODO Auto-generated method stub
376 * returns the current sequenceRenderer that should be used to colour the
381 abstract SequenceRenderer getSequenceRenderer();
383 // ///////////////////////////////
384 // JmolStatusListener
386 public void handlePopupMenu(int x, int y)
388 jmolpopup.show(x, y);
392 public void highlightAtom(int atomIndex, int pdbResNum, String chain,
395 if (modelFileNames == null)
400 // look up file model number for this pdbfile
403 // may need to adjust for URLencoding here - we don't worry about that yet.
404 while (mdlNum < modelFileNames.length
405 && !pdbfile.equals(modelFileNames[mdlNum]))
407 // System.out.println("nomatch:"+pdbfile+"\nmodelfn:"+fn);
410 if (mdlNum == modelFileNames.length)
416 // if (!pdbfile.equals(pdbentry.getFile()))
418 if (resetLastRes.length() > 0)
420 viewer.evalStringQuiet(resetLastRes.toString());
424 eval.append("select " + pdbResNum); // +modelNum
426 resetLastRes.setLength(0);
427 resetLastRes.append("select " + pdbResNum); // +modelNum
430 resetLastRes.append(":");
431 if (!chain.equals(" "))
434 resetLastRes.append(chain);
437 eval.append(" /" + (mdlNum + 1));
438 resetLastRes.append("/" + (mdlNum + 1));
440 eval.append(";wireframe 100;" + eval.toString() + " and not hetero;");
442 resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
443 + " and not hetero; spacefill 0;");
445 eval.append("spacefill 200;select none");
447 viewer.evalStringQuiet(eval.toString());
452 private void jmolHistory(boolean enable)
454 viewer.setBooleanProperty("history", enable);
457 public void loadInline(String string)
460 viewer.openStringInline(string);
463 public void mouseOverStructure(int atomIndex, String strInfo)
466 int mdlSep = strInfo.indexOf("/");
467 int chainSeparator = strInfo.indexOf(":"), chainSeparator1 = -1;
469 if (chainSeparator == -1)
471 chainSeparator = strInfo.indexOf(".");
472 if (mdlSep > -1 && mdlSep < chainSeparator)
474 chainSeparator1 = chainSeparator;
475 chainSeparator = mdlSep;
478 pdbResNum = Integer.parseInt(strInfo.substring(
479 strInfo.indexOf("]") + 1, chainSeparator));
483 if (strInfo.indexOf(":") > -1)
484 chainId = strInfo.substring(strInfo.indexOf(":") + 1, strInfo
491 String pdbfilename = modelFileNames[frameNo]; // default is first or current
495 if (chainSeparator1 == -1)
497 chainSeparator1 = strInfo.indexOf(".", mdlSep);
499 String mdlId = (chainSeparator1 > -1) ? strInfo.substring(mdlSep + 1,
500 chainSeparator1) : strInfo.substring(mdlSep + 1);
503 // recover PDB filename for the model hovered over.
505 .getModelFileName(new Integer(mdlId).intValue() - 1);
506 } catch (Exception e)
511 if (lastMessage == null || !lastMessage.equals(strInfo))
512 ssm.mouseOverStructure(pdbResNum, chainId, pdbfilename);
514 lastMessage = strInfo;
517 public void notifyAtomHovered(int atomIndex, String strInfo, String data)
521 System.err.println("Ignoring additional hover info: " + data);
523 mouseOverStructure(atomIndex, strInfo);
527 * { if (history != null && strStatus != null &&
528 * !strStatus.equals("Script completed")) { history.append("\n" + strStatus);
532 public void notifyAtomPicked(int atomIndex, String strInfo, String strData)
535 * this implements the toggle label behaviour copied from the original
536 * structure viewer, MCView
540 System.err.println("Ignoring additional pick data string " + strData);
542 int chainSeparator = strInfo.indexOf(":");
544 if (chainSeparator == -1)
545 chainSeparator = strInfo.indexOf(".");
547 String picked = strInfo.substring(strInfo.indexOf("]") + 1,
549 String mdlString = "";
550 if ((p = strInfo.indexOf(":")) > -1)
551 picked += strInfo.substring(p + 1, strInfo.indexOf("."));
553 if ((p = strInfo.indexOf("/")) > -1)
555 mdlString += strInfo.substring(p, strInfo.indexOf(" #"));
557 picked = "((" + picked + ".CA" + mdlString + ")|(" + picked + ".P"
561 if (!atomsPicked.contains(picked))
563 viewer.evalStringQuiet("select " + picked + ";label %n %r:%c");
564 atomsPicked.addElement(picked);
568 viewer.evalString("select " + picked + ";label off");
569 atomsPicked.removeElement(picked);
575 public void notifyCallback(int type, Object[] data)
581 case JmolConstants.CALLBACK_LOADSTRUCT:
582 notifyFileLoaded((String) data[1], (String) data[2],
583 (String) data[3], (String) data[4], ((Integer) data[5])
587 case JmolConstants.CALLBACK_PICK:
588 notifyAtomPicked(((Integer) data[2]).intValue(), (String) data[1],
590 // also highlight in alignment
591 case JmolConstants.CALLBACK_HOVER:
592 notifyAtomHovered(((Integer) data[2]).intValue(), (String) data[1],
595 case JmolConstants.CALLBACK_SCRIPT:
596 notifyScriptTermination((String) data[2], ((Integer) data[3])
599 case JmolConstants.CALLBACK_ECHO:
600 sendConsoleEcho((String) data[1]);
602 case JmolConstants.CALLBACK_MESSAGE:
603 sendConsoleMessage((data == null) ? ((String) null)
606 case JmolConstants.CALLBACK_MEASURE:
607 case JmolConstants.CALLBACK_CLICK:
609 System.err.println("Unhandled callback " + type + " " + data);
612 } catch (Exception e)
614 System.err.println("Squashed Jmol callback handler error:");
619 public boolean notifyEnabled(int callbackPick)
621 switch (callbackPick)
623 case JmolConstants.CALLBACK_ECHO:
624 case JmolConstants.CALLBACK_LOADSTRUCT:
625 case JmolConstants.CALLBACK_MEASURE:
626 case JmolConstants.CALLBACK_MESSAGE:
627 case JmolConstants.CALLBACK_PICK:
628 case JmolConstants.CALLBACK_SCRIPT:
629 case JmolConstants.CALLBACK_HOVER:
630 case JmolConstants.CALLBACK_ERROR:
632 case JmolConstants.CALLBACK_CLICK:
633 case JmolConstants.CALLBACK_ANIMFRAME:
634 case JmolConstants.CALLBACK_MINIMIZATION:
635 case JmolConstants.CALLBACK_RESIZE:
636 case JmolConstants.CALLBACK_SYNC:
641 public void notifyFileLoaded(String fullPathName, String fileName2,
642 String modelName, String errorMsg, int modelParts)
644 if (errorMsg != null)
646 fileLoadingError = errorMsg;
650 fileLoadingError = null;
651 modelFileNames = null;
652 chainNames = new Vector();
653 boolean notifyLoaded = false;
654 String[] modelfilenames = getPdbFile();
655 ssm = StructureSelectionManager.getStructureSelectionManager();
656 for (int modelnum = 0; modelnum < modelfilenames.length; modelnum++)
658 String fileName = modelfilenames[modelnum];
659 if (fileName != null)
661 // search pdbentries and sequences to find correct pdbentry and
662 // sequence[] pair for this filename
663 if (pdbentry != null)
665 boolean foundEntry = false;
666 for (int pe = 0; pe < pdbentry.length; pe++)
668 if (pdbentry[pe].getFile().equals(fileName))
674 // TODO: replace with getData ?
675 pdb = ssm.setMapping(sequence, chains, pdbentry[pe]
676 .getFile(), AppletFormatAdapter.PASTE);
677 pdbentry[pe].setFile("INLINE" + pdb.id);
681 // TODO: Jmol can in principle retrieve from CLASSLOADER but
684 // to be tested. See mantis bug
685 // https://mantis.lifesci.dundee.ac.uk/view.php?id=36605
687 pdb = ssm.setMapping(sequence, chains, pdbentry[pe]
688 .getFile(), AppletFormatAdapter.URL);
692 pdbentry[pe].setId(pdb.id);
694 for (int i = 0; i < pdb.chains.size(); i++)
696 chainNames.addElement(new String(pdb.id + ":"
697 + ((MCview.PDBChain) pdb.chains.elementAt(i)).id));
702 if (!foundEntry && associateNewStructs)
704 // this is a foreign pdb file that jalview doesn't know about - add
707 // and try to find a home - either on a matching sequence or as a
710 String pdbcontent = viewer.getData("/" + (modelnum + 1) + ".1",
712 // parse pdb file into a chain, etc.
713 // locate best match for pdb in associated views and add mapping to
715 // if properly registered then notifyLoaded=true;
721 // so finally, update the jmol bits and pieces
722 jmolpopup.updateComputedMenus();
724 .evalStringQuiet("model 0; select backbone;restrict;cartoon;wireframe off;spacefill off");
725 // register ourselves as a listener and notify the gui that it needs to
727 ssm.addStructureViewerListener(this);
735 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
737 notifyAtomPicked(iatom, strMeasure, null);
740 public void notifyScriptTermination(String strStatus, int msWalltime)
745 * display a message echoed from the jmol viewer
749 public abstract void sendConsoleEcho(String strEcho); /*
750 * { showConsole(true);
752 * history.append("\n" +
756 // /End JmolStatusListener
757 // /////////////////////////////
761 * status message - usually the response received after a script
764 public abstract void sendConsoleMessage(String strStatus);
766 public void setCallbackFunction(String callbackType,
767 String callbackFunction)
769 System.err.println("Ignoring set-callback request to associate "
770 + callbackType + " with function " + callbackFunction);
774 public void setJalviewColourScheme(ColourSchemeI cs)
776 colourBySequence = false;
786 Enumeration en = ResidueProperties.aa3Hash.keys();
787 StringBuffer command = new StringBuffer("select *;color white;");
788 while (en.hasMoreElements())
790 res = en.nextElement().toString();
791 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
795 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
797 command.append("select " + res + ";color[" + col.getRed() + ","
798 + col.getGreen() + "," + col.getBlue() + "];");
801 viewer.evalStringQuiet(command.toString());
805 public void showHelp()
807 showUrl("http://jmol.sourceforge.net/docs/JmolUserGuide/", "jmolHelp");
811 * open the URL somehow
815 public abstract void showUrl(String url, String target);
818 * called when the binding thinks the UI needs to be refreshed after a Jmol
819 * state change. this could be because structures were loaded, or because an
822 abstract void updateUI();