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);
79 public AppJmol(String file, String id, SequenceI[] seq,
80 AlignmentPanel ap, String loadStatus, Rectangle bounds, String viewid)
82 loadingFromArchive = true;
83 pdbentry = new PDBEntry();
84 pdbentry.setFile(file);
89 this.setBounds(bounds);
90 colourBySequence = false;
91 seqColour.setSelected(false);
93 // jalview.gui.Desktop.addInternalFrame(this, "Loading File",
94 // bounds.width,bounds.height);
98 this.addInternalFrameListener(new InternalFrameAdapter()
100 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
107 public synchronized void addSequence(SequenceI[] seq)
109 Vector v = new Vector();
110 for (int i = 0; i < sequence.length; i++)
111 v.addElement(sequence[i]);
113 for (int i = 0; i < seq.length; i++)
114 if (!v.contains(seq[i]))
115 v.addElement(seq[i]);
117 SequenceI[] tmp = new SequenceI[v.size()];
122 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String[] chains,
125 // ////////////////////////////////
126 // Is the pdb file already loaded?
127 String alreadyMapped = StructureSelectionManager
128 .getStructureSelectionManager().alreadyMappedToFile(
131 if (alreadyMapped != null)
133 int option = JOptionPane
134 .showInternalConfirmDialog(
137 + " is already displayed."
138 + "\nDo you want to map sequences to the visible structure?",
139 "Map Sequences to Visible Window: "
140 + pdbentry.getId(), JOptionPane.YES_NO_OPTION);
142 if (option == JOptionPane.YES_OPTION)
144 StructureSelectionManager.getStructureSelectionManager()
145 .setMapping(seq, chains, alreadyMapped,
146 AppletFormatAdapter.FILE);
147 if (ap.seqPanel.seqCanvas.fr != null)
149 ap.seqPanel.seqCanvas.fr.featuresAdded();
150 ap.paintAlignment(true);
153 // Now this AppJmol is mapped to new sequences. We must add them to
154 // the exisiting array
155 JInternalFrame[] frames = Desktop.instance.getAllFrames();
157 for (int i = 0; i < frames.length; i++)
159 if (frames[i] instanceof AppJmol)
161 AppJmol topJmol = ((AppJmol) frames[i]);
162 if (topJmol.pdbentry.getFile().equals(alreadyMapped))
164 topJmol.addSequence(seq);
173 // /////////////////////////////////
176 this.pdbentry = pdbentry;
178 this.setSize(400, 400);
179 // jalview.gui.Desktop.addInternalFrame(this, "Jmol
180 // View"+(pdbentry.getId()!=null ? "for "+pdbentry.getId()
183 if (pdbentry.getFile() != null)
185 initJmol("load \"" + pdbentry.getFile() + "\"");
189 Thread worker = new Thread(this);
193 this.addInternalFrameListener(new InternalFrameAdapter()
195 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
202 void initJmol(String command)
204 renderPanel = new RenderPanel();
206 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
208 StringBuffer title = new StringBuffer(sequence[0].getName() + ":"
211 if (pdbentry.getProperty() != null)
213 if (pdbentry.getProperty().get("method") != null)
215 title.append(" Method: ");
216 title.append(pdbentry.getProperty().get("method"));
218 if (pdbentry.getProperty().get("chains") != null)
220 title.append(" Chain:");
221 title.append(pdbentry.getProperty().get("chains"));
225 this.setTitle(title.toString());
226 jalview.gui.Desktop.addInternalFrame(this, title.toString(),
227 getBounds().width, getBounds().height);
229 viewer = org.jmol.api.JmolViewer.allocateViewer(renderPanel,
230 new SmarterJmolAdapter());
232 viewer.setAppletContext("", null, null, "");
234 viewer.setJmolStatusListener(this);
236 jmolpopup = JmolPopup.newJmolPopup(viewer);
238 viewer.evalStringQuiet(command);
241 void setChainMenuItems(Vector chains)
243 chainMenu.removeAll();
245 JMenuItem menuItem = new JMenuItem("All");
246 menuItem.addActionListener(new ActionListener()
248 public void actionPerformed(ActionEvent evt)
250 allChainsSelected = true;
251 for (int i = 0; i < chainMenu.getItemCount(); i++)
253 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
254 ((JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
257 allChainsSelected = false;
261 chainMenu.add(menuItem);
263 for (int c = 0; c < chains.size(); c++)
265 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
266 menuItem.addItemListener(new ItemListener()
268 public void itemStateChanged(ItemEvent evt)
270 if (!allChainsSelected)
275 chainMenu.add(menuItem);
279 boolean allChainsSelected = false;
283 StringBuffer cmd = new StringBuffer();
284 for (int i = 0; i < chainMenu.getItemCount(); i++)
286 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
288 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
289 if (item.isSelected())
290 cmd.append(":" + item.getText() + " or ");
294 if (cmd.length() > 0)
295 cmd.setLength(cmd.length() - 4);
297 viewer.evalStringQuiet("select *;restrict " + cmd + ";cartoon;center "
303 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
304 viewer.evalStringQuiet("zap");
305 viewer.setJmolStatusListener(null);
308 // We'll need to find out what other
309 // listeners need to be shut down in Jmol
310 StructureSelectionManager.getStructureSelectionManager()
311 .removeStructureViewerListener(this, pdbentry.getFile());
318 EBIFetchClient ebi = new EBIFetchClient();
319 String query = "pdb:" + pdbentry.getId();
320 pdbentry.setFile(ebi.fetchDataAsFile(query, "default", "raw")
322 initJmol("load " + pdbentry.getFile());
323 } catch (OutOfMemoryError oomerror)
325 new OOMWarning("Retrieving PDB id " + pdbentry.getId() + " from MSD",
327 } catch (Exception ex)
329 ex.printStackTrace();
333 public void pdbFile_actionPerformed(ActionEvent actionEvent)
335 JalviewFileChooser chooser = new JalviewFileChooser(jalview.bin.Cache
336 .getProperty("LAST_DIRECTORY"));
338 chooser.setFileView(new JalviewFileView());
339 chooser.setDialogTitle("Save PDB File");
340 chooser.setToolTipText("Save");
342 int value = chooser.showSaveDialog(this);
344 if (value == JalviewFileChooser.APPROVE_OPTION)
348 BufferedReader in = new BufferedReader(new FileReader(pdbentry
350 File outFile = chooser.getSelectedFile();
352 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
354 while ((data = in.readLine()) != null)
356 if (!(data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1))
362 } catch (Exception ex)
364 ex.printStackTrace();
369 public void viewMapping_actionPerformed(ActionEvent actionEvent)
371 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
372 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping",
374 cap.setText(StructureSelectionManager.getStructureSelectionManager()
375 .printMapping(pdbentry.getFile()));
384 public void eps_actionPerformed(ActionEvent e)
386 makePDBImage(jalview.util.ImageMaker.EPS);
395 public void png_actionPerformed(ActionEvent e)
397 makePDBImage(jalview.util.ImageMaker.PNG);
400 void makePDBImage(int type)
402 int width = getWidth();
403 int height = getHeight();
405 jalview.util.ImageMaker im;
407 if (type == jalview.util.ImageMaker.PNG)
409 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.PNG,
410 "Make PNG image from view", width, height, null, null);
414 im = new jalview.util.ImageMaker(this, jalview.util.ImageMaker.EPS,
415 "Make EPS file from view", width, height, null, this
419 if (im.getGraphics() != null)
421 Rectangle rect = new Rectangle(width, height);
422 viewer.renderScreenImage(im.getGraphics(), rect.getSize(), rect);
427 public void seqColour_actionPerformed(ActionEvent actionEvent)
430 colourBySequence = seqColour.isSelected();
431 colourBySequence(ap.alignFrame.alignPanel);
434 public void chainColour_actionPerformed(ActionEvent actionEvent)
436 colourBySequence = false;
437 seqColour.setSelected(false);
438 viewer.evalStringQuiet("select *;color chain");
441 public void chargeColour_actionPerformed(ActionEvent actionEvent)
443 colourBySequence = false;
444 seqColour.setSelected(false);
445 viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
446 + "select LYS,ARG;color blue;select CYS;color yellow");
449 public void zappoColour_actionPerformed(ActionEvent actionEvent)
451 setJalviewColourScheme(new ZappoColourScheme());
454 public void taylorColour_actionPerformed(ActionEvent actionEvent)
456 setJalviewColourScheme(new TaylorColourScheme());
459 public void hydroColour_actionPerformed(ActionEvent actionEvent)
461 setJalviewColourScheme(new HydrophobicColourScheme());
464 public void helixColour_actionPerformed(ActionEvent actionEvent)
466 setJalviewColourScheme(new HelixColourScheme());
469 public void strandColour_actionPerformed(ActionEvent actionEvent)
471 setJalviewColourScheme(new StrandColourScheme());
474 public void turnColour_actionPerformed(ActionEvent actionEvent)
476 setJalviewColourScheme(new TurnColourScheme());
479 public void buriedColour_actionPerformed(ActionEvent actionEvent)
481 setJalviewColourScheme(new BuriedColourScheme());
484 public void setJalviewColourScheme(ColourSchemeI cs)
486 colourBySequence = false;
487 seqColour.setSelected(false);
496 Enumeration en = ResidueProperties.aa3Hash.keys();
497 StringBuffer command = new StringBuffer("select *;color white;");
498 while (en.hasMoreElements())
500 res = en.nextElement().toString();
501 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
505 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
507 command.append("select " + res + ";color[" + col.getRed() + ","
508 + col.getGreen() + "," + col.getBlue() + "];");
511 viewer.evalStringQuiet(command.toString());
514 public void userColour_actionPerformed(ActionEvent actionEvent)
516 new UserDefinedColours(this, null);
519 public void backGround_actionPerformed(ActionEvent actionEvent)
521 java.awt.Color col = JColorChooser.showDialog(this,
522 "Select Background Colour", null);
526 viewer.evalStringQuiet("background [" + col.getRed() + ","
527 + col.getGreen() + "," + col.getBlue() + "];");
531 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
535 jalview.util.BrowserLauncher
536 .openURL("http://jmol.sourceforge.net/docs/JmolUserGuide/");
537 } catch (Exception ex)
542 // ////////////////////////////////
543 // /StructureListener
544 public String getPdbFile()
546 return pdbentry.getFile();
549 Pattern pattern = Pattern
550 .compile("\\[(.*)\\]([0-9]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?");
554 public void mouseOverStructure(int atomIndex, String strInfo)
556 Matcher matcher = pattern.matcher(strInfo);
559 int pdbResNum = Integer.parseInt(matcher.group(2));
560 String chainId = matcher.group(3);
563 chainId = chainId.substring(1, chainId.length());
569 if (lastMessage == null || !lastMessage.equals(strInfo))
571 ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile());
573 lastMessage = strInfo;
576 StringBuffer resetLastRes = new StringBuffer();
578 StringBuffer eval = new StringBuffer();
580 public void highlightAtom(int atomIndex, int pdbResNum, String chain,
583 if (!pdbfile.equals(pdbentry.getFile()))
586 if (resetLastRes.length() > 0)
588 viewer.evalStringQuiet(resetLastRes.toString());
592 eval.append("select " + pdbResNum);
594 resetLastRes.setLength(0);
595 resetLastRes.append("select " + pdbResNum);
597 if (!chain.equals(" "))
599 eval.append(":" + chain);
600 resetLastRes.append(":" + chain);
603 eval.append(";wireframe 100;" + eval.toString() + ".CA;");
605 resetLastRes.append(";wireframe 0;" + resetLastRes.toString()
606 + ".CA;spacefill 0;");
608 eval.append("spacefill 200;select none");
610 viewer.evalStringQuiet(eval.toString());
613 public Color getColour(int atomIndex, int pdbResNum, String chain,
616 if (!pdbfile.equals(pdbentry.getFile()))
619 return new Color(viewer.getAtomArgb(atomIndex));
622 public void updateColours(Object source)
624 colourBySequence((AlignmentPanel) source);
627 // End StructureListener
628 // //////////////////////////
632 FeatureRenderer fr = null;
634 public void colourBySequence(AlignmentPanel sourceap)
638 if (!colourBySequence || ap.alignFrame.getCurrentView() != ap.av)
641 StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
643 if (mapping.length < 1)
646 SequenceRenderer sr = new SequenceRenderer(ap.av);
648 boolean showFeatures = false;
650 if (ap.av.showSequenceFeatures)
655 fr = new jalview.gui.FeatureRenderer(ap);
658 fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
661 StringBuffer command = new StringBuffer();
664 for (int sp, s = 0; s < sequence.length; s++)
666 for (int m = 0; m < mapping.length; m++)
668 if (mapping[m].getSequence() == sequence[s]
669 && (sp = ap.av.alignment.findIndex(sequence[s])) > -1)
671 SequenceI asp = ap.av.alignment.getSequenceAt(sp);
672 for (int r = 0; r < asp.getLength(); r++)
674 // No mapping to gaps in sequence.
675 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
679 int pos = mapping[m].getPDBResNum(asp.findPosition(r));
681 if (pos < 1 || pos == lastPos)
686 Color col = sr.getResidueBoxColour(asp, r);
689 col = fr.findFeatureColour(col, asp, r);
691 if (command.toString().endsWith(
692 ":" + mapping[m].getChain() + ";color[" + col.getRed()
693 + "," + col.getGreen() + "," + col.getBlue()
696 command = condenseCommand(command, pos);
700 command.append(";select " + pos);
702 if (!mapping[m].getChain().equals(" "))
704 command.append(":" + mapping[m].getChain());
707 command.append(";color[" + col.getRed() + "," + col.getGreen()
708 + "," + col.getBlue() + "]");
716 if (lastCommand == null || !lastCommand.equals(command.toString()))
718 viewer.evalStringQuiet(command.toString());
720 lastCommand = command.toString();
723 StringBuffer condenseCommand(StringBuffer command, int pos)
725 StringBuffer sb = new StringBuffer(command.substring(0, command
726 .lastIndexOf("select") + 7));
728 command.delete(0, sb.length());
732 if (command.indexOf("-") > -1)
734 start = command.substring(0, command.indexOf("-"));
738 start = command.substring(0, command.indexOf(":"));
741 sb.append(start + "-" + pos + command.substring(command.indexOf(":")));
746 // ///////////////////////////////
747 // JmolStatusListener
749 public String eval(String strEval)
751 // System.out.println(strEval);
752 // "# 'eval' is implemented only for the applet.";
756 public void createImage(String file, String type, int quality)
758 System.out.println("JMOL CREATE IMAGE");
761 public void setCallbackFunction(String callbackType,
762 String callbackFunction)
766 public void notifyFileLoaded(String fullPathName, String fileName,
767 String modelName, Object clientFile, String errorMsg)
769 if (errorMsg != null)
771 fileLoadingError = errorMsg;
776 fileLoadingError = null;
778 if (fileName != null)
782 ssm = StructureSelectionManager.getStructureSelectionManager();
783 MCview.PDBfile pdbFile = ssm.setMapping(sequence, chains, pdbentry
784 .getFile(), AppletFormatAdapter.FILE);
785 ssm.addStructureViewerListener(this);
786 Vector chains = new Vector();
787 for (int i = 0; i < pdbFile.chains.size(); i++)
790 .addElement(((MCview.PDBChain) pdbFile.chains.elementAt(i)).id);
792 setChainMenuItems(chains);
794 jmolpopup.updateComputedMenus();
796 if (!loadingFromArchive)
799 .evalStringQuiet("select backbone;restrict;cartoon;wireframe off;spacefill off");
801 colourBySequence(ap);
806 loadingFromArchive = false;
812 public void notifyFrameChanged(int frameNo)
814 boolean isAnimationRunning = (frameNo <= -2);
817 public void notifyScriptStart(String statusMessage, String additionalInfo)
821 public void sendConsoleEcho(String strEcho)
823 if (scriptWindow != null)
824 scriptWindow.sendConsoleEcho(strEcho);
827 public void sendConsoleMessage(String strStatus)
829 if (scriptWindow != null)
830 scriptWindow.sendConsoleMessage(strStatus);
833 public void notifyScriptTermination(String strStatus, int msWalltime)
835 if (scriptWindow != null)
836 scriptWindow.notifyScriptTermination(strStatus, msWalltime);
839 public void handlePopupMenu(int x, int y)
841 jmolpopup.show(x, y);
844 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
846 notifyAtomPicked(iatom, strMeasure);
849 public void notifyNewDefaultModeMeasurement(int count, String strInfo)
853 public void notifyAtomPicked(int atomIndex, String strInfo)
855 Matcher matcher = pattern.matcher(strInfo);
859 String resnum = new String(matcher.group(2));
860 String chainId = matcher.group(3);
862 String picked = resnum;
865 picked += (":" + chainId.substring(1, chainId.length()));
869 if (!atomsPicked.contains(picked))
872 viewer.evalString("select " + picked + ";label %n %r:%c");
874 viewer.evalString("select " + picked + ";label %n %r");
875 atomsPicked.addElement(picked);
879 viewer.evalString("select " + picked + ";label off");
880 atomsPicked.removeElement(picked);
883 if (scriptWindow != null)
885 scriptWindow.sendConsoleMessage(strInfo);
886 scriptWindow.sendConsoleMessage("\n");
890 public void notifyAtomHovered(int atomIndex, String strInfo)
892 mouseOverStructure(atomIndex, strInfo);
895 public void sendSyncScript(String script, String appletName)
899 public void showUrl(String url)
903 public void showConsole(boolean showConsole)
905 if (scriptWindow == null)
906 scriptWindow = new ScriptWindow(this);
910 if (splitPane == null)
912 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
913 splitPane.setTopComponent(renderPanel);
914 splitPane.setBottomComponent(scriptWindow);
915 this.getContentPane().add(splitPane, BorderLayout.CENTER);
918 splitPane.setDividerLocation(getHeight() - 200);
919 splitPane.validate();
923 if (splitPane != null)
924 splitPane.setVisible(false);
928 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
934 public float functionXY(String functionName, int x, int y)
939 // /End JmolStatusListener
940 // /////////////////////////////
942 class RenderPanel extends JPanel
944 final Dimension currentSize = new Dimension();
946 final Rectangle rectClip = new Rectangle();
948 public void paintComponent(Graphics g)
950 getSize(currentSize);
951 g.getClipBounds(rectClip);
955 g.setColor(Color.black);
956 g.fillRect(0, 0, currentSize.width, currentSize.height);
957 g.setColor(Color.white);
958 g.setFont(new Font("Verdana", Font.BOLD, 14));
959 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
961 else if (fileLoadingError != null)
963 g.setColor(Color.black);
964 g.fillRect(0, 0, currentSize.width, currentSize.height);
965 g.setColor(Color.white);
966 g.setFont(new Font("Verdana", Font.BOLD, 14));
967 g.drawString("Error loading file..." + pdbentry.getId(), 20,
968 currentSize.height / 2);
972 viewer.renderScreenImage(g, currentSize, rectClip);
977 public String getViewId()
981 viewId=System.currentTimeMillis()+"."+this.hashCode();