2 * Jalview - A Sequence Alignment Editor and Viewer (Development Version 2.4.1)
3 * Copyright (C) 2009 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 import java.util.regex.*;
25 import javax.swing.event.*;
26 import java.awt.event.*;
29 import jalview.jbgui.GStructureViewer;
30 import jalview.datamodel.*;
32 import jalview.structure.*;
33 import jalview.datamodel.PDBEntry;
35 import jalview.schemes.*;
36 import jalview.ws.ebi.EBIFetchClient;
38 import org.jmol.api.*;
39 import org.jmol.adapter.smarter.SmarterJmolAdapter;
40 import org.jmol.popup.*;
42 public class AppJmol extends GStructureViewer implements StructureListener,
43 JmolStatusListener, Runnable
50 ScriptWindow scriptWindow;
58 StructureSelectionManager ssm;
62 RenderPanel renderPanel;
66 String fileLoadingError;
68 boolean colourBySequence = true;
70 boolean loadingFromArchive = false;
72 Vector atomsPicked = new Vector();
74 public AppJmol(String file, String id, SequenceI[] seq,
75 AlignmentPanel ap, String loadStatus, Rectangle bounds)
77 this(file, id, seq, ap, loadStatus, bounds, null);
80 public AppJmol(String file, String id, SequenceI[] seq,
81 AlignmentPanel ap, String loadStatus, Rectangle bounds,
84 loadingFromArchive = true;
85 pdbentry = new PDBEntry();
86 pdbentry.setFile(file);
91 this.setBounds(bounds);
92 colourBySequence = false;
93 seqColour.setSelected(false);
95 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
96 // bounds.width,bounds.height);
100 this.addInternalFrameListener(new InternalFrameAdapter()
102 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
109 public synchronized void addSequence(SequenceI[] seq)
111 Vector v = new Vector();
112 for (int i = 0; i < sequence.length; i++)
113 v.addElement(sequence[i]);
115 for (int i = 0; i < seq.length; i++)
116 if (!v.contains(seq[i]))
117 v.addElement(seq[i]);
119 SequenceI[] tmp = new SequenceI[v.size()];
124 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
127 // ////////////////////////////////
128 // Is the pdb file already loaded?
129 String alreadyMapped = StructureSelectionManager
130 .getStructureSelectionManager().alreadyMappedToFile(
133 if (alreadyMapped != null)
135 int option = JOptionPane
136 .showInternalConfirmDialog(
139 + " is already displayed."
140 + "\nDo you want to map sequences to the visible structure?",
141 "Map Sequences to Visible Window: "
142 + pdbentry.getId(), JOptionPane.YES_NO_OPTION);
144 if (option == JOptionPane.YES_OPTION)
146 StructureSelectionManager.getStructureSelectionManager()
147 .setMapping(seq, chains, alreadyMapped,
148 AppletFormatAdapter.FILE);
149 if (ap.seqPanel.seqCanvas.fr != null)
151 ap.seqPanel.seqCanvas.fr.featuresAdded();
152 ap.paintAlignment(true);
155 // Now this AppJmol is mapped to new sequences. We must add them to
156 // the exisiting array
157 JInternalFrame[] frames = Desktop.instance.getAllFrames();
159 for (int i = 0; i < frames.length; i++)
161 if (frames[i] instanceof AppJmol)
163 AppJmol topJmol = ((AppJmol) frames[i]);
164 if (topJmol.pdbentry.getFile().equals(alreadyMapped))
166 topJmol.addSequence(seq);
175 // /////////////////////////////////
178 this.pdbentry = pdbentry;
180 this.setSize(400, 400);
181 // jalview.gui.Desktop.addInternalFrame(this, "Jmol
182 // View"+(pdbentry.getId()!=null ? "for "+pdbentry.getId()
185 if (pdbentry.getFile() != null)
187 initJmol("load \"" + pdbentry.getFile() + "\"");
191 Thread worker = new Thread(this);
195 this.addInternalFrameListener(new InternalFrameAdapter()
197 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
204 void initJmol(String command)
206 renderPanel = new RenderPanel();
208 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
210 StringBuffer title = new StringBuffer(sequence[0].getName() + ":"
213 if (pdbentry.getProperty() != null)
215 if (pdbentry.getProperty().get("method") != null)
217 title.append(" Method: ");
218 title.append(pdbentry.getProperty().get("method"));
220 if (pdbentry.getProperty().get("chains") != null)
222 title.append(" Chain:");
223 title.append(pdbentry.getProperty().get("chains"));
227 this.setTitle(title.toString());
228 jalview.gui.Desktop.addInternalFrame(this, title.toString(),
229 getBounds().width, getBounds().height);
231 viewer = org.jmol.api.JmolViewer.allocateViewer(renderPanel,
232 new SmarterJmolAdapter());
234 viewer.setAppletContext("", null, null, "");
236 viewer.setJmolStatusListener(this);
238 jmolpopup = JmolPopup.newJmolPopup(viewer);
240 viewer.evalStringQuiet(command);
243 void setChainMenuItems(Vector chains)
245 chainMenu.removeAll();
247 JMenuItem menuItem = new JMenuItem("All");
248 menuItem.addActionListener(new ActionListener()
250 public void actionPerformed(ActionEvent evt)
252 allChainsSelected = true;
253 for (int i = 0; i < chainMenu.getItemCount(); i++)
255 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
256 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
259 allChainsSelected = false;
263 chainMenu.add(menuItem);
265 for (int c = 0; c < chains.size(); c++)
267 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
268 menuItem.addItemListener(new ItemListener()
270 public void itemStateChanged(ItemEvent evt)
272 if (!allChainsSelected)
277 chainMenu.add(menuItem);
281 boolean allChainsSelected = false;
285 StringBuffer cmd = new StringBuffer();
286 for (int i = 0; i < chainMenu.getItemCount(); i++)
288 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
290 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
291 if (item.isSelected())
292 cmd.append(":" + item.getText() + " or ");
296 if (cmd.length() > 0)
297 cmd.setLength(cmd.length() - 4);
299 viewer.evalStringQuiet("select *;restrict " + cmd + ";cartoon;center "
305 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
306 viewer.evalStringQuiet("zap");
307 viewer.setJmolStatusListener(null);
310 // We'll need to find out what other
311 // listeners need to be shut down in Jmol
312 StructureSelectionManager.getStructureSelectionManager()
313 .removeStructureViewerListener(this, pdbentry.getFile());
320 // TODO: replace with reference fetching/transfer code (validate PDBentry as a DBRef?)
321 jalview.ws.dbsources.Pdb pdbclient = new jalview.ws.dbsources.Pdb();
323 if ((pdbseq=pdbclient.getSequenceRecords(pdbentry.getId())) != null)
325 // just transfer the file name from the first seuqence's first PDBEntry
326 pdbentry.setFile(((PDBEntry) pdbseq.getSequenceAt(0).getPDBId().elementAt(0)).getFile());
327 initJmol("load " + pdbentry.getFile());
332 .showInternalMessageDialog(
335 + " could not be retrieved. Please try downloading the file manually.",
336 "Couldn't load file", JOptionPane.ERROR_MESSAGE);
339 } catch (OutOfMemoryError oomerror)
341 new OOMWarning("Retrieving PDB id " + pdbentry.getId() + " from MSD",
343 } catch (Exception ex)
345 ex.printStackTrace();
349 public void pdbFile_actionPerformed(ActionEvent actionEvent)
351 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
352 .getProperty("LAST_DIRECTORY"));
354 chooser.setFileView(new JalviewFileView());
355 chooser.setDialogTitle("Save PDB File");
356 chooser.setToolTipText("Save");
358 int value = chooser.showSaveDialog(this);
360 if (value == JalviewFileChooser.APPROVE_OPTION)
364 BufferedReader in = new BufferedReader(new FileReader(pdbentry
366 File outFile = chooser.getSelectedFile();
368 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
370 while ((data = in.readLine()) != null)
372 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
378 } catch (Exception ex)
380 ex.printStackTrace();
385 public void viewMapping_actionPerformed(ActionEvent actionEvent)
387 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
388 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
390 cap.setText(StructureSelectionManager.getStructureSelectionManager()
391 .printMapping(pdbentry.getFile()));
400 public void eps_actionPerformed(ActionEvent e)
402 makePDBImage(jalview.util.ImageMaker.EPS);
411 public void png_actionPerformed(ActionEvent e)
413 makePDBImage(jalview.util.ImageMaker.PNG);
416 void makePDBImage(int type)
418 int width = getWidth();
419 int height = getHeight();
421 jalview.util.ImageMaker im;
423 if (type == jalview.util.ImageMaker.PNG)
425 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
426 "Make PNG image from view", width, height, null, null);
430 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
431 "Make EPS file from view", width, height, null, this
435 if (im.getGraphics() != null)
437 Rectangle rect = new Rectangle(width, height);
438 viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
443 public void seqColour_actionPerformed(ActionEvent actionEvent)
446 colourBySequence = seqColour.isSelected();
447 colourBySequence(ap.alignFrame.alignPanel);
450 public void chainColour_actionPerformed(ActionEvent actionEvent)
452 colourBySequence = false;
453 seqColour.setSelected(false);
454 viewer.evalStringQuiet("select *;color chain");
457 public void chargeColour_actionPerformed(ActionEvent actionEvent)
459 colourBySequence = false;
460 seqColour.setSelected(false);
461 viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
462 + "select LYS,ARG;color blue;select CYS;color yellow");
465 public void zappoColour_actionPerformed(ActionEvent actionEvent)
467 setJalviewColourScheme(new ZappoColourScheme());
470 public void taylorColour_actionPerformed(ActionEvent actionEvent)
472 setJalviewColourScheme(new TaylorColourScheme());
475 public void hydroColour_actionPerformed(ActionEvent actionEvent)
477 setJalviewColourScheme(new HydrophobicColourScheme());
480 public void helixColour_actionPerformed(ActionEvent actionEvent)
482 setJalviewColourScheme(new HelixColourScheme());
485 public void strandColour_actionPerformed(ActionEvent actionEvent)
487 setJalviewColourScheme(new StrandColourScheme());
490 public void turnColour_actionPerformed(ActionEvent actionEvent)
492 setJalviewColourScheme(new TurnColourScheme());
495 public void buriedColour_actionPerformed(ActionEvent actionEvent)
497 setJalviewColourScheme(new BuriedColourScheme());
500 public void setJalviewColourScheme(ColourSchemeI cs)
502 colourBySequence = false;
503 seqColour.setSelected(false);
512 Enumeration en = ResidueProperties.aa3Hash.keys();
513 StringBuffer command = new StringBuffer("select *;color white;");
514 while (en.hasMoreElements())
516 res = en.nextElement().toString();
517 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
521 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
523 command.append("select " + res + ";color[" + col.getRed() + ","
524 + col.getGreen() + "," + col.getBlue() + "];");
527 viewer.evalStringQuiet(command.toString());
530 public void userColour_actionPerformed(ActionEvent actionEvent)
532 new UserDefinedColours(this, null);
535 public void backGround_actionPerformed(ActionEvent actionEvent)
537 java.awt.Color col = JColorChooser.showDialog(this,
538 "Select Background Colour", null);
542 viewer.evalStringQuiet("background [" + col.getRed() + ","
543 + col.getGreen() + "," + col.getBlue() + "];");
547 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
551 jalview.util.BrowserLauncher
552 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
553 } catch (Exception ex)
558 // ////////////////////////////////
559 // /StructureListener
560 public String getPdbFile()
562 return pdbentry.getFile();
565 Pattern pattern = Pattern
566 .compile("\\[(.*)\\]([0-9]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?");
570 public void mouseOverStructure(int atomIndex, String strInfo)
572 Matcher matcher = pattern.matcher(strInfo);
575 int pdbResNum = Integer.parseInt(matcher.group(2));
576 String chainId = matcher.group(3);
579 chainId = chainId.substring(1, chainId.length());
585 if (lastMessage == null || !lastMessage.equals(strInfo))
587 ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile());
589 lastMessage = strInfo;
592 StringBuffer resetLastRes = new StringBuffer();
594 StringBuffer eval = new StringBuffer();
596 public void highlightAtom(int atomIndex, int pdbResNum, String chain,
599 // TODO: rna: remove CA dependency in select string
600 if (!pdbfile.equals(pdbentry.getFile()))
603 if (resetLastRes.length() > 0)
605 viewer.evalStringQuiet(resetLastRes.toString());
609 eval.append("select " + pdbResNum);
611 resetLastRes.setLength(0);
612 resetLastRes.append("select " + pdbResNum);
615 resetLastRes.append(":");
616 if (!chain.equals(" "))
619 resetLastRes.append(chain);
622 eval.append(";wireframe 100;" + eval.toString() + " and not hetero;"); // ".*;");
624 resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
625 //+ ".*;spacefill 0;");
626 + " and not hetero;spacefill 0;");
628 eval.append("spacefill 200;select none");
629 // System.out.println("jmol:\n"+eval+"\n");
630 viewer.evalStringQuiet(eval.toString());
633 public Color getColour(int atomIndex, int pdbResNum, String chain,
636 if (!pdbfile.equals(pdbentry.getFile()))
639 return new Color(viewer.getAtomArgb(atomIndex));
642 public void updateColours(Object source)
644 colourBySequence((AlignmentPanel) source);
647 // End StructureListener
648 // //////////////////////////
652 FeatureRenderer fr = null;
654 public void colourBySequence(AlignmentPanel sourceap)
658 if (!colourBySequence || ap.alignFrame.getCurrentView() != ap.av)
661 StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
663 if (mapping.length < 1)
666 SequenceRenderer sr = new SequenceRenderer(ap.av);
668 boolean showFeatures = false;
670 if (ap.av.showSequenceFeatures)
675 fr = new jalview.gui.FeatureRenderer(ap);
678 fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
681 StringBuffer command = new StringBuffer();
684 for (int sp, s = 0; s < sequence.length; s++)
686 for (int m = 0; m < mapping.length; m++)
688 if (mapping[m].getSequence() == sequence[s]
689 && (sp = ap.av.alignment.findIndex(sequence[s])) > -1)
691 SequenceI asp = ap.av.alignment.getSequenceAt(sp);
692 for (int r = 0; r < asp.getLength(); r++)
694 // No mapping to gaps in sequence.
695 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
699 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
701 if (pos < 1 || pos == lastPos)
706 Color col = sr.getResidueBoxColour(asp, r);
709 col = fr.findFeatureColour(col, asp, r);
711 if (command.toString().endsWith(
712 ":" + mapping[m].getChain() + ";color[" + col.getRed()
713 + "," + col.getGreen() + "," + col.getBlue()
716 command = condenseCommand(command, pos);
720 command.append(";select " + pos);
722 if (!mapping[m].getChain().equals(" "))
724 command.append(":" + mapping[m].getChain());
727 command.append(";color[" + col.getRed() + "," + col.getGreen()
728 + "," + col.getBlue() + "]");
736 if (lastCommand == null || !lastCommand.equals(command.toString()))
738 viewer.evalStringQuiet(command.toString());
740 lastCommand = command.toString();
743 StringBuffer condenseCommand(StringBuffer command, int pos)
745 StringBuffer sb = new StringBuffer(command.substring(0, command
746 .lastIndexOf("select") + 7));
748 command.delete(0, sb.length());
752 if (command.indexOf("-") > -1)
754 start = command.substring(0, command.indexOf("-"));
758 start = command.substring(0, command.indexOf(":"));
761 sb.append(start + "-" + pos + command.substring(command.indexOf(":")));
766 // ///////////////////////////////
767 // JmolStatusListener
769 public String eval(String strEval)
771 // System.out.println(strEval);
772 // "# 'eval' is implemented only for the applet.";
776 public void createImage(String file, String type, int quality)
778 System.out.println("JMOL CREATE IMAGE");
781 public void setCallbackFunction(String callbackType,
782 String callbackFunction)
786 public void notifyFileLoaded(String fullPathName, String fileName,
787 String modelName, Object clientFile, String errorMsg)
789 if (errorMsg != null)
791 fileLoadingError = errorMsg;
796 fileLoadingError = null;
798 if (fileName != null)
802 ssm = StructureSelectionManager.getStructureSelectionManager();
803 MCview.PDBfile pdbFile = ssm.setMapping(sequence, chains, pdbentry
804 .getFile(), AppletFormatAdapter.FILE);
805 ssm.addStructureViewerListener(this);
806 Vector chains = new Vector();
807 for (int i = 0; i < pdbFile.chains.size(); i++)
810 .addElement(((MCview.PDBChain) pdbFile.chains.elementAt(i)).id);
812 setChainMenuItems(chains);
814 jmolpopup.updateComputedMenus();
816 if (!loadingFromArchive)
819 .evalStringQuiet("select backbone;restrict;cartoon;wireframe off;spacefill off");
821 colourBySequence(ap);
826 loadingFromArchive = false;
832 public void notifyFrameChanged(int frameNo)
834 boolean isAnimationRunning = (frameNo <= -2);
837 public void notifyScriptStart(String statusMessage, String additionalInfo)
841 public void sendConsoleEcho(String strEcho)
843 if (scriptWindow != null)
844 scriptWindow.sendConsoleEcho(strEcho);
847 public void sendConsoleMessage(String strStatus)
849 if (scriptWindow != null)
850 scriptWindow.sendConsoleMessage(strStatus);
853 public void notifyScriptTermination(String strStatus, int msWalltime)
855 if (scriptWindow != null)
856 scriptWindow.notifyScriptTermination(strStatus, msWalltime);
859 public void handlePopupMenu(int x, int y)
861 jmolpopup.show(x, y);
864 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
866 notifyAtomPicked(iatom, strMeasure);
869 public void notifyNewDefaultModeMeasurement(int count, String strInfo)
873 public void notifyAtomPicked(int atomIndex, String strInfo)
875 Matcher matcher = pattern.matcher(strInfo);
879 String resnum = new String(matcher.group(2));
880 String chainId = matcher.group(3);
882 String picked = resnum;
885 picked += (":" + chainId.substring(1, chainId.length()));
889 if (!atomsPicked.contains(picked))
892 viewer.evalString("select " + picked + ";label %n %r:%c");
894 viewer.evalString("select " + picked + ";label %n %r");
895 atomsPicked.addElement(picked);
899 viewer.evalString("select " + picked + ";label off");
900 atomsPicked.removeElement(picked);
903 if (scriptWindow != null)
905 scriptWindow.sendConsoleMessage(strInfo);
906 scriptWindow.sendConsoleMessage("\n");
910 public void notifyAtomHovered(int atomIndex, String strInfo)
912 mouseOverStructure(atomIndex, strInfo);
915 public void sendSyncScript(String script, String appletName)
919 public void showUrl(String url)
923 public void showConsole(boolean showConsole)
925 if (scriptWindow == null)
926 scriptWindow = new ScriptWindow(this);
930 if (splitPane == null)
932 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
933 splitPane.setTopComponent(renderPanel);
934 splitPane.setBottomComponent(scriptWindow);
935 this.getContentPane().add(splitPane, BorderLayout.CENTER);
938 splitPane.setDividerLocation(getHeight() - 200);
939 splitPane.validate();
943 if (splitPane != null)
944 splitPane.setVisible(false);
948 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
954 public float functionXY(String functionName, int x, int y)
959 // /End JmolStatusListener
960 // /////////////////////////////
962 class RenderPanel extends JPanel
964 final Dimension currentSize = new Dimension();
966 final Rectangle rectClip = new Rectangle();
968 public void paintComponent(Graphics g)
970 getSize(currentSize);
971 g.getClipBounds(rectClip);
975 g.setColor(Color.black);
976 g.fillRect(0, 0, currentSize.width, currentSize.height);
977 g.setColor(Color.white);
978 g.setFont(new Font("Verdana", Font.BOLD, 14));
979 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
981 else if (fileLoadingError != null)
983 g.setColor(Color.black);
984 g.fillRect(0, 0, currentSize.width, currentSize.height);
985 g.setColor(Color.white);
986 g.setFont(new Font("Verdana", Font.BOLD, 14));
987 g.drawString("Error loading file..." + pdbentry.getId(), 20,
988 currentSize.height / 2);
992 viewer.renderScreenImage(g, currentSize, rectClip);
997 String viewId = null;
999 public String getViewId()
1003 viewId = System.currentTimeMillis() + "." + this.hashCode();