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.*;
37 import org.jmol.api.*;
38 import org.jmol.adapter.smarter.SmarterJmolAdapter;
39 import org.jmol.popup.*;
43 extends GStructureViewer
44 implements StructureListener, JmolStatusListener, Runnable
49 ScriptWindow scriptWindow;
53 StructureSelectionManager ssm;
55 RenderPanel renderPanel;
57 String fileLoadingError;
58 boolean colourBySequence = true;
59 boolean loadingFromArchive = false;
60 Vector atomsPicked = new Vector();
62 public AppJmol(String file, String id,
68 loadingFromArchive = true;
69 pdbentry = new PDBEntry();
70 pdbentry.setFile(file);
75 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;
160 jalview.gui.Desktop.addInternalFrame(this, "Loading File", 400, 400);
162 if (pdbentry.getFile() != null)
164 initJmol("load \""+pdbentry.getFile()+"\"");
168 Thread worker = new Thread(this);
172 this.addInternalFrameListener(new InternalFrameAdapter()
174 public void internalFrameClosing(InternalFrameEvent internalFrameEvent)
182 void initJmol(String command)
184 renderPanel = new RenderPanel();
186 this.getContentPane().add(renderPanel, java.awt.BorderLayout.CENTER);
188 StringBuffer title = new StringBuffer(sequence[0].getName() + ":" +
191 if (pdbentry.getProperty() != null)
193 if (pdbentry.getProperty().get("method") != null)
195 title.append(" Method: ");
196 title.append(pdbentry.getProperty().get("method"));
198 if (pdbentry.getProperty().get("chains") != null)
200 title.append(" Chain:");
201 title.append(pdbentry.getProperty().get("chains"));
205 this.setTitle(title.toString());
207 viewer = org.jmol.api.JmolViewer.allocateViewer(renderPanel,
208 new SmarterJmolAdapter());
211 viewer.setAppletContext("", null, null, "");
213 viewer.setJmolStatusListener(this);
215 jmolpopup = JmolPopup.newJmolPopup(viewer);
217 viewer.evalStringQuiet(command);
221 void setChainMenuItems(Vector chains)
223 chainMenu.removeAll();
225 JMenuItem menuItem = new JMenuItem("All");
226 menuItem.addActionListener(new ActionListener()
228 public void actionPerformed(ActionEvent evt)
230 allChainsSelected = true;
231 for(int i=0; i<chainMenu.getItemCount(); i++)
233 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
234 ( (JCheckBoxMenuItem) chainMenu.getItem(i)).setSelected(true);
237 allChainsSelected = false;
241 chainMenu.add(menuItem);
243 for (int c = 0; c < chains.size(); c++)
245 menuItem = new JCheckBoxMenuItem(chains.elementAt(c).toString(), true);
246 menuItem.addItemListener(new ItemListener()
248 public void itemStateChanged(ItemEvent evt)
250 if (!allChainsSelected)
255 chainMenu.add(menuItem);
259 boolean allChainsSelected = false;
262 StringBuffer cmd = new StringBuffer();
263 for(int i=0; i<chainMenu.getItemCount(); i++)
265 if (chainMenu.getItem(i) instanceof JCheckBoxMenuItem)
267 JCheckBoxMenuItem item = (JCheckBoxMenuItem) chainMenu.getItem(i);
268 if(item.isSelected())
269 cmd.append(":"+item.getText()+" or ");
273 if (cmd.length() > 0)
274 cmd.setLength(cmd.length() - 4);
276 viewer.evalStringQuiet("select *;restrict "
277 +cmd+";cartoon;center "+cmd);
282 viewer.setModeMouse(org.jmol.viewer.JmolConstants.MOUSE_NONE);
283 viewer.evalStringQuiet("zap");
284 viewer.setJmolStatusListener(null);
287 //We'll need to find out what other
288 // listeners need to be shut down in Jmol
289 StructureSelectionManager
290 .getStructureSelectionManager()
291 .removeStructureViewerListener(this, pdbentry.getFile());
298 EBIFetchClient ebi = new EBIFetchClient();
299 String query = "pdb:" + pdbentry.getId();
300 pdbentry.setFile(ebi.fetchDataAsFile(query, "default", "raw")
302 initJmol("load "+pdbentry.getFile());
306 ex.printStackTrace();
310 public void pdbFile_actionPerformed(ActionEvent actionEvent)
312 JalviewFileChooser chooser = new JalviewFileChooser(
313 jalview.bin.Cache.getProperty(
316 chooser.setFileView(new JalviewFileView());
317 chooser.setDialogTitle("Save PDB File");
318 chooser.setToolTipText("Save");
320 int value = chooser.showSaveDialog(this);
322 if (value == JalviewFileChooser.APPROVE_OPTION)
326 BufferedReader in = new BufferedReader(new FileReader(pdbentry.getFile()));
327 File outFile = chooser.getSelectedFile();
329 PrintWriter out = new PrintWriter(new FileOutputStream(outFile));
331 while ( (data = in.readLine()) != null)
334 ! (data.indexOf("<PRE>") > -1 || data.indexOf("</PRE>") > -1)
344 ex.printStackTrace();
349 public void viewMapping_actionPerformed(ActionEvent actionEvent)
351 jalview.gui.CutAndPasteTransfer cap = new jalview.gui.CutAndPasteTransfer();
352 jalview.gui.Desktop.addInternalFrame(cap, "PDB - Sequence Mapping", 550,
355 StructureSelectionManager.getStructureSelectionManager().printMapping(
363 * @param e DOCUMENT ME!
365 public void eps_actionPerformed(ActionEvent e)
367 makePDBImage(jalview.util.ImageMaker.EPS);
373 * @param e DOCUMENT ME!
375 public void png_actionPerformed(ActionEvent e)
377 makePDBImage(jalview.util.ImageMaker.PNG);
380 void makePDBImage(int type)
382 int width = getWidth();
383 int height = getHeight();
385 jalview.util.ImageMaker im;
387 if (type == jalview.util.ImageMaker.PNG)
389 im = new jalview.util.ImageMaker(this,
390 jalview.util.ImageMaker.PNG,
391 "Make PNG image from view",
397 im = new jalview.util.ImageMaker(this,
398 jalview.util.ImageMaker.EPS,
399 "Make EPS file from view",
401 null, this.getTitle());
404 if (im.getGraphics() != null)
406 Rectangle rect = new Rectangle(width, height);
407 viewer.renderScreenImage(im.getGraphics(),
408 rect.getSize(), rect);
414 public void seqColour_actionPerformed(ActionEvent actionEvent)
417 colourBySequence = seqColour.isSelected();
418 colourBySequence(ap.alignFrame.alignPanel);
421 public void chainColour_actionPerformed(ActionEvent actionEvent)
423 colourBySequence = false;
424 seqColour.setSelected(false);
425 viewer.evalStringQuiet("select *;color chain");
428 public void chargeColour_actionPerformed(ActionEvent actionEvent)
430 colourBySequence = false;
431 seqColour.setSelected(false);
432 viewer.evalStringQuiet("select *;color white;select ASP,GLU;color red;"
433 +"select LYS,ARG;color blue;select CYS;color yellow");
436 public void zappoColour_actionPerformed(ActionEvent actionEvent)
438 setJalviewColourScheme(new ZappoColourScheme());
441 public void taylorColour_actionPerformed(ActionEvent actionEvent)
443 setJalviewColourScheme(new TaylorColourScheme());
446 public void hydroColour_actionPerformed(ActionEvent actionEvent)
448 setJalviewColourScheme(new HydrophobicColourScheme());
451 public void helixColour_actionPerformed(ActionEvent actionEvent)
453 setJalviewColourScheme(new HelixColourScheme());
456 public void strandColour_actionPerformed(ActionEvent actionEvent)
458 setJalviewColourScheme(new StrandColourScheme());
461 public void turnColour_actionPerformed(ActionEvent actionEvent)
463 setJalviewColourScheme(new TurnColourScheme());
466 public void buriedColour_actionPerformed(ActionEvent actionEvent)
468 setJalviewColourScheme(new BuriedColourScheme());
471 public void setJalviewColourScheme(ColourSchemeI cs)
473 colourBySequence = false;
474 seqColour.setSelected(false);
483 Enumeration en = ResidueProperties.aa3Hash.keys();
484 StringBuffer command = new StringBuffer("select *;color white;");
485 while(en.hasMoreElements())
487 res = en.nextElement().toString();
488 index = ((Integer) ResidueProperties.aa3Hash.get(res)).intValue();
492 col = cs.findColour(ResidueProperties.aa[index].charAt(0));
494 command.append("select "+res+";color["
496 + col.getGreen() + ","
497 + col.getBlue() + "];");
500 viewer.evalStringQuiet(command.toString());
503 public void userColour_actionPerformed(ActionEvent actionEvent)
505 new UserDefinedColours(this, null);
508 public void backGround_actionPerformed(ActionEvent actionEvent)
510 java.awt.Color col = JColorChooser.showDialog(this,
511 "Select Background Colour",
516 viewer.evalStringQuiet("background ["
518 + col.getGreen() + ","
519 + col.getBlue() + "];");
524 public void jmolHelp_actionPerformed(ActionEvent actionEvent)
527 jalview.util.BrowserLauncher.openURL(
528 "http://jmol.sourceforge.net/docs/JmolUserGuide/");
529 }catch(Exception ex){}
533 //////////////////////////////////
535 public String getPdbFile()
537 return pdbentry.getFile();
540 Pattern pattern = Pattern.compile(
541 "\\[(.*)\\]([0-9]+)(:[a-zA-Z]*)?\\.([a-zA-Z]+)(/[0-9]*)?"
545 public void mouseOverStructure(int atomIndex, String strInfo)
547 Matcher matcher = pattern.matcher(strInfo);
550 int pdbResNum = Integer.parseInt(matcher.group(2));
551 String chainId = matcher.group(3);
554 chainId = chainId.substring(1, chainId.length());
560 if (lastMessage == null || !lastMessage.equals(strInfo))
562 ssm.mouseOverStructure(pdbResNum, chainId, pdbentry.getFile());
564 lastMessage = strInfo;
567 StringBuffer resetLastRes = new StringBuffer();
568 StringBuffer eval = new StringBuffer();
570 public void highlightAtom(int atomIndex, int pdbResNum, String chain, String pdbfile)
572 if (!pdbfile.equals(pdbentry.getFile()))
575 if (resetLastRes.length() > 0)
577 viewer.evalStringQuiet(resetLastRes.toString());
581 eval.append("select " + pdbResNum);
583 resetLastRes.setLength(0);
584 resetLastRes.append("select " + pdbResNum);
586 if (!chain.equals(" "))
588 eval.append(":" + chain);
589 resetLastRes.append(":" + chain);
592 eval.append(";wireframe 100;"+eval.toString()+".CA;");
594 resetLastRes.append(";wireframe 0;"+resetLastRes.toString()+".CA;spacefill 0;");
596 eval.append("spacefill 200;select none");
598 viewer.evalStringQuiet(eval.toString());
601 public Color getColour(int atomIndex, int pdbResNum, String chain, String pdbfile)
603 if (!pdbfile.equals(pdbentry.getFile()))
606 return new Color(viewer.getAtomArgb(atomIndex));
609 public void updateColours(Object source)
611 colourBySequence( (AlignmentPanel) source);
615 //End StructureListener
616 ////////////////////////////
619 FeatureRenderer fr=null;
620 public void colourBySequence(AlignmentPanel sourceap)
624 if(!colourBySequence || ap.alignFrame.getCurrentView()!=ap.av)
627 StructureMapping[] mapping = ssm.getMapping(pdbentry.getFile());
629 if (mapping.length < 1)
633 SequenceRenderer sr = new SequenceRenderer(ap.av);
635 boolean showFeatures = false;
637 if (ap.av.showSequenceFeatures)
642 fr = new jalview.gui.FeatureRenderer(ap);
645 fr.transferSettings(ap.seqPanel.seqCanvas.getFeatureRenderer());
648 StringBuffer command = new StringBuffer();
651 for (int s = 0; s < sequence.length; s++)
653 for (int m = 0; m < mapping.length; m++)
655 if (mapping[m].getSequence() == sequence[s]
656 && ap.av.alignment.findIndex(sequence[s])>-1)
658 for (int r = 0; r < sequence[s].getLength(); r++)
660 int pos = mapping[m].getPDBResNum(
661 sequence[s].findPosition(r));
663 if (pos < 1 || pos==lastPos)
668 Color col = sr.getResidueBoxColour(sequence[s], r);
671 col = fr.findFeatureColour(col, sequence[s], r);
673 if (command.toString().endsWith(":" + mapping[m].getChain()+
676 + col.getGreen() + ","
677 + col.getBlue() + "]"))
679 command = condenseCommand(command, pos);
683 command.append(";select " + pos);
685 if (!mapping[m].getChain().equals(" "))
687 command.append(":" + mapping[m].getChain());
690 command.append(";color["
692 + col.getGreen() + ","
693 + col.getBlue() + "]");
701 if (lastCommand == null || !lastCommand.equals(command.toString()))
703 viewer.evalStringQuiet(command.toString());
705 lastCommand = command.toString();
708 StringBuffer condenseCommand(StringBuffer command, int pos)
710 StringBuffer sb = new StringBuffer(command.substring(0, command.lastIndexOf("select")+7));
712 command.delete(0, sb.length());
716 if (command.indexOf("-") > -1)
718 start = command.substring(0,command.indexOf("-"));
722 start = command.substring(0, command.indexOf(":"));
725 sb.append(start+"-"+pos+command.substring(command.indexOf(":")));
730 /////////////////////////////////
733 public String eval(String strEval)
735 // System.out.println(strEval);
736 //"# 'eval' is implemented only for the applet.";
740 public void createImage(String file, String type, int quality)
742 System.out.println("JMOL CREATE IMAGE");
745 public void setCallbackFunction(String callbackType,
746 String callbackFunction)
749 public void notifyFileLoaded(String fullPathName, String fileName,
750 String modelName, Object clientFile,
755 fileLoadingError = errorMsg;
760 fileLoadingError = null;
762 if (fileName != null)
766 ssm = StructureSelectionManager.getStructureSelectionManager();
767 MCview.PDBfile pdbFile = ssm.setMapping(sequence,chains,pdbentry.getFile(), AppletFormatAdapter.FILE);
768 ssm.addStructureViewerListener(this);
769 Vector chains = new Vector();
770 for(int i=0; i<pdbFile.chains.size(); i++)
772 chains.addElement(((MCview.PDBChain)pdbFile.chains.elementAt(i)).id);
774 setChainMenuItems(chains);
776 jmolpopup.updateComputedMenus();
778 if(!loadingFromArchive)
780 viewer.evalStringQuiet(
781 "select backbone;restrict;cartoon;wireframe off;spacefill off");
783 colourBySequence(ap);
788 viewer.evalStringQuiet("set picking label");
790 loadingFromArchive = false;
796 public void notifyFrameChanged(int frameNo)
798 boolean isAnimationRunning = (frameNo <= -2);
801 public void notifyScriptStart(String statusMessage, String additionalInfo)
804 public void sendConsoleEcho(String strEcho)
806 if (scriptWindow != null)
807 scriptWindow.sendConsoleEcho(strEcho);
810 public void sendConsoleMessage(String strStatus)
812 if (scriptWindow != null)
813 scriptWindow.sendConsoleMessage(strStatus);
816 public void notifyScriptTermination(String strStatus, int msWalltime)
818 if (scriptWindow != null)
819 scriptWindow.notifyScriptTermination(strStatus, msWalltime);
822 public void handlePopupMenu(int x, int y)
824 jmolpopup.show(x, y);
827 public void notifyNewPickingModeMeasurement(int iatom, String strMeasure)
829 notifyAtomPicked(iatom, strMeasure);
832 public void notifyNewDefaultModeMeasurement(int count, String strInfo)
835 public void notifyAtomPicked(int atomIndex, String strInfo)
837 Matcher matcher = pattern.matcher(strInfo);
841 String resnum = new String(matcher.group(2));
842 String chainId = matcher.group(3);
844 String picked = resnum;
847 picked+=(":"+chainId.substring(1, chainId.length()));
852 if (!atomsPicked.contains(picked))
855 viewer.evalString("select "+picked+";label %n %r:%c");
857 viewer.evalString("select "+picked+";label %n %r");
858 atomsPicked.addElement(picked);
862 viewer.evalString("select "+picked+";label off");
863 atomsPicked.removeElement(picked);
866 if (scriptWindow != null)
868 scriptWindow.sendConsoleMessage(strInfo);
869 scriptWindow.sendConsoleMessage("\n");
873 public void notifyAtomHovered(int atomIndex, String strInfo)
875 mouseOverStructure(atomIndex, strInfo);
878 public void sendSyncScript(String script, String appletName)
881 public void showUrl(String url)
884 public void showConsole(boolean showConsole)
886 if (scriptWindow == null)
887 scriptWindow = new ScriptWindow(this);
893 splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
894 splitPane.setTopComponent(renderPanel);
895 splitPane.setBottomComponent(scriptWindow);
896 this.getContentPane().add(splitPane, BorderLayout.CENTER);
899 splitPane.setDividerLocation(getHeight()-200);
900 splitPane.validate();
904 if (splitPane != null)
905 splitPane.setVisible(false);
909 this.getContentPane().add(renderPanel, BorderLayout.CENTER);
915 public float functionXY(String functionName, int x, int y)
920 ///End JmolStatusListener
921 ///////////////////////////////
927 final Dimension currentSize = new Dimension();
928 final Rectangle rectClip = new Rectangle();
930 public void paintComponent(Graphics g)
932 getSize(currentSize);
933 g.getClipBounds(rectClip);
937 g.setColor(Color.black);
938 g.fillRect(0, 0, currentSize.width, currentSize.height);
939 g.setColor(Color.white);
940 g.setFont(new Font("Verdana", Font.BOLD, 14));
941 g.drawString("Retrieving PDB data....", 20, currentSize.height / 2);
943 else if(fileLoadingError!=null)
945 g.setColor(Color.black);
946 g.fillRect(0, 0, currentSize.width, currentSize.height);
947 g.setColor(Color.white);
948 g.setFont(new Font("Verdana", Font.BOLD, 14));
949 g.drawString("Error loading file..." + pdbentry.getId(), 20,
950 currentSize.height / 2);
954 viewer.renderScreenImage(g, currentSize, rectClip);