2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2007 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.*;
44 extends GStructureViewer
45 implements StructureListener, JmolStatusListener, Runnable
50 ScriptWindow scriptWindow;
54 StructureSelectionManager ssm;
56 RenderPanel renderPanel;
58 String fileLoadingError;
59 boolean colourBySequence = true;
60 boolean loadingFromArchive = false;
61 Vector atomsPicked = new Vector();
63 public AppJmol(String file, String id,
69 loadingFromArchive = true;
70 pdbentry = new PDBEntry();
71 pdbentry.setFile(file);
76 this.setBounds(bounds);
77 colourBySequence = false;
78 seqColour.setSelected(false);
80 //jalview.gui.Desktop.addInternalFrame(this, "Loading File",
81 // bounds.width,bounds.height);
85 this.addInternalFrameListener(new InternalFrameAdapter()
87 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
94 public synchronized void addSequence(SequenceI [] seq)
96 Vector v = new Vector();
97 for(int i=0; i<sequence.length; i++)
98 v.addElement(sequence[i]);
100 for(int i=0; i<seq.length; i++)
101 if(!v.contains(seq[i]))
102 v.addElement(seq[i]);
104 SequenceI [] tmp = new SequenceI[v.size()];
109 public AppJmol(PDBEntry pdbentry, SequenceI[] seq, String [] chains, AlignmentPanel ap)
111 //////////////////////////////////
112 //Is the pdb file already loaded?
113 String alreadyMapped = StructureSelectionManager
114 .getStructureSelectionManager()
115 .alreadyMappedToFile(pdbentry.getId());
117 if (alreadyMapped != null)
119 int option = JOptionPane.showInternalConfirmDialog(Desktop.desktop,
120 pdbentry.getId() + " is already displayed."
121 + "\nDo you want to map sequences to the visible structure?",
122 "Map Sequences to Visible Window: " + pdbentry.getId(),
123 JOptionPane.YES_NO_OPTION);
125 if (option == JOptionPane.YES_OPTION)
127 StructureSelectionManager.getStructureSelectionManager()
128 .setMapping(seq, chains, alreadyMapped, AppletFormatAdapter.FILE);
129 if (ap.seqPanel.seqCanvas.fr!=null) {
130 ap.seqPanel.seqCanvas.fr.featuresAdded();
131 ap.paintAlignment(true);
134 //Now this AppJmol is mapped to new sequences. We must add them to
135 // the exisiting array
136 JInternalFrame [] frames = Desktop.instance.getAllFrames();
138 for(int i=0; i<frames.length; i++)
140 if(frames[i] instanceof AppJmol)
142 AppJmol topJmol = ((AppJmol)frames[i]);
143 if(topJmol.pdbentry.getFile().equals(alreadyMapped))
145 topJmol.addSequence(seq);
154 ///////////////////////////////////
157 this.pdbentry = pdbentry;
159 this.setSize(400,400);
160 //jalview.gui.Desktop.addInternalFrame(this, "Jmol View"+(pdbentry.getId()!=null ? "for "+pdbentry.getId()
163 if (pdbentry.getFile() != null)
165 initJmol("load \""+pdbentry.getFile()+"\"");
169 Thread worker = new Thread(this);
173 this.addInternalFrameListener(new InternalFrameAdapter()
175 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
183 void initJmol(String command)
185 renderPanel = new RenderPanel();
187 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
189 StringBuffer title = new StringBuffer(sequence[0].getName() + ":" +
192 if (pdbentry.getProperty() != null)
194 if (pdbentry.getProperty().get("method") != null)
196 title.append(" Method: ");
197 title.append(pdbentry.getProperty().get("method"));
199 if (pdbentry.getProperty().get("chains") != null)
201 title.append(" Chain:");
202 title.append(pdbentry.getProperty().get("chains"));
206 this.setTitle(title.toString());
207 jalview.gui.Desktop.addInternalFrame(this, title.toString(),
208 getBounds().width,getBounds().height);
210 viewer = org.jmol.api.JmolViewer.allocateViewer(renderPanel,
211 new SmarterJmolAdapter());
214 viewer.setAppletContext("", null, null, "");
216 viewer.setJmolStatusListener(this);
218 jmolpopup = JmolPopup.newJmolPopup(viewer);
220 viewer.evalStringQuiet(command);
224 void setChainMenuItems(Vector chains)
226 chainMenu.removeAll();
228 JMenuItem menuItem = new JMenuItem("All");
229 menuItem.addActionListener(new ActionListener()
231 public void actionPerformed(ActionEvent evt)
233 allChainsSelected = true;
234 for(int i=0; i<chainMenu.getItemCount(); i++)
236 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
237 ( (JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
240 allChainsSelected = false;
244 chainMenu.add(menuItem);
246 for (int c = 0; c < chains.size(); c++)
248 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
249 menuItem.addItemListener(new ItemListener()
251 public void itemStateChanged(ItemEvent evt)
253 if (!allChainsSelected)
258 chainMenu.add(menuItem);
262 boolean allChainsSelected = false;
265 StringBuffer cmd = new StringBuffer();
266 for(int i=0; i<chainMenu.getItemCount(); i++)
268 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
270 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
271 if(item.isSelected())
272 cmd.append(":"+item.getText()+" or ");
276 if (cmd.length() > 0)
277 cmd.setLength(cmd.length() - 4);
279 viewer.evalStringQuiet("select *;restrict "
280 +cmd+";cartoon;center "+cmd);
285 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
286 viewer.evalStringQuiet("zap");
287 viewer.setJmolStatusListener(null);
290 //We'll need to find out what other
291 // listeners need to be shut down in Jmol
292 StructureSelectionManager
293 .getStructureSelectionManager()
294 .removeStructureViewerListener(this, pdbentry.getFile());
301 EBIFetchClient ebi = new EBIFetchClient();
302 String query = "pdb:" + pdbentry.getId();
303 pdbentry.setFile(ebi.fetchDataAsFile(query, "default", "raw")
305 initJmol("load "+pdbentry.getFile());
309 ex.printStackTrace();
313 public void pdbFile_actionPerformed(ActionEvent actionEvent)
315 JalviewFileChooser chooser = new JalviewFileChooser(
316 jalview.bin.Cache.getProperty(
319 chooser.setFileView(new JalviewFileView());
320 chooser.setDialogTitle("Save PDB File");
321 chooser.setToolTipText("Save");
323 int value = chooser.showSaveDialog(this);
325 if (value == JalviewFileChooser.APPROVE_OPTION)
329 BufferedReader in = new BufferedReader(new FileReader(pdbentry.getFile()));
330 File outFile = chooser.getSelectedFile();
332 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
334 while ( (data = in.readLine()) != null)
337 ! (data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1)
347 ex.printStackTrace();
352 public void viewMapping_actionPerformed(ActionEvent actionEvent)
354 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
355 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping", 550,
358 StructureSelectionManager.getStructureSelectionManager().printMapping(
366 * @param e DOCUMENT ME!
368 public void eps_actionPerformed(ActionEvent e)
370 makePDBImage(jalview.util.ImageMaker.EPS);
376 * @param e DOCUMENT ME!
378 public void png_actionPerformed(ActionEvent e)
380 makePDBImage(jalview.util.ImageMaker.PNG);
383 void makePDBImage(int type)
385 int width = getWidth();
386 int height = getHeight();
388 jalview.util.ImageMaker im;
390 if (type == jalview.util.ImageMaker.PNG)
392 im = new jalview.util.ImageMaker(this,
393 jalview.util.ImageMaker.PNG,
394 "Make PNG image from view",
400 im = new jalview.util.ImageMaker(this,
401 jalview.util.ImageMaker.EPS,
402 "Make EPS file from view",
404 null, this.getTitle());
407 if (im.getGraphics() != null)
409 Rectangle rect = new Rectangle(width, height);
410 viewer.renderScreenImage(im.getGraphics(),
411 rect.getSize(), rect);
417 public void seqColour_actionPerformed(ActionEvent actionEvent)
420 colourBySequence = seqColour.isSelected();
421 colourBySequence(ap.alignFrame.alignPanel);
424 public void chainColour_actionPerformed(ActionEvent actionEvent)
426 colourBySequence = false;
427 seqColour.setSelected(false);
428 viewer.evalStringQuiet("select *;color chain");
431 public void chargeColour_actionPerformed(ActionEvent actionEvent)
433 colourBySequence = false;
434 seqColour.setSelected(false);
435 viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
436 +"select LYS,ARG;color blue;select CYS;color yellow");
439 public void zappoColour_actionPerformed(ActionEvent actionEvent)
441 setJalviewColourScheme(new ZappoColourScheme());
444 public void taylorColour_actionPerformed(ActionEvent actionEvent)
446 setJalviewColourScheme(new TaylorColourScheme());
449 public void hydroColour_actionPerformed(ActionEvent actionEvent)
451 setJalviewColourScheme(new HydrophobicColourScheme());
454 public void helixColour_actionPerformed(ActionEvent actionEvent)
456 setJalviewColourScheme(new HelixColourScheme());
459 public void strandColour_actionPerformed(ActionEvent actionEvent)
461 setJalviewColourScheme(new StrandColourScheme());
464 public void turnColour_actionPerformed(ActionEvent actionEvent)
466 setJalviewColourScheme(new TurnColourScheme());
469 public void buriedColour_actionPerformed(ActionEvent actionEvent)
471 setJalviewColourScheme(new BuriedColourScheme());
474 public void setJalviewColourScheme(ColourSchemeI cs)
476 colourBySequence = false;
477 seqColour.setSelected(false);
486 Enumeration en = ResidueProperties.aa3Hash.keys();
487 StringBuffer command = new StringBuffer("select *;color white;");
488 while(en.hasMoreElements())
490 res = en.nextElement().toString();
491 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
495 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
497 command.append("select "+res+";color["
499 + col.getGreen() + ","
500 + col.getBlue() + "];");
503 viewer.evalStringQuiet(command.toString());
506 public void userColour_actionPerformed(ActionEvent actionEvent)
508 new UserDefinedColours(this, null);
511 public void backGround_actionPerformed(ActionEvent actionEvent)
513 java.awt.Color col = JColorChooser.showDialog(this,
514 "Select Background Colour",
519 viewer.evalStringQuiet("background ["
521 + col.getGreen() + ","
522 + col.getBlue() + "];");
527 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
530 jalview.util.BrowserLauncher.openURL(
531 "http://jmol.sourceforge.net/docs/JmolUserGuide/");
532 }catch(Exception ex){}
536 //////////////////////////////////
538 public String getPdbFile()
540 return pdbentry.getFile();
543 Pattern pattern = Pattern.compile(
544 "\\[(.*)\\]([0-9]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?"
548 public void mouseOverStructure(int atomIndex, String strInfo)
550 Matcher matcher = pattern.matcher(strInfo);
553 int pdbResNum = Integer.parseInt(matcher.group(2));
554 String chainId = matcher.group(3);
557 chainId = chainId.substring(1, chainId.length());
563 if (lastMessage == null || !lastMessage.equals(strInfo))
565 ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile());
567 lastMessage = strInfo;
570 StringBuffer resetLastRes = new StringBuffer();
571 StringBuffer eval = new StringBuffer();
573 public void highlightAtom(int atomIndex, int pdbResNum, String chain, String pdbfile)
575 if (!pdbfile.equals(pdbentry.getFile()))
578 if (resetLastRes.length() > 0)
580 viewer.evalStringQuiet(resetLastRes.toString());
584 eval.append("select " + pdbResNum);
586 resetLastRes.setLength(0);
587 resetLastRes.append("select " + pdbResNum);
589 if (!chain.equals(" "))
591 eval.append(":" + chain);
592 resetLastRes.append(":" + chain);
595 eval.append(";wireframe 100;"+eval.toString()+".CA;");
597 resetLastRes.append(";wireframe 0;"+resetLastRes.toString()+".CA;spacefill 0;");
599 eval.append("spacefill 200;select none");
601 viewer.evalStringQuiet(eval.toString());
604 public Color getColour(int atomIndex, int pdbResNum, String chain, String pdbfile)
606 if (!pdbfile.equals(pdbentry.getFile()))
609 return new Color(viewer.getAtomArgb(atomIndex));
612 public void updateColours(Object source)
614 colourBySequence( (AlignmentPanel) source);
618 //End StructureListener
619 ////////////////////////////
622 FeatureRenderer fr=null;
623 public void colourBySequence(AlignmentPanel sourceap)
627 if(!colourBySequence || ap.alignFrame.getCurrentView()!=ap.av)
630 StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
632 if (mapping.length < 1)
636 SequenceRenderer sr = new SequenceRenderer(ap.av);
638 boolean showFeatures = false;
640 if (ap.av.showSequenceFeatures)
645 fr = new jalview.gui.FeatureRenderer(ap);
648 fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
651 StringBuffer command = new StringBuffer();
654 for (int sp,s = 0; s < sequence.length; s++)
656 for (int m = 0; m < mapping.length; m++)
658 if (mapping[m].getSequence() == sequence[s]
659 && (sp=ap.av.alignment.findIndex(sequence[s]))>-1)
661 SequenceI asp = ap.av.alignment.getSequenceAt(sp);
662 for (int r = 0; r < asp.getLength(); r++)
664 // No mapping to gaps in sequence.
665 if (jalview.util.Comparison.isGap(asp.getCharAt(r)))
669 int pos = mapping[m].getPDBResNum(
670 asp.findPosition(r));
672 if (pos < 1 || pos==lastPos)
677 Color col = sr.getResidueBoxColour(asp, r);
680 col = fr.findFeatureColour(col, asp, r);
682 if (command.toString().endsWith(":" + mapping[m].getChain()+
685 + col.getGreen() + ","
686 + col.getBlue() + "]"))
688 command = condenseCommand(command, pos);
692 command.append(";select " + pos);
694 if (!mapping[m].getChain().equals(" "))
696 command.append(":" + mapping[m].getChain());
699 command.append(";color["
701 + col.getGreen() + ","
702 + col.getBlue() + "]");
710 if (lastCommand == null || !lastCommand.equals(command.toString()))
712 viewer.evalStringQuiet(command.toString());
714 lastCommand = command.toString();
717 StringBuffer condenseCommand(StringBuffer command, int pos)
719 StringBuffer sb = new StringBuffer(command.substring(0, command.lastIndexOf("select")+7));
721 command.delete(0, sb.length());
725 if (command.indexOf("-") > -1)
727 start = command.substring(0,command.indexOf("-"));
731 start = command.substring(0, command.indexOf(":"));
734 sb.append(start+"-"+pos+command.substring(command.indexOf(":")));
739 /////////////////////////////////
742 public String eval(String strEval)
744 // System.out.println(strEval);
745 //"# 'eval' is implemented only for the applet.";
749 public void createImage(String file, String type, int quality)
751 System.out.println("JMOL CREATE IMAGE");
754 public void setCallbackFunction(String callbackType,
755 String callbackFunction)
758 public void notifyFileLoaded(String fullPathName, String fileName,
759 String modelName, Object clientFile,
764 fileLoadingError = errorMsg;
769 fileLoadingError = null;
771 if (fileName != null)
775 ssm = StructureSelectionManager.getStructureSelectionManager();
776 MCview.PDBfile pdbFile = ssm.setMapping(sequence,chains,pdbentry.getFile(), AppletFormatAdapter.FILE);
777 ssm.addStructureViewerListener(this);
778 Vector chains = new Vector();
779 for(int i=0; i<pdbFile.chains.size(); i++)
781 chains.addElement(((MCview.PDBChain)pdbFile.chains.elementAt(i)).id);
783 setChainMenuItems(chains);
785 jmolpopup.updateComputedMenus();
787 if(!loadingFromArchive)
789 viewer.evalStringQuiet(
790 "select backbone;restrict;cartoon;wireframe off;spacefill off");
792 colourBySequence(ap);
797 loadingFromArchive = false;
803 public void notifyFrameChanged(int frameNo)
805 boolean isAnimationRunning = (frameNo <= -2);
808 public void notifyScriptStart(String statusMessage, String additionalInfo)
811 public void sendConsoleEcho(String strEcho)
813 if (scriptWindow != null)
814 scriptWindow.sendConsoleEcho(strEcho);
817 public void sendConsoleMessage(String strStatus)
819 if (scriptWindow != null)
820 scriptWindow.sendConsoleMessage(strStatus);
823 public void notifyScriptTermination(String strStatus, int msWalltime)
825 if (scriptWindow != null)
826 scriptWindow.notifyScriptTermination(strStatus, msWalltime);
829 public void handlePopupMenu(int x, int y)
831 jmolpopup.show(x, y);
834 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
836 notifyAtomPicked(iatom, strMeasure);
839 public void notifyNewDefaultModeMeasurement(int count, String strInfo)
842 public void notifyAtomPicked(int atomIndex, String strInfo)
844 Matcher matcher = pattern.matcher(strInfo);
848 String resnum = new String(matcher.group(2));
849 String chainId = matcher.group(3);
851 String picked = resnum;
854 picked+=(":"+chainId.substring(1, chainId.length()));
859 if (!atomsPicked.contains(picked))
862 viewer.evalString("select "+picked+";label %n %r:%c");
864 viewer.evalString("select "+picked+";label %n %r");
865 atomsPicked.addElement(picked);
869 viewer.evalString("select "+picked+";label off");
870 atomsPicked.removeElement(picked);
873 if (scriptWindow != null)
875 scriptWindow.sendConsoleMessage(strInfo);
876 scriptWindow.sendConsoleMessage("\n");
880 public void notifyAtomHovered(int atomIndex, String strInfo)
882 mouseOverStructure(atomIndex, strInfo);
885 public void sendSyncScript(String script, String appletName)
888 public void showUrl(String url)
891 public void showConsole(boolean showConsole)
893 if (scriptWindow == null)
894 scriptWindow = new ScriptWindow(this);
900 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
901 splitPane.setTopComponent(renderPanel);
902 splitPane.setBottomComponent(scriptWindow);
903 this.getContentPane().add(splitPane, BorderLayout.CENTER);
906 splitPane.setDividerLocation(getHeight()-200);
907 splitPane.validate();
911 if (splitPane != null)
912 splitPane.setVisible(false);
916 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
922 public float functionXY(String functionName, int x, int y)
927 ///End JmolStatusListener
928 ///////////////////////////////
934 final Dimension currentSize = new Dimension();
935 final Rectangle rectClip = new Rectangle();
937 public void paintComponent(Graphics g)
939 getSize(currentSize);
940 g.getClipBounds(rectClip);
944 g.setColor(Color.black);
945 g.fillRect(0, 0, currentSize.width, currentSize.height);
946 g.setColor(Color.white);
947 g.setFont(new Font("Verdana", Font.BOLD, 14));
948 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
950 else if(fileLoadingError!=null)
952 g.setColor(Color.black);
953 g.fillRect(0, 0, currentSize.width, currentSize.height);
954 g.setColor(Color.white);
955 g.setFont(new Font("Verdana", Font.BOLD, 14));
956 g.drawString("Error loading file..." + pdbentry.getId(), 20,
957 currentSize.height / 2);
961 viewer.renderScreenImage(g, currentSize, rectClip);