2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3 * Copyright (C) 2008 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 loadingFromArchive = true;
78 pdbentry = new PDBEntry();
79 pdbentry.setFile(file);
84 this.setBounds(bounds);
85 colourBySequence = false;
86 seqColour.setSelected(false);
88 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
89 // bounds.width,bounds.height);
93 this.addInternalFrameListener(new InternalFrameAdapter()
95 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
102 public synchronized void addSequence(SequenceI[] seq)
104 Vector v = new Vector();
105 for (int i = 0; i < sequence.length; i++)
106 v.addElement(sequence[i]);
108 for (int i = 0; i < seq.length; i++)
109 if (!v.contains(seq[i]))
110 v.addElement(seq[i]);
112 SequenceI[] tmp = new SequenceI[v.size()];
117 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
120 // ////////////////////////////////
121 // Is the pdb file already loaded?
122 String alreadyMapped = StructureSelectionManager
123 .getStructureSelectionManager().alreadyMappedToFile(
126 if (alreadyMapped != null)
128 int option = JOptionPane
129 .showInternalConfirmDialog(
132 + " is already displayed."
133 + "\nDo you want to map sequences to the visible structure?",
134 "Map Sequences to Visible Window: "
135 + pdbentry.getId(), JOptionPane.YES_NO_OPTION);
137 if (option == JOptionPane.YES_OPTION)
139 StructureSelectionManager.getStructureSelectionManager()
140 .setMapping(seq, chains, alreadyMapped,
141 AppletFormatAdapter.FILE);
142 if (ap.seqPanel.seqCanvas.fr != null)
144 ap.seqPanel.seqCanvas.fr.featuresAdded();
145 ap.paintAlignment(true);
148 // Now this AppJmol is mapped to new sequences. We must add them to
149 // the exisiting array
150 JInternalFrame[] frames = Desktop.instance.getAllFrames();
152 for (int i = 0; i < frames.length; i++)
154 if (frames[i] instanceof AppJmol)
156 AppJmol topJmol = ((AppJmol) frames[i]);
157 if (topJmol.pdbentry.getFile().equals(alreadyMapped))
159 topJmol.addSequence(seq);
168 // /////////////////////////////////
171 this.pdbentry = pdbentry;
173 this.setSize(400, 400);
174 // jalview.gui.Desktop.addInternalFrame(this, "Jmol
175 // View"+(pdbentry.getId()!=null ? "for "+pdbentry.getId()
178 if (pdbentry.getFile() != null)
180 initJmol("load \"" + pdbentry.getFile() + "\"");
184 Thread worker = new Thread(this);
188 this.addInternalFrameListener(new InternalFrameAdapter()
190 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
197 void initJmol(String command)
199 renderPanel = new RenderPanel();
201 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
203 StringBuffer title = new StringBuffer(sequence[0].getName() + ":"
206 if (pdbentry.getProperty() != null)
208 if (pdbentry.getProperty().get("method") != null)
210 title.append(" Method: ");
211 title.append(pdbentry.getProperty().get("method"));
213 if (pdbentry.getProperty().get("chains") != null)
215 title.append(" Chain:");
216 title.append(pdbentry.getProperty().get("chains"));
220 this.setTitle(title.toString());
221 jalview.gui.Desktop.addInternalFrame(this, title.toString(),
222 getBounds().width, getBounds().height);
224 viewer = org.jmol.api.JmolViewer.allocateViewer(renderPanel,
225 new SmarterJmolAdapter());
227 viewer.setAppletContext("", null, null, "");
229 viewer.setJmolStatusListener(this);
231 jmolpopup = JmolPopup.newJmolPopup(viewer);
233 viewer.evalStringQuiet(command);
236 void setChainMenuItems(Vector chains)
238 chainMenu.removeAll();
240 JMenuItem menuItem = new JMenuItem("All");
241 menuItem.addActionListener(new ActionListener()
243 public void actionPerformed(ActionEvent evt)
245 allChainsSelected = true;
246 for (int i = 0; i < chainMenu.getItemCount(); i++)
248 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
249 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
252 allChainsSelected = false;
256 chainMenu.add(menuItem);
258 for (int c = 0; c < chains.size(); c++)
260 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
261 menuItem.addItemListener(new ItemListener()
263 public void itemStateChanged(ItemEvent evt)
265 if (!allChainsSelected)
270 chainMenu.add(menuItem);
274 boolean allChainsSelected = false;
278 StringBuffer cmd = new StringBuffer();
279 for (int i = 0; i < chainMenu.getItemCount(); i++)
281 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
283 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
284 if (item.isSelected())
285 cmd.append(":" + item.getText() + " or ");
289 if (cmd.length() > 0)
290 cmd.setLength(cmd.length() - 4);
292 viewer.evalStringQuiet("select *;restrict " + cmd + ";cartoon;center "
298 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
299 viewer.evalStringQuiet("zap");
300 viewer.setJmolStatusListener(null);
303 // We'll need to find out what other
304 // listeners need to be shut down in Jmol
305 StructureSelectionManager.getStructureSelectionManager()
306 .removeStructureViewerListener(this, pdbentry.getFile());
313 EBIFetchClient ebi = new EBIFetchClient();
314 String query = "pdb:" + pdbentry.getId();
315 pdbentry.setFile(ebi.fetchDataAsFile(query, "default", "raw")
317 initJmol("load " + pdbentry.getFile());
318 } catch (OutOfMemoryError oomerror)
320 new OOMWarning("Retrieving PDB id " + pdbentry.getId() + " from MSD",
322 } catch (Exception ex)
324 ex.printStackTrace();
328 public void pdbFile_actionPerformed(ActionEvent actionEvent)
330 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
331 .getProperty("LAST_DIRECTORY"));
333 chooser.setFileView(new JalviewFileView());
334 chooser.setDialogTitle("Save PDB File");
335 chooser.setToolTipText("Save");
337 int value = chooser.showSaveDialog(this);
339 if (value == JalviewFileChooser.APPROVE_OPTION)
343 BufferedReader in = new BufferedReader(new FileReader(pdbentry
345 File outFile = chooser.getSelectedFile();
347 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
349 while ((data = in.readLine()) != null)
351 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
357 } catch (Exception ex)
359 ex.printStackTrace();
364 public void viewMapping_actionPerformed(ActionEvent actionEvent)
366 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
367 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
369 cap.setText(StructureSelectionManager.getStructureSelectionManager()
370 .printMapping(pdbentry.getFile()));
379 public void eps_actionPerformed(ActionEvent e)
381 makePDBImage(jalview.util.ImageMaker.EPS);
390 public void png_actionPerformed(ActionEvent e)
392 makePDBImage(jalview.util.ImageMaker.PNG);
395 void makePDBImage(int type)
397 int width = getWidth();
398 int height = getHeight();
400 jalview.util.ImageMaker im;
402 if (type == jalview.util.ImageMaker.PNG)
404 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
405 "Make PNG image from view", width, height, null, null);
409 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
410 "Make EPS file from view", width, height, null, this
414 if (im.getGraphics() != null)
416 Rectangle rect = new Rectangle(width, height);
417 viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
422 public void seqColour_actionPerformed(ActionEvent actionEvent)
425 colourBySequence = seqColour.isSelected();
426 colourBySequence(ap.alignFrame.alignPanel);
429 public void chainColour_actionPerformed(ActionEvent actionEvent)
431 colourBySequence = false;
432 seqColour.setSelected(false);
433 viewer.evalStringQuiet("select *;color chain");
436 public void chargeColour_actionPerformed(ActionEvent actionEvent)
438 colourBySequence = false;
439 seqColour.setSelected(false);
440 viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
441 + "select LYS,ARG;color blue;select CYS;color yellow");
444 public void zappoColour_actionPerformed(ActionEvent actionEvent)
446 setJalviewColourScheme(new ZappoColourScheme());
449 public void taylorColour_actionPerformed(ActionEvent actionEvent)
451 setJalviewColourScheme(new TaylorColourScheme());
454 public void hydroColour_actionPerformed(ActionEvent actionEvent)
456 setJalviewColourScheme(new HydrophobicColourScheme());
459 public void helixColour_actionPerformed(ActionEvent actionEvent)
461 setJalviewColourScheme(new HelixColourScheme());
464 public void strandColour_actionPerformed(ActionEvent actionEvent)
466 setJalviewColourScheme(new StrandColourScheme());
469 public void turnColour_actionPerformed(ActionEvent actionEvent)
471 setJalviewColourScheme(new TurnColourScheme());
474 public void buriedColour_actionPerformed(ActionEvent actionEvent)
476 setJalviewColourScheme(new BuriedColourScheme());
479 public void setJalviewColourScheme(ColourSchemeI cs)
481 colourBySequence = false;
482 seqColour.setSelected(false);
491 Enumeration en = ResidueProperties.aa3Hash.keys();
492 StringBuffer command = new StringBuffer("select *;color white;");
493 while (en.hasMoreElements())
495 res = en.nextElement().toString();
496 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
500 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
502 command.append("select " + res + ";color[" + col.getRed() + ","
503 + col.getGreen() + "," + col.getBlue() + "];");
506 viewer.evalStringQuiet(command.toString());
509 public void userColour_actionPerformed(ActionEvent actionEvent)
511 new UserDefinedColours(this, null);
514 public void backGround_actionPerformed(ActionEvent actionEvent)
516 java.awt.Color col = JColorChooser.showDialog(this,
517 "Select Background Colour", null);
521 viewer.evalStringQuiet("background [" + col.getRed() + ","
522 + col.getGreen() + "," + col.getBlue() + "];");
526 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
530 jalview.util.BrowserLauncher
531 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
532 } catch (Exception ex)
537 // ////////////////////////////////
538 // /StructureListener
539 public String getPdbFile()
541 return pdbentry.getFile();
544 Pattern pattern = Pattern
545 .compile("\\[(.*)\\]([0-9]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?");
549 public void mouseOverStructure(int atomIndex, String strInfo)
551 Matcher matcher = pattern.matcher(strInfo);
554 int pdbResNum = Integer.parseInt(matcher.group(2));
555 String chainId = matcher.group(3);
558 chainId = chainId.substring(1, chainId.length());
564 if (lastMessage == null || !lastMessage.equals(strInfo))
566 ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile());
568 lastMessage = strInfo;
571 StringBuffer resetLastRes = new StringBuffer();
573 StringBuffer eval = new StringBuffer();
575 public void highlightAtom(int atomIndex, int pdbResNum, String chain,
578 if (!pdbfile.equals(pdbentry.getFile()))
581 if (resetLastRes.length() > 0)
583 viewer.evalStringQuiet(resetLastRes.toString());
587 eval.append("select " + pdbResNum);
589 resetLastRes.setLength(0);
590 resetLastRes.append("select " + pdbResNum);
592 if (!chain.equals(" "))
594 eval.append(":" + chain);
595 resetLastRes.append(":" + chain);
598 eval.append(";wireframe 100;" + eval.toString() + ".CA;");
600 resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
601 + ".CA;spacefill 0;");
603 eval.append("spacefill 200;select none");
605 viewer.evalStringQuiet(eval.toString());
608 public Color getColour(int atomIndex, int pdbResNum, String chain,
611 if (!pdbfile.equals(pdbentry.getFile()))
614 return new Color(viewer.getAtomArgb(atomIndex));
617 public void updateColours(Object source)
619 colourBySequence((AlignmentPanel) source);
622 // End StructureListener
623 // //////////////////////////
627 FeatureRenderer fr = null;
629 public void colourBySequence(AlignmentPanel sourceap)
633 if (!colourBySequence || ap.alignFrame.getCurrentView() != ap.av)
636 StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
638 if (mapping.length < 1)
641 SequenceRenderer sr = new SequenceRenderer(ap.av);
643 boolean showFeatures = false;
645 if (ap.av.showSequenceFeatures)
650 fr = new jalview.gui.FeatureRenderer(ap);
653 fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
656 StringBuffer command = new StringBuffer();
659 for (int sp, s = 0; s < sequence.length; s++)
661 for (int m = 0; m < mapping.length; m++)
663 if (mapping[m].getSequence() == sequence[s]
664 && (sp = ap.av.alignment.findIndex(sequence[s])) > -1)
666 SequenceI asp = ap.av.alignment.getSequenceAt(sp);
667 for (int r = 0; r < asp.getLength(); r++)
669 // No mapping to gaps in sequence.
670 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
674 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
676 if (pos < 1 || pos == lastPos)
681 Color col = sr.getResidueBoxColour(asp, r);
684 col = fr.findFeatureColour(col, asp, r);
686 if (command.toString().endsWith(
687 ":" + mapping[m].getChain() + ";color[" + col.getRed()
688 + "," + col.getGreen() + "," + col.getBlue()
691 command = condenseCommand(command, pos);
695 command.append(";select " + pos);
697 if (!mapping[m].getChain().equals(" "))
699 command.append(":" + mapping[m].getChain());
702 command.append(";color[" + col.getRed() + "," + col.getGreen()
703 + "," + col.getBlue() + "]");
711 if (lastCommand == null || !lastCommand.equals(command.toString()))
713 viewer.evalStringQuiet(command.toString());
715 lastCommand = command.toString();
718 StringBuffer condenseCommand(StringBuffer command, int pos)
720 StringBuffer sb = new StringBuffer(command.substring(0, command
721 .lastIndexOf("select") + 7));
723 command.delete(0, sb.length());
727 if (command.indexOf("-") > -1)
729 start = command.substring(0, command.indexOf("-"));
733 start = command.substring(0, command.indexOf(":"));
736 sb.append(start + "-" + pos + command.substring(command.indexOf(":")));
741 // ///////////////////////////////
742 // JmolStatusListener
744 public String eval(String strEval)
746 // System.out.println(strEval);
747 // "# 'eval' is implemented only for the applet.";
751 public void createImage(String file, String type, int quality)
753 System.out.println("JMOL CREATE IMAGE");
756 public void setCallbackFunction(String callbackType,
757 String callbackFunction)
761 public void notifyFileLoaded(String fullPathName, String fileName,
762 String modelName, Object clientFile, String errorMsg)
764 if (errorMsg != null)
766 fileLoadingError = errorMsg;
771 fileLoadingError = null;
773 if (fileName != null)
777 ssm = StructureSelectionManager.getStructureSelectionManager();
778 MCview.PDBfile pdbFile = ssm.setMapping(sequence, chains, pdbentry
779 .getFile(), AppletFormatAdapter.FILE);
780 ssm.addStructureViewerListener(this);
781 Vector chains = new Vector();
782 for (int i = 0; i < pdbFile.chains.size(); i++)
785 .addElement(((MCview.PDBChain) pdbFile.chains.elementAt(i)).id);
787 setChainMenuItems(chains);
789 jmolpopup.updateComputedMenus();
791 if (!loadingFromArchive)
794 .evalStringQuiet("select backbone;restrict;cartoon;wireframe off;spacefill off");
796 colourBySequence(ap);
801 loadingFromArchive = false;
807 public void notifyFrameChanged(int frameNo)
809 boolean isAnimationRunning = (frameNo <= -2);
812 public void notifyScriptStart(String statusMessage, String additionalInfo)
816 public void sendConsoleEcho(String strEcho)
818 if (scriptWindow != null)
819 scriptWindow.sendConsoleEcho(strEcho);
822 public void sendConsoleMessage(String strStatus)
824 if (scriptWindow != null)
825 scriptWindow.sendConsoleMessage(strStatus);
828 public void notifyScriptTermination(String strStatus, int msWalltime)
830 if (scriptWindow != null)
831 scriptWindow.notifyScriptTermination(strStatus, msWalltime);
834 public void handlePopupMenu(int x, int y)
836 jmolpopup.show(x, y);
839 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
841 notifyAtomPicked(iatom, strMeasure);
844 public void notifyNewDefaultModeMeasurement(int count, String strInfo)
848 public void notifyAtomPicked(int atomIndex, String strInfo)
850 Matcher matcher = pattern.matcher(strInfo);
854 String resnum = new String(matcher.group(2));
855 String chainId = matcher.group(3);
857 String picked = resnum;
860 picked += (":" + chainId.substring(1, chainId.length()));
864 if (!atomsPicked.contains(picked))
867 viewer.evalString("select " + picked + ";label %n %r:%c");
869 viewer.evalString("select " + picked + ";label %n %r");
870 atomsPicked.addElement(picked);
874 viewer.evalString("select " + picked + ";label off");
875 atomsPicked.removeElement(picked);
878 if (scriptWindow != null)
880 scriptWindow.sendConsoleMessage(strInfo);
881 scriptWindow.sendConsoleMessage("\n");
885 public void notifyAtomHovered(int atomIndex, String strInfo)
887 mouseOverStructure(atomIndex, strInfo);
890 public void sendSyncScript(String script, String appletName)
894 public void showUrl(String url)
898 public void showConsole(boolean showConsole)
900 if (scriptWindow == null)
901 scriptWindow = new ScriptWindow(this);
905 if (splitPane == null)
907 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
908 splitPane.setTopComponent(renderPanel);
909 splitPane.setBottomComponent(scriptWindow);
910 this.getContentPane().add(splitPane, BorderLayout.CENTER);
913 splitPane.setDividerLocation(getHeight() - 200);
914 splitPane.validate();
918 if (splitPane != null)
919 splitPane.setVisible(false);
923 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
929 public float functionXY(String functionName, int x, int y)
934 // /End JmolStatusListener
935 // /////////////////////////////
937 class RenderPanel extends JPanel
939 final Dimension currentSize = new Dimension();
941 final Rectangle rectClip = new Rectangle();
943 public void paintComponent(Graphics g)
945 getSize(currentSize);
946 g.getClipBounds(rectClip);
950 g.setColor(Color.black);
951 g.fillRect(0, 0, currentSize.width, currentSize.height);
952 g.setColor(Color.white);
953 g.setFont(new Font("Verdana", Font.BOLD, 14));
954 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
956 else if (fileLoadingError != null)
958 g.setColor(Color.black);
959 g.fillRect(0, 0, currentSize.width, currentSize.height);
960 g.setColor(Color.white);
961 g.setFont(new Font("Verdana", Font.BOLD, 14));
962 g.drawString("Error loading file..." + pdbentry.getId(), 20,
963 currentSize.height / 2);
967 viewer.renderScreenImage(g, currentSize, rectClip);